List of usage examples for com.lowagie.text Document addAuthor
public boolean addAuthor(String author)
From source file:ambit2.data.qmrf.Qmrf_Xml_Pdf.java
License:Open Source License
public void xml2pdf(InputSource xml, OutputStream pdf) { try {/*from ww w .ja v a 2 s . co m*/ Document document = new Document(PageSize.A4, 80, 50, 30, 65); PdfWriter writer = PdfWriter.getInstance(document, pdf); //writer.setViewerPreferences(PdfWriter.HideMenubar| PdfWriter.HideToolbar); writer.setViewerPreferences(PdfWriter.PageModeUseThumbs | PdfWriter.PageModeUseOutlines); //PdfOutline root = writer.getDirectContent().getRootOutline(); //new PdfOutline(root, new PDFAction("http://nina.acad.bg/qmrf"), "a bookmark"); //writer.addFileAttachment(arg0, arg1, arg2, arg3) if (docBuilder == null) docBuilder = docBuilderFactory.newDocumentBuilder(); docBuilder.setErrorHandler(new SimpleErrorHandler(getClass().getName())); QMRFSchemaResolver resolver = new QMRFSchemaResolver("http://ambit2.acad.bg/qmrf/qmrf.dtd", null); resolver.setIgnoreSystemID(true); docBuilder.setEntityResolver(resolver); org.w3c.dom.Document doc = null; try { doc = docBuilder.parse(xml); } catch (Exception x) { document.addCreationDate(); document.addCreator(getClass().getName()); document.open(); document.add(new Paragraph(new Chunk(x.getMessage()))); document.close(); return; } document.addCreationDate(); document.addCreator(getClass().getName()); document.addKeywords(replaceTags(findNodeValue("keywords", doc))); document.addTitle(replaceTags(findNodeValue("QSAR_title", doc))); try { NodeList info = doc.getElementsByTagName("QMRF"); for (int i = 0; i < info.getLength(); i++) document.addSubject(findAttributeValue("name", info.item(i)) + '.' + findAttributeValue("version", info.item(i))); } catch (Exception x) { document.addSubject("QMRF"); } try { document.addAuthor(listNodeAttributes(doc, "qmrf_authors", "author_ref", "author", att_author, new Boolean(true))); } catch (Exception x) { document.addAuthor(getClass().getName()); } document.open(); PdfContentByte cb = writer.getDirectContent(); try { headerTable(document, doc); } catch (Exception x) { document.add(new Paragraph(new Chunk(x.getMessage()))); document.close(); return; } PdfOutline root = writer.getDirectContent().getRootOutline(); for (int i = 0; i < subchapters.length; i++) try { int align = Paragraph.ALIGN_LEFT; if (Mode.chapter == (Mode) subchapters[i][2]) { document.add(new Paragraph(new Chunk('\n'))); PdfPTable table = new PdfPTable(1); table.setWidthPercentage(100); StringBuffer b = new StringBuffer(); b.append(findAttributeValue(subchapters[i][0].toString(), xml_attribute_chapter, doc)); b.append('.'); b.append(findAttributeValue(subchapters[i][0].toString(), xml_attribute_name, doc)); String bookmark = b.toString(); Chunk title = new Chunk(bookmark); title.setLocalDestination(bookmark); title.setFont(bfont); PdfDestination destination = new PdfDestination(PdfDestination.FITH); PdfOutline outline = new PdfOutline(root, destination, bookmark); Paragraph p = new Paragraph(title); PdfPCell cell = new PdfPCell(p); cell.setBackgroundColor(chapterColor); table.addCell(cell); document.add(table); float pos = writer.getVerticalPosition(false); if (pos < 90) document.newPage(); } else { Phrase phrase = new Phrase(); switch ((Mode) subchapters[i][2]) { case title: { StringBuffer b = new StringBuffer(); String cn = findAttributeValue(subchapters[i][0].toString(), xml_attribute_chapter, doc); if (cn == null) break; b.append(findAttributeValue(subchapters[i][0].toString(), xml_attribute_chapter, doc)); b.append('.'); b.append(findAttributeValue(subchapters[i][0].toString(), xml_attribute_name, doc)); String subchapterBookmark = b.toString(); b.append(':'); Chunk title = new Chunk(b.toString()); title.setLocalDestination(subchapterBookmark); title.setFont(bfont); phrase.add(title); PdfDestination destination = new PdfDestination(PdfDestination.FITBH); PdfOutline outline = new PdfOutline(root, destination, subchapterBookmark); break; } case text: { createNodePhrase(subchapters[i][0].toString(), doc, phrase, font); align = Paragraph.ALIGN_JUSTIFIED; break; } case answer: { String a = findAnswer(subchapters[i][0].toString(), doc); if (a != null) { Chunk answer = new Chunk(a); answer.setFont(font); phrase.add(answer); } break; } case dataset: { StringBuffer b = new StringBuffer(); b.append(findDataAvailable(subchapters[i][0].toString(), doc)); Chunk dataset = new Chunk(b.toString()); dataset.setFont(font); phrase.add(dataset); break; } case attachments: { PdfPTable table = getAttachmentsAsTable(doc, "attachment_training_data"); if (table != null) { phrase.add(new Paragraph("Training set(s)")); phrase.add(table); } table = getAttachmentsAsTable(doc, "attachment_validation_data"); if (table != null) { phrase.add(new Paragraph("Test set(s)")); phrase.add(table); } table = getAttachmentsAsTable(doc, "attachment_documents"); if (table != null) { phrase.add(new Paragraph("Supporting information")); phrase.add(table); } break; /* StringBuffer b = new StringBuffer(); b.append("Training set(s)\n"); b.append(listAttachments(doc,"attachment_training_data")); b.append("Test set(s)\n"); b.append(listAttachments(doc,"attachment_validation_data")); b.append("Supporting information\n"); b.append(listAttachments(doc,"attachment_documents")); Chunk attachments = new Chunk(b.toString()); attachments.setFont(font); phrase.add(attachments); break; */ } case reference: { try { String value = listNodeAttributes(doc, subchapters[i][0].toString(), subchapters[i][3].toString(), subchapters[i][4].toString(), (String[]) subchapters[i][5], (Boolean) subchapters[i][6]); Chunk reference = new Chunk(value); reference.setFont(font); align = Paragraph.ALIGN_JUSTIFIED; phrase.add(reference); } catch (Exception x) { } break; } } Paragraph p = new Paragraph(phrase); p.setAlignment(align); document.add(p); float pos = writer.getVerticalPosition(false); /* cb.moveTo(0, pos); cb.lineTo(PageSize.A4.width(), pos); cb.stroke(); */ if (pos < 90) document.newPage(); } } catch (Exception x) { x.printStackTrace(); } document.close(); } catch (Exception e) { e.printStackTrace(); System.err.println(e.getMessage()); } }
From source file:ambit2.db.reporters.PDFReporter.java
public void header(Document output, Q query) { output.addCreationDate();// w w w . ja v a 2 s.c om output.addCreator(getClass().getName()); output.addSubject(""); output.addAuthor("http://ambit.sourceforge.net"); output.addHeader("License", getLicenseURI()); output.addTitle(query.toString()); output.addKeywords(query.toString()); if (getLicenseURI() != null) { HeaderFooter footer = new HeaderFooter(new Phrase(String.format("License %s", getLicenseURI())), false); footer.setAlignment(Element.ALIGN_CENTER); output.setFooter(footer); } output.open(); font = new Font(Font.TIMES_ROMAN, 10, Font.NORMAL); table = new PdfPTable(new float[] { 3f, 5f }); table.setWidthPercentage(100); try { writeHeader(output); } catch (Exception x) { } }
From source file:at.granul.mason.collector.ChartFileScalarDataWriter.java
License:Open Source License
public static void exportGraph(XYChartGenerator chart, String prefix, int width, int height) { try {//from ww w. ja va 2s . com Document document = new Document(new com.lowagie.text.Rectangle(width, height)); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(prefix + "_" + DataWriter.DF.format(new Date()) + ".pdf"))); document.addAuthor("MASON"); document.open(); PdfContentByte cb = writer.getDirectContent(); //PdfTemplate tp = cb.createTemplate(width, height); //Write the chart with all datasets chart.addLegend(); /*LegendTitle title = new LegendTitle(chart.getChart().getPlot()); title.setLegendItemGraphicPadding(new org.jfree.ui.RectangleInsets(0,8,0,4)); chart.addLegend(title);*/ LegendTitle legendTitle = chart.getChart().getLegend(); legendTitle.setPosition(RectangleEdge.BOTTOM); Graphics2D g2 = cb.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height); chart.getChart().draw(g2, rectangle2D); g2.dispose(); //PNG Output ChartUtilities.saveChartAsJPEG(new File(prefix + "_" + DataWriter.DF.format(new Date()) + ".png"), chart.getChart(), width, height); chart.getChart().removeLegend(); //tp = cb.createTemplate(width, height); //All invisible final XYItemRenderer renderer = chart.getChartPanel().getChart().getXYPlot().getRenderer(); for (int a = 0; a < chart.getSeriesCount(); a++) { renderer.setSeriesVisible(a, false); } final Dataset seriesDataset = chart.getSeriesDataset(); XYSeriesCollection series = ((XYSeriesCollection) seriesDataset); for (int a = 0; a < chart.getSeriesCount(); a++) { renderer.setSeriesVisible(a, true); final String seriesName = series.getSeries(a).getKey() + ""; chart.setYAxisLabel(seriesName); document.newPage(); g2 = cb.createGraphics(width, height * (a + 2), new DefaultFontMapper()); g2.translate(0, height * (a + 1)); chart.getChart().draw(g2, rectangle2D); g2.dispose(); //PNG Output ChartUtilities.saveChartAsJPEG( new File(prefix + "_" + seriesName + DataWriter.DF.format(new Date()) + ".png"), chart.getChart(), width, height); renderer.setSeriesVisible(a, false); } //cb.addTemplate(tp, 0, 0); document.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:br.com.nfsconsultoria.azcontrole.bean.VendaBean.java
public void preProcessPDF(Object document) throws IOException, BadElementException, DocumentException { Document pdf = (Document) document; pdf.setPageSize(PageSize.A4);/*w ww. j a v a 2s . c om*/ pdf.addAuthor("Luis Carlos Santos"); pdf.addTitle("Acordo Cadastrados"); pdf.addCreator("NFS Consultoria"); pdf.addSubject("Acordo Cadastrados"); pdf.open(); Font catFont = new Font(Font.TIMES_ROMAN, 18, Font.BOLD); Paragraph p = new Paragraph("Relatrio de Acordos", catFont); p.setAlignment(Element.ALIGN_CENTER); p.setSpacingAfter(20); ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext(); String logo = externalContext.getRealPath("") + File.separator + "resources" + File.separator + "images" + File.separator + "banner.png"; pdf.add(Image.getInstance(logo)); pdf.add(p); }
From source file:br.com.nordestefomento.jrimum.utilix.PDFUtil.java
License:Apache License
/** * <p>/* w ww . j a va2 s.c o m*/ * Junta varios arquivos pdf em um soh. * </p> * * @param pdfFiles * Lista de array de bytes * * @return Arquivo PDF em forma de byte * @since 0.2 */ @SuppressWarnings("unchecked") public static byte[] mergeFiles(List<byte[]> pdfFiles) { // retorno byte[] bytes = null; if (isNotNull(pdfFiles) && !pdfFiles.isEmpty()) { int pageOffset = 0; boolean first = true; ArrayList master = null; Document document = null; PdfCopy writer = null; ByteArrayOutputStream byteOS = null; try { byteOS = new ByteArrayOutputStream(); master = new ArrayList(); for (byte[] doc : pdfFiles) { if (isNotNull(doc)) { // cria-se um reader para cada documento PdfReader reader = new PdfReader(doc); if (reader.isEncrypted()) { reader = new PdfReader(doc, "".getBytes()); } reader.consolidateNamedDestinations(); // pega-se o numero total de paginas int n = reader.getNumberOfPages(); List bookmarks = SimpleBookmark.getBookmark(reader); if (isNotNull(bookmarks)) { if (pageOffset != 0) { SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null); } master.addAll(bookmarks); } pageOffset += n; if (first) { // passo 1: criar um document-object document = new Document(reader.getPageSizeWithRotation(1)); // passo 2: criar um writer que observa o documento writer = new PdfCopy(document, byteOS); document.addAuthor("JRimum Group"); document.addSubject("JRimum Merged Document"); document.addCreator("JRimum Utilix"); // passo 3: abre-se o documento document.open(); first = false; } // passo 4: adciona-se o conteudo PdfImportedPage page; for (int i = 0; i < n;) { ++i; page = writer.getImportedPage(reader, i); writer.addPage(page); } } } if (master.size() > 0) { writer.setOutlines(master); } // passo 5: fecha-se o documento if (isNotNull(document)) { document.close(); } bytes = byteOS.toByteArray(); } catch (Exception e) { LOG.error("", e); } } return bytes; }
From source file:ca.sqlpower.architect.profile.output.ProfilePDFFormat.java
License:Open Source License
/** * Outputs a PDF file report of the data in drs to the given * output stream./*from www. j a v a2s. com*/ * @throws SQLObjectException * @throws IllegalAccessException * @throws InstantiationException */ public void format(OutputStream out, List<ProfileResult> profileResults) throws DocumentException, IOException, SQLException, SQLObjectException, InstantiationException, IllegalAccessException, ClassNotFoundException { final int minRowsTogether = 1; // counts smaller than this are considered orphan/widow final int mtop = 50; // margin at top of page (in points) final int mbot = 50; // margin at bottom of page (page numbers are below this) // final int pbot = 20; // padding between bottom margin and bottom of body text final int mlft = 50; // margin at left side of page final int mrgt = 50; // margin at right side of page final Rectangle pagesize = PageSize.LETTER.rotate(); final Document document = new Document(pagesize, mlft, mrgt, mtop, mbot); final PdfWriter writer = PdfWriter.getInstance(document, out); final float fsize = 6f; // the font size to use in the table body final BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED); document.addTitle("Table Profiling Report"); document.addSubject("Tables: " + profileResults); document.addAuthor(System.getProperty("user.name")); document.addCreator("Power*Architect version " + ArchitectVersion.APP_FULL_VERSION); document.open(); // vertical position where next element should start // (bottom is 0; top is pagesize.height()) float pos = pagesize.height() - mtop; final PdfContentByte cb = writer.getDirectContent(); final PdfTemplate nptemplate = cb.createTemplate(50, 50); writer.setPageEvent(new PdfPageEventHelper() { // prints the "page N of <template>" footer public void onEndPage(PdfWriter writer, Document document) { int pageN = writer.getPageNumber(); String text = "Page " + pageN + " of "; float len = bf.getWidthPoint(text, fsize - 2); cb.beginText(); cb.setFontAndSize(bf, fsize - 2); cb.setTextMatrix(pagesize.width() / 2 - len / 2, mbot / 2); cb.showText(text); cb.endText(); cb.addTemplate(nptemplate, pagesize.width() / 2 - len / 2 + len, mbot / 2); } public void onCloseDocument(PdfWriter writer, Document document) { nptemplate.beginText(); nptemplate.setFontAndSize(bf, fsize - 2); nptemplate.showText(String.valueOf(writer.getPageNumber() - 1)); nptemplate.endText(); } }); document.add(new Paragraph("SQL Power Architect Profiling Report")); document.add(new Paragraph("Generated " + new java.util.Date() + " by " + System.getProperty("user.name"))); float[] widths = new float[totalColumn]; // widths of widest cells per row in pdf table LinkedList<ProfileTableStructure> profiles = new LinkedList<ProfileTableStructure>(); // 1 table per profile result Font f = new Font(bf, fsize); // This ddl generator is set to the appropriate ddl generator for the source database // every time we encounter a table profile result in the list. DDLGenerator ddlg = null; PdfPTable pdfTable = null; for (ProfileResult result : profileResults) { if (result instanceof TableProfileResult) { TableProfileResult tableResult = (TableProfileResult) result; pdfTable = new PdfPTable(widths.length); pdfTable.setWidthPercentage(100f); ProfileTableStructure oneProfile = makeNextTable(tableResult, pdfTable, bf, fsize, widths); profiles.add(oneProfile); ddlg = tableResult.getDDLGenerator(); } else if (result instanceof ColumnProfileResult) { final ColumnProfileResult columnResult = (ColumnProfileResult) result; TableProfileResult tResult = columnResult.getParent(); addBodyRow(tResult, columnResult, ddlg, pdfTable, bf, f, fsize, widths); } } double allowedTableSize = pagesize.width() - mrgt - mlft; double totalWidths = 0; for (int i = 0; i < headings.length; i++) { if (!columnsToTruncate.contains(headings[i])) { widths[i] += PIXELS_PER_BORDER; totalWidths += widths[i]; } } truncateLength = (allowedTableSize - totalWidths - (PIXELS_PER_BORDER * (columnsToTruncate.size()))) / columnsToTruncate.size(); logger.debug("Truncate length is " + truncateLength); widths = new float[totalColumn]; profiles = new LinkedList<ProfileTableStructure>(); // 1 table per profile result for (ProfileResult result : profileResults) { if (result instanceof TableProfileResult) { TableProfileResult tableResult = (TableProfileResult) result; pdfTable = new PdfPTable(widths.length); pdfTable.setWidthPercentage(100f); ProfileTableStructure oneProfile = makeNextTable(tableResult, pdfTable, bf, fsize, widths); profiles.add(oneProfile); ddlg = tableResult.getDDLGenerator(); } else if (result instanceof ColumnProfileResult) { final ColumnProfileResult columnResult = (ColumnProfileResult) result; TableProfileResult tResult = columnResult.getParent(); addBodyRow(tResult, columnResult, ddlg, pdfTable, bf, f, fsize, widths); } } for (int i = 0; i < headings.length; i++) { widths[i] += PIXELS_PER_BORDER; } // add the PdfPTables to the document; try to avoid orphan and widow rows pos = writer.getVerticalPosition(true) - fsize; logger.debug("Starting at pos=" + pos); boolean newPageInd = true; for (ProfileTableStructure profile : profiles) { pdfTable = profile.getMainTable(); pdfTable.setTotalWidth(pagesize.width() - mrgt - mlft); pdfTable.setWidths(widths); resetHeaderWidths(profile, widths); int startrow = pdfTable.getHeaderRows(); int endrow = startrow; // current page will contain header+startrow..endrow /* no other rows in the table, just the header, and the header may * contain error message */ if (endrow == pdfTable.size()) { pos = pdfTable.writeSelectedRows(0, pdfTable.getHeaderRows(), mlft, pos, cb); continue; } while (endrow < pdfTable.size()) { // figure out how many body rows fit nicely on the page float endpos = pos - calcHeaderHeight(pdfTable); // y position of page number# = (mbot/2+fsize) while ((endpos - pdfTable.getRowHeight(endrow)) >= (mbot / 2 + fsize + 2) && endrow < pdfTable.size()) { endpos -= pdfTable.getRowHeight(endrow); endrow++; } // adjust for orphan rows. Might create widows or make // endrow < startrow, which is handled later by deferring the table if (endrow < pdfTable.size() && endrow + minRowsTogether >= pdfTable.size()) { // page # maybe fall into table area, but usually that's column of // min value, usually that's enough space for both, or we should // disable page # on this page if (endrow + 1 == pdfTable.size() && endpos - pdfTable.getRowHeight(endrow) > 10) { // short by 1 row.. just squeeze it in endrow = pdfTable.size(); } else { // more than 1 row remains: shorten this page so orphans aren't lonely endrow = pdfTable.size() - minRowsTogether; } } if (endrow == pdfTable.size() || endrow - startrow >= minRowsTogether) { // this is the end of the table, or we have enough rows to bother printing pos = pdfTable.writeSelectedRows(0, pdfTable.getHeaderRows(), mlft, pos, cb); pos = pdfTable.writeSelectedRows(startrow, endrow, mlft, pos, cb); startrow = endrow; newPageInd = false; } else { // not the end of the table and not enough rows to print out if (newPageInd) throw new IllegalStateException( "PDF Page is not large engouh to display " + minRowsTogether + " row(s)"); endrow = startrow; } // new page if necessary (that is, when we aren't finished the table yet) if (endrow != pdfTable.size()) { document.newPage(); pos = pagesize.height() - mtop; newPageInd = true; } } } document.close(); }
From source file:ca.sqlpower.architect.swingui.action.ExportPlaypenToPDFAction.java
License:Open Source License
@Override public void doStuff(MonitorableImpl monitor, Map<String, Object> properties) { logger.debug("Creating PDF of playpen: " + getPlaypen()); //This is the current play pen snapshot at the time of starting the worker //thread. This way the play pen doesn't change while it is printing. PlayPen pp = playPen;//from w w w .j a v a 2 s . c o m /* We translate the graphics to (OUTSIDE_PADDING, OUTSIDE_PADDING) * so nothing is drawn right on the edge of the document. So * we multiply by 2 so we can accomodate the translate and ensure * nothing gets drawn outside of the document size. */ final int width = pp.getBounds().width + 2 * OUTSIDE_PADDING; final int height = pp.getBounds().height + 2 * OUTSIDE_PADDING; final Rectangle ppSize = new Rectangle(width, height); OutputStream out = null; Document d = null; try { out = new BufferedOutputStream(new FileOutputStream((File) properties.get(FILE_KEY))); d = new Document(ppSize); d.addTitle(Messages.getString("ExportPlaypenToPDFAction.PdfTitle")); //$NON-NLS-1$ d.addAuthor(System.getProperty("user.name")); //$NON-NLS-1$ d.addCreator(Messages.getString("ExportPlaypenToPDFAction.powerArchitectVersion") //$NON-NLS-1$ + ArchitectVersion.APP_FULL_VERSION); PdfWriter writer = PdfWriter.getInstance(d, out); d.open(); PdfContentByte cb = writer.getDirectContent(); Graphics2D g = cb.createGraphicsShapes(width, height); // ensure a margin g.translate(OUTSIDE_PADDING, OUTSIDE_PADDING); PlayPenContentPane contentPane = pp.getContentPane(); for (int i = 0; i < contentPane.getChildren().size(); i++) { PlayPenComponent ppc = contentPane.getChildren().get(i); if (logger.isDebugEnabled()) { logger.debug("Painting component " + ppc); } g.translate(ppc.getLocation().x, ppc.getLocation().y); Font gFont = g.getFont(); ppc.paint(g); g.setFont(gFont); g.translate(-ppc.getLocation().x, -ppc.getLocation().y); monitor.setProgress(i); } pp.paintComponent(g); g.dispose(); } catch (Exception ex) { ASUtils.showExceptionDialog(getSession(), Messages.getString("ExportPlaypenToPDFAction.couldNotExportPlaypen"), //$NON-NLS-1$ ex); } finally { if (d != null) { try { d.close(); } catch (Exception ex) { ASUtils.showExceptionDialog(getSession(), Messages.getString("ExportPlaypenToPDFAction.couldNotCloseDocument"), //$NON-NLS-1$ ex); } } if (out != null) { try { out.flush(); out.close(); } catch (IOException ex) { ASUtils.showExceptionDialog(getSession(), Messages.getString("ExportPlaypenToPDFAction.couldNotClosePdfFile"), //$NON-NLS-1$ ex); } } } }
From source file:ca.sqlpower.matchmaker.swingui.action.ExportMungePenToPDFAction.java
License:Open Source License
@Override public void doStuff(MonitorableImpl monitor, Map<String, Object> properties) { if (!(session.getOldPane() instanceof MungeProcessEditor)) { JOptionPane.showMessageDialog(session.getFrame(), "We only allow PDF exports of the playpen at current.", "Cannot Export Playpen", JOptionPane.WARNING_MESSAGE); return;//w ww . ja va2s. c o m } MungePen mungePen = ((MungeProcessEditor) session.getOldPane()).getMungePen(); /* We translate the graphics to (OUTSIDE_PADDING, OUTSIDE_PADDING) * so nothing is drawn right on the edge of the document. So * we multiply by 2 so we can accomodate the translate and ensure * nothing gets drawn outside of the document size. */ final int width = mungePen.getBounds().width + 2 * OUTSIDE_PADDING; final int height = mungePen.getBounds().height + 2 * OUTSIDE_PADDING; final Rectangle ppSize = new Rectangle(width, height); OutputStream out = null; Document d = null; try { out = new BufferedOutputStream(new FileOutputStream((File) properties.get(FILE_KEY))); d = new Document(ppSize); d.addTitle("DQguru Transform PDF Export"); d.addAuthor(System.getProperty("user.name")); d.addCreator("DQguru version " + MatchMakerVersion.APP_VERSION); PdfWriter writer = PdfWriter.getInstance(d, out); d.open(); PdfContentByte cb = writer.getDirectContent(); Graphics2D g = cb.createGraphicsShapes(width, height); // ensure a margin g.translate(OUTSIDE_PADDING, OUTSIDE_PADDING); mungePen.paintComponent(g); int j = 0; //paint each component individually to show progress for (int i = mungePen.getComponentCount() - 1; i >= 0; i--) { JComponent mpc = (JComponent) mungePen.getComponent(i); //set text and foreground as paintComponent //does not normally do this g.setColor(mpc.getForeground()); g.setFont(mpc.getFont()); logger.debug("Printing " + mpc.getName() + " to PDF"); paintComponentAndChildren(mpc, g); monitor.setProgress(j); j++; } g.dispose(); } catch (Exception ex) { SPSUtils.showExceptionDialogNoReport(session.getFrame(), "Could not export the playpen", ex); } finally { if (d != null) { try { d.close(); } catch (Exception ex) { SPSUtils.showExceptionDialogNoReport(session.getFrame(), "Could not close document for exporting playpen", ex); } } if (out != null) { try { out.flush(); out.close(); } catch (IOException ex) { SPSUtils.showExceptionDialogNoReport(session.getFrame(), "Could not close pdf file for exporting playpen", ex); } } } }
From source file:com.AppModel.Reportes.GeneraPdf.java
public void generarArchivoPdf(String xml) { try {/* w w w .j a va 2s.com*/ Document document = new Document(PageSize.A4); PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream("plantillaa.pdf")); document.open(); document.addAuthor("Persona creadora"); document.addCreator("Software generador"); document.addCreationDate(); document.addTitle("Titulo del documento"); HTMLWorker htmlWorker = new HTMLWorker(document); // String str = "<table>\n" // + " <tr>\n" // + " <td>Boleta</td>\n" // + " <td>Fecha</td>\n" // + " <th>Operacion</th>\n" // + " <td>Abono</td>\n" // + " <td>Interes generado </td>\n" // + " <td>Cargo</td>\n" // + " <td>Usuario que realizo el movimiento</td> \n" // + " </tr>\n" // + " <tr>\n" // + " <td align=center>MLOM005817</td>\n" // + " <td align=center>2015-04-19 15:53:37.0</td>\n" // + " <td align=center>Nuevo empeo</td>\n" // + " <td align=center></td>\n" // + " <td align=center></td>\n" // + " <td align=center>$533.00</td>\n" // + " <td align=center>admin</td>\n" // + " </tr>\n" // + " <tr>\n" // + " <td align=center>MLOM005817</td>\n" // + " <td align=center>2015-04-19 15:56:04.0</td>\n" // + " <td align=center>Extension de contrato</td>\n" // + " <td align=center></td><td align=center>$1.44</td>\n" // + " <td align=center></td>\n" // + " <td align=center>admin</td>\n" // + " </tr>\n" // + " <tr>\n" // + " <td align=center>MLOM005817</td>\n" // + " <td align=center>2015-04-19 16:00:51.0</td>\n" // + " <td align=center>Desempeo</td>\n" // + " <td align=center>$554.64 </td>\n" // + " <td align=center>$21.64 </td>\n" // + " <td align=center></td>\n" // + " <td align=center>admin</td>\n" // + " </tr>\n" // + " <tr>\n" // + " <td align=center>MLOM005818</td>\n" // + " <td align=center>2015-04-19 16:37:24.0</td>\n" // + " <td align=center>Refrendo</td>\n" // + " <td align=center>$533.00 </td>\n" // + " <td align=center>$21.64 </td>\n" // + " <td align=center>$533.00 </td>\n" // + " <td align=center>admin</td>\n" // + " </tr>\n" // + " <tr>\n" // + " <td></td>\n" // + " <td></td>\n" // + " <td></td>\n" // + " <td></td>\n" // + " <td align=center><b>$1,087.64 pesos</b> </td>\n" // + " <td align=center><b>$44.72 pesos</b> </td>\n" // + " <td align=center><b>$1,066.00 pesos</b> </td>\n" // + " </tr>\n" // + " <tr style=height:50px;>\n" // + " <td align=right colspan=7> </td>\n" // + " <td align=left colspan=5><b>El monto de apertura dia fue de: $90000.0 pesos</b> </td>\n" // + " <td align=left colspan=5><b id='saldoAlCierre' title='89511.72'>Saldo al cierre: $89511.72 pesos</b> </td>\n" // + " </tr>\n" // + " </table>"; String str = "<table>\n" + " <tr>\n" + " <td>Boleta</td>\n" + " <td>Fecha</td>\n" + " <th>Operacion</th>\n" + " <td>Abono</td>\n" + " <td>Interes generado </td>\n" + " <td>Cargo</td>\n" + " <td>Usuario que realizo el movimiento</td> \n" + " </tr>\n" + " <tr>\n" + " <td align=center>MLOM005817</td>\n" + " <td align=center>2015-04-19 15:53:37.0</td>\n" + " <td align=center>Nuevo empeo</td>\n" + " <td align=center></td>\n" + " <td align=center></td>\n" + " <td align=center>$533.00</td>\n" + " <td align=center>admin</td>\n" + " </tr>\n" + " <tr>\n" + " <td align=center>MLOM005817</td>\n" + " <td align=center>2015-04-19 15:56:04.0</td>\n" + " <td align=center>Extension de contrato</td>\n" + " <td align=center></td><td align=center>$1.44</td>\n" + " <td align=center></td>\n" + " <td align=center>admin</td>\n" + " </tr>\n" + " <tr>\n" + " <td align=center>MLOM005817</td>\n" + " <td align=center>2015-04-19 16:00:51.0</td>\n" + " <td align=center>Desempeo</td>\n" + " <td align=center>$554.64 </td>\n" + " <td align=center>$21.64 </td>\n" + " <td align=center></td>\n" + " <td align=center>admin</td>\n" + " </tr>\n" + " <tr>\n" + " <td align=center>MLOM005818</td>\n" + " <td align=center>2015-04-19 16:37:24.0</td>\n" + " <td align=center>Refrendo</td>\n" + " <td align=center>$533.00 </td>\n" + " <td align=center>$21.64 </td>\n" + " <td align=center>$533.00 </td>\n" + " <td align=center>admin</td>\n" + " </tr>\n" + " <tr>\n" + " <td></td>\n" + " <td></td>\n" + " <td></td>\n" + " <td align=center><b>$1,087.64 pesos</b> </td>\n" + " <td align=center><b>$44.72 pesos</b> </td>\n" + " <td align=center><b>$1,066.00 pesos</b> </td>\n" + " </tr>\n" + " <tr style=height:50px;>\n" + " <td align=right colspan=7> </td>\n" + " </tr><tr>\n" + " <td align=left colspan=5><b>El monto de apertura dia fue de: $90000.0 pesos</b> </td>\n" + " </tr><tr>\n" + " <td align=left colspan=5><b id='saldoAlCierre' title='89511.72'>Saldo al cierre: $89511.72 pesos</b> </td>\n" + " </tr>\n" + " </table>"; htmlWorker.parse(new StringReader(str)); document.close(); } catch (Exception e) { System.out.println("" + e.getMessage()); } }
From source file:com.aripd.clms.service.ContractServiceBean.java
private static void addMetaData(Document document) { document.addTitle("Generated PDF for CLMS"); document.addSubject("Using iText"); document.addKeywords("Java, PDF, iText"); document.addAuthor("dev@aripd.com"); document.addCreator("dev@aripd.com"); }