List of usage examples for com.lowagie.text Document open
boolean open
To view the source code for com.lowagie.text Document open.
Click Source Link
From source file:com.amphisoft.epub2pdf.Converter.java
License:Open Source License
public void convert(String epubPath) throws IOException, DocumentException { File epubFile = new File(epubPath); if (!(epubFile.canRead())) { throw new IOException("Could not read " + epubPath); } else {//from ww w . ja va2s .c o m System.err.println("Converting " + epubFile.getAbsolutePath()); } String epubFilename = epubFile.getName(); String epubFilenameBase = epubFilename.substring(0, epubFilename.length() - 5); String pdfFilename = epubFilenameBase + ".pdf"; File outputFile = new File(outputDir.getAbsolutePath() + File.separator + pdfFilename); epubIn = Epub.fromFile(epubPath); XhtmlHandler.setSourceEpub(epubIn); Opf opf = epubIn.getOpf(); List<String> contentPaths = opf.spineHrefs(); List<File> contentFiles = new ArrayList<File>(); for (String path : contentPaths) { contentFiles.add(new File(epubIn.getContentRoot(), path)); } Ncx ncx = epubIn.getNcx(); List<NavPoint> ncxToc = new ArrayList<NavPoint>(); if (ncx != null) { ncxToc.addAll(ncx.getNavPointsFlat()); } Tree<TocTreeNode> tocTree = TocTreeNode.buildTocTree(ncx); XhtmlHandler.setTocTree(tocTree); Document doc = new Document(); boolean pageSizeOK = doc.setPageSize(pageSize); boolean marginsOK = doc.setMargins(marginLeftPt, marginRightPt, marginTopPt, marginBottomPt); System.err.println("Writing PDF to " + outputFile.getAbsolutePath()); PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(outputFile)); writer.setStrictImageSequence(true); PdfOutline bookmarkRoot = null; if (!(pageSizeOK && marginsOK)) { throw new RuntimeException("Failed to set PDF page size a/o margins"); } int fileCount = contentFiles.size(); printlnerr("Processing " + fileCount + " HTML file(s): "); int currentFile = 0; for (File file : contentFiles) { currentFile++; char progressChar; int mod10 = currentFile % 10; if (mod10 == 5) progressChar = '5'; else if (mod10 == 0) progressChar = '0'; else progressChar = '.'; printerr(progressChar); if (!(doc.isOpen())) { doc.open(); doc.newPage(); bookmarkRoot = writer.getRootOutline(); XhtmlHandler.setBookmarkRoot(bookmarkRoot); } NavPoint fileLevelNP = Ncx.findNavPoint(ncxToc, file.getName()); TreeNode<TocTreeNode> npNode = TocTreeNode.findInTreeByNavPoint(tocTree, fileLevelNP); if (fileLevelNP != null) { doc.newPage(); PdfOutline pdfOutlineParent = bookmarkRoot; if (npNode != null) { TreeNode<TocTreeNode> parent = npNode.getParent(); if (parent != null) { TocTreeNode parentTTN = parent.getValue(); if (parentTTN != null && parentTTN.getPdfOutline() != null) { pdfOutlineParent = parentTTN.getPdfOutline(); } } } PdfDestination here = new PdfDestination(PdfDestination.FIT); PdfOutline pdfTocEntry = new PdfOutline(pdfOutlineParent, here, fileLevelNP.getNavLabelText()); if (npNode != null) { npNode.getValue().setPdfDestination(here); npNode.getValue().setPdfOutline(pdfTocEntry); } } XhtmlHandler.process(file.getCanonicalPath(), doc); } printlnerr(); doc.close(); System.err.println("PDF written to " + outputFile.getAbsolutePath()); epubIn.cleanup(); }
From source file:com.anevis.jfreechartsamplespring.chart.ChartServiceImpl.java
private byte[] writeChartsToDocument(JFreeChart... charts) { try {/*from w ww.j a va2s . c om*/ ByteArrayOutputStream baos = new ByteArrayOutputStream(); float width = PageSize.A4.getWidth(); float height = PageSize.A4.getHeight() / 2; int index = 0; Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); PdfContentByte contentByte = writer.getDirectContent(); for (JFreeChart chart : charts) { PdfTemplate template = contentByte.createTemplate(width, height); Graphics2D graphics2D = template.createGraphics(width, height); Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height); chart.draw(graphics2D, rectangle2D); graphics2D.dispose(); contentByte.addTemplate(template, 0, height - (height * index)); index++; } writer.flush(); document.close(); return baos.toByteArray(); } catch (DocumentException ex) { Logger.getLogger(ChartService.class.getName()).log(Level.SEVERE, null, ex); } return null; }
From source file:com.AppModel.Reportes.GeneraPdf.java
public void generarArchivoPdf(String xml) { try {// ww w . j a v a 2 s . 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
@Override public void generatePdf(ContractEntity contract) { String baseFontUrl = "/fonts/Quivira.otf"; FontFactory.register(baseFontUrl);/*w w w . j a va2 s.c o m*/ ByteArrayOutputStream output = new ByteArrayOutputStream(); try { BaseFont bf = BaseFont.createFont(baseFontUrl, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); Font font18n = new Font(bf, 18, Font.NORMAL); Font font12n = new Font(bf, 12, Font.NORMAL); Font font8n = new Font(bf, 8, Font.NORMAL); Font font8nbu = new Font(bf, 8, Font.BOLD | Font.UNDERLINE); Font font8ng = new Font(bf, 8, Font.NORMAL, Color.DARK_GRAY); Font font6n = new Font(bf, 6, Font.NORMAL); Document document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.getInstance(document, output); document.open(); addMetaData(document); addTitlePage(document, contract); Image imgBlue = Image.getInstance(1, 1, 3, 8, new byte[] { (byte) 0, (byte) 0, (byte) 255, }); imgBlue.scaleAbsolute(document.getPageSize().getWidth(), 10); imgBlue.setAbsolutePosition(0, document.getPageSize().getHeight() - imgBlue.getScaledHeight()); PdfImage stream = new PdfImage(imgBlue, "", null); stream.put(new PdfName("ITXT_SpecialId"), new PdfName("123456789")); PdfIndirectObject ref = writer.addToBody(stream); imgBlue.setDirectReference(ref.getIndirectReference()); document.add(imgBlue); PdfPTable table = new PdfPTable(2); table.setWidthPercentage(100); PdfPCell cell = new PdfPCell(new Paragraph(contract.getName(), font18n)); cell.setBorder(Rectangle.NO_BORDER); cell.setColspan(2); cell.setPadding(5); table.addCell(cell); cell = new PdfPCell(new Paragraph("Version: " + contract.getVersion(), font8n)); cell.setBorder(Rectangle.NO_BORDER); cell.setColspan(2); cell.setPadding(5); table.addCell(cell); cell = new PdfPCell(new Paragraph("Review: " + contract.getReview(), font8n)); cell.setBorder(Rectangle.NO_BORDER); cell.setColspan(2); cell.setPadding(5); table.addCell(cell); cell = new PdfPCell(new Paragraph(contract.getRemark(), font12n)); cell.setBorder(Rectangle.NO_BORDER); cell.setColspan(2); cell.setPadding(5); table.addCell(cell); document.add(table); // Start a new page document.newPage(); HTMLWorker htmlWorker = new HTMLWorker(document); htmlWorker.parse(new StringReader(contract.getRemark())); // Start a new page document.newPage(); document.add(new Paragraph("Review Board", font18n)); document.add(new LineSeparator(0.5f, 100, null, 0, -5)); table = new PdfPTable(3); table.setWidthPercentage(100); cell = new PdfPCell(new Paragraph("Review Board", font18n)); cell.setColspan(3); table.addCell(cell); cell = new PdfPCell(new Paragraph("Version", font12n)); table.addCell(cell); cell = new PdfPCell(new Paragraph("Date", font12n)); table.addCell(cell); cell = new PdfPCell(new Paragraph("Review", font12n)); table.addCell(cell); for (HistoryContractEntity history : historyContractService.listing(contract)) { cell = new PdfPCell(new Paragraph(history.getVersion().toString(), font8n)); table.addCell(cell); cell = new PdfPCell(new Paragraph(history.getStartdate().toString(), font8n)); table.addCell(cell); cell = new PdfPCell(new Paragraph(history.getReview(), font8n)); table.addCell(cell); } document.add(table); document.close(); FacesContext context = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse(); response.reset(); response.addHeader("Content-Type", "application/force-download"); String filename = URLEncoder.encode(contract.getName() + ".pdf", "UTF-8"); // response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + filename); response.getOutputStream().write(output.toByteArray()); response.getOutputStream().flush(); context.responseComplete(); context.renderResponse(); } catch (BadPdfFormatException | IOException ex) { Logger.getLogger(ContractServiceBean.class.getName()).log(Level.SEVERE, null, ex); } catch (DocumentException ex) { Logger.getLogger(ContractServiceBean.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.aryjr.nheengatu.pdf.PDFDocument.java
License:Open Source License
public void generateFile(final OutputStream out) throws IOException { final Document document; if (styleSheet == null || styleSheet.getStyles() == null || !styleSheet.getStyles().containsKey("@page")) { document = new Document(PageSize.A4); document.setMargins(3.0f * PDFDocument.CM_UNIT, 2.0f * PDFDocument.CM_UNIT, 1.0f * PDFDocument.CM_UNIT, 2.0f * PDFDocument.CM_UNIT); System.out.println("Processamento: terminou setMargins"); } else {/*from w w w.j a va 2 s . com*/ Style style = ((Style) (styleSheet.getStyles().get("@page"))); if ("landscape".equals(style.getPropertyValue("size"))) { document = new Document(PageSize.A4.rotate()); } else { document = new Document(PageSize.A4); } String s = style.getPropertyValue("margin-left"); Float f = styleMeasure(s, "3cm"); document.setMargins(styleMeasure(style.getPropertyValue("margin-left"), "3cm"), styleMeasure(style.getPropertyValue("margin-right"), "2cm"), styleMeasure(style.getPropertyValue("margin-top"), "1cm"), styleMeasure(style.getPropertyValue("margin-bottom"), "2cm")); System.out.println("Processamento: terminou setMargins do else"); } try { final PdfWriter writer = PdfWriter.getInstance(document, out); writer.setPageEvent(new PDFPageBreak(writer, document, headFirstPage, footFirstPage, head, foot)); document.open(); final MultiColumnText mct = new MultiColumnText(); // set up 3 even columns with 10pt space between mct.addRegularColumns(document.left(), document.right(), 0f, 1); System.out.println("Processamento: prestes a extract visible components"); // Extracting the document content extractVisibleComponents(body, document, mct, null, null); document.add(mct); document.close(); } catch (final DocumentException de) { System.err.println(de.getMessage()); } }
From source file:com.aryjr.nheengatu.testes.AbsolutePosition.java
License:Open Source License
public static void main(final String[] args) { // System.out.println("My First PdfPTable"); final Document document = new Document(); try {/*from w w w. jav a2 s . c o m*/ final PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("/home/aryjr/MyFirstTable.pdf")); document.open(); // PdfPTable table = createTable(); // document.add(table); // table.writeSelectedRows(0, -1, 50, 200, // writer.getDirectContent()); final PdfContentByte cb = writer.getDirectContent(); cb.concatCTM(1f, 0f, 0f, -1f, 0f, 0f); // Paragraph text = new Paragraph("Ary Junior", // FontFactory.getFont(Style.DEFAULT_FONT_FAMILY, // Style.DEFAULT_FONT_SIZE, Font.NORMAL, Style.DEFAULT_FONT_COLOR)); final BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.beginText(); cb.setFontAndSize(bf, 12); cb.showText("Ary Junior"); cb.endText(); Runtime.getRuntime().exec("acroread /home/aryjr/MyFirstTable.pdf"); } catch (final DocumentException de) { System.err.println(de.getMessage()); } catch (final IOException ioe) { System.err.println(ioe.getMessage()); } document.close(); }
From source file:com.aurel.track.util.PdfUtils.java
License:Open Source License
public static void createPdfFromText(StringBuilder text, File pdfFile) { Document output = null; try {/*from www .j a v a 2 s . com*/ BufferedReader input = new BufferedReader(new StringReader(text.toString())); // Size DIN A4 // see com.lowagie.text.PageSize for a complete list of page-size constants. output = new Document(PageSize.A4, 40, 40, 40, 40); float fntSize, lineSpacing; fntSize = 9f; lineSpacing = 11f; Font font1 = FontFactory.getFont(FontFactory.COURIER, fntSize); Font font2 = FontFactory.getFont(FontFactory.COURIER, fntSize); font2.setColor(Color.BLUE); Font font3 = FontFactory.getFont(FontFactory.COURIER, fntSize); font3.setColor(Color.RED); PdfWriter.getInstance(output, new FileOutputStream(pdfFile)); output.open(); output.addAuthor("Steinbeis"); output.addSubject("Debug Info"); output.addTitle(pdfFile.getName()); String line = ""; while (null != (line = input.readLine())) { Font ft = font1; if (line.startsWith("%")) { ft = font2; } if (line.startsWith("% ^^^") || line.startsWith("% vvv")) { ft = font3; } Paragraph p = new Paragraph(lineSpacing, line, ft); p.setAlignment(Element.ALIGN_JUSTIFIED); output.add(p); } output.close(); input.close(); } catch (Exception e) { LOGGER.debug("Problem creating debug info pdf file", e); } }
From source file:com.bayareasoftware.chartengine.chart.jfree.JFreeChartDriver.java
License:Apache License
/** * Writes a chart to an output stream in PDF format. * * @param out the output stream./* w ww . jav a 2s . co m*/ * @param chart the chart. * @param width the chart width. * @param height the chart height. * */ public void writeChartAsPDF(OutputStream out, JFreeChart chart, int width, int height, FontMapper mapper) { com.lowagie.text.Rectangle pagesize = new com.lowagie.text.Rectangle(width, height); Document document = new Document(pagesize, 50.0f, 50.0f, 50.0f, 50.0f); try { PdfWriter writer = PdfWriter.getInstance(document, out); document.addAuthor("ChartMechanic"); document.addSubject("ChartMechanic PDF"); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, mapper); Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height); chart.draw(g2, r2D); g2.dispose(); cb.addTemplate(tp, 0, 0); } catch (DocumentException de) { System.err.println(de.getMessage()); } document.close(); }
From source file:com.bean.UserBean.java
public void gerarPDF1() { try {/*from www .j a v a2s . com*/ Document doc = new Document(PageSize.A4); OutputStream os = new FileOutputStream("C:/Users/lprates/Downloads/out.pdf"); PdfWriter.getInstance(doc, os); doc.open(); Paragraph p = new Paragraph("Meu primeiro arquivo PDF!"); doc.add(p); doc.close(); os.close(); //abre pdf usando o PDF Reader instalado na maquina do Usuario Desktop.getDesktop().open(new File("C:/Users/lprates/Downloads/out.pdf")); } catch (Exception e) { } }
From source file:com.bean.UserBean.java
public void gerarPDF2() { try {/* w w w . j a v a 2 s. c om*/ Document doc = new Document(); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); PdfWriter docWriter = null; docWriter = PdfWriter.getInstance(doc, baosPDF); doc.open(); doc.add(new Paragraph("This document was created by a class named: " + this.getClass().getName())); doc.add(new Paragraph("This document was created on " + new java.util.Date())); doc.close(); docWriter.close(); FacesContext facesContext = FacesContext.getCurrentInstance(); ExternalContext externalContext = facesContext.getExternalContext(); externalContext.setResponseContentType("application/pdf"); // com a opcao inline abre o PDF no browser do usuario //externalContext.setResponseHeader("Content-Disposition", "inline; filename=\"my.pdf\""); // com a opcao attachment faz download do PDF no computador do usuario externalContext.setResponseHeader("Content-Disposition", "attachment; filename=\"my.pdf\""); OutputStream responseOutputStream = externalContext.getResponseOutputStream(); baosPDF.writeTo(responseOutputStream); responseOutputStream.flush(); baosPDF.reset(); facesContext.responseComplete(); } catch (Exception e) { } }