List of usage examples for com.lowagie.text Document Document
public Document()
Document
-object. From source file:classroom.intro.HelloWorld12.java
public static void main(String[] args) { // step 1//from w w w. j a v a 2 s . c om Document document = new Document(); try { // step 2 PdfWriter.getInstance(document, new FileOutputStream(RESULT)); // step 3 document.open(); // step 4 Image image = Image.getInstance(IMAGE); image.scaleToFit(595, 842); image.setAbsolutePosition(0, 0); document.add(image); } catch (DocumentException de) { System.err.println(de.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } // step 5 document.close(); }
From source file:cn.js.nt.yao.sudokupdf.PDFRender.java
License:Apache License
private void openDocument() { try {// w w w . java 2s. c o m if (doc != null) { return; } doc = new Document(); doc.setPageSize(getLayout().getPageSize()); pdfFile = File.createTempFile("sudoku", ".pdf"); getPdfFile().deleteOnExit(); writer = PdfWriter.getInstance(doc, new BufferedOutputStream(new FileOutputStream(getPdfFile()))); getWriter().setPdfVersion(PdfWriter.VERSION_1_4); getWriter().setViewerPreferences(PdfWriter.PageModeUseNone); getDoc().open(); } catch (DocumentException ex) { Logger.getLogger(PDFRender.class.getName()).log(Level.SEVERE, null, ex); throw new RuntimeException(ex); } catch (IOException ex) { Logger.getLogger(PDFRender.class.getName()).log(Level.SEVERE, null, ex); throw new RuntimeException(ex); } }
From source file:com.amphisoft.epub2pdf.content.XhtmlTocBookmarkProbe.java
License:Open Source License
public static void main(String[] args) { String htmlInPath;//from ww w .j a va2 s . c om if (args.length == 1) { htmlInPath = args[0]; } else { htmlInPath = "data/pg-prufrock/1459/0.html"; } try { Document doc = new Document(); process(htmlInPath, doc); } catch (Exception e) { printlnerr(e.getLocalizedMessage()); } }
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 {//w w w . ja v a 2 s .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 va2 s.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.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 ww w .j a v a 2 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.bean.UserBean.java
public void gerarPDF2() { try {/*from w ww . j a v a 2 s . c o m*/ 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) { } }
From source file:com.bytecode.customexporter.PDFCustomExporter.java
@Override public void export(ActionEvent event, String tableId, FacesContext context, String filename, String tableTitle, boolean pageOnly, boolean selectionOnly, String encodingType, MethodExpression preProcessor, MethodExpression postProcessor, boolean subTable) throws IOException { try {/*from w w w . jav a 2 s .c o m*/ Document document = new Document(); if (orientation.equalsIgnoreCase("Landscape")) document.setPageSize(PageSize.A4.rotate()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(document, baos); StringTokenizer st = new StringTokenizer(tableId, ","); while (st.hasMoreElements()) { String tableName = (String) st.nextElement(); UIComponent component = SearchExpressionFacade.resolveComponent(context, event.getComponent(), tableName); if (component == null) { throw new FacesException("Cannot find component \"" + tableName + "\" in view."); } if (!(component instanceof DataTable || component instanceof DataList)) { throw new FacesException("Unsupported datasource target:\"" + component.getClass().getName() + "\", exporter must target a PrimeFaces DataTable/DataList."); } if (preProcessor != null) { preProcessor.invoke(context.getELContext(), new Object[] { document }); } if (!document.isOpen()) { document.open(); } if (tableTitle != null && !tableTitle.isEmpty() && !tableId.contains("" + ",")) { Font tableTitleFont = FontFactory.getFont(FontFactory.TIMES, encodingType, Font.DEFAULTSIZE, Font.BOLD); Paragraph title = new Paragraph(tableTitle, tableTitleFont); document.add(title); Paragraph preface = new Paragraph(); addEmptyLine(preface, 3); document.add(preface); } PdfPTable pdf; DataList list = null; DataTable table = null; if (component instanceof DataList) { list = (DataList) component; pdf = exportPDFTable(context, list, pageOnly, encodingType); } else { table = (DataTable) component; pdf = exportPDFTable(context, table, pageOnly, selectionOnly, encodingType, subTable); } if (pdf != null) { document.add(pdf); } // add a couple of blank lines Paragraph preface = new Paragraph(); addEmptyLine(preface, datasetPadding); document.add(preface); if (postProcessor != null) { postProcessor.invoke(context.getELContext(), new Object[] { document }); } } document.close(); writePDFToResponse(context.getExternalContext(), baos, filename); } catch (DocumentException e) { throw new IOException(e.getMessage()); } }
From source file:com.centurylink.mdw.designer.pages.ExportHelper.java
License:Apache License
/** * Export a process//from ww w . ja v a 2s . c o m * @param filename the file name (including path) where the document will be generated * @param format can be docx, pdf, rtf, html and bpmn * @param canvas for printing process images * @param graph the process to be printed. */ public void exportProcess(String filename, String format, Graph process, DesignerCanvas canvas) throws Exception { initialize(false); String oldNodeIdType = process.getNodeIdType(); try { process.setNodeIdType(nodeIdType); options.add(SECTION_NUMBER); if (format.equals(DOCX)) { DocxBuilder builder = printProcessDocx(filename, process, canvas); builder.save(new java.io.File(filename)); return; } else if (format.equals(HTML)) { StringBuffer sb = printPrologHtml("Process " + process.getName()); printProcessHtml(sb, canvas, 0, process, filename); printEpilogHtml(sb, filename); return; } else if (format.equals(JPG) || format.equals(PNG)) { byte[] imgBytes = printImage(-1f, canvas, process.getGraphSize(), format.equals(JPG) ? "jpeg" : "png"); OutputStream os = null; try { os = new FileOutputStream(new File(filename)); os.write(imgBytes); return; } catch (Exception ex) { ex.printStackTrace(); throw ex; } finally { if (os != null) os.close(); } } else if (format.equals(BPMN2)) { new BPMNHelper().exportProcess(process.getProcessVO(), filename); } else { // itext processor Document document = new Document(); try { DocWriter writer = null; if (format.equals(RTF)) { writer = RtfWriter2.getInstance(document, new FileOutputStream(filename)); } else if (format.equals(PDF)) { writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); } document.open(); document.setPageSize(PageSize.LETTER); Rectangle page_size = document.getPageSize(); Chapter chapter = printOneProcessPdf(writer, canvas, format, 1, process, filename, page_size); document.add(chapter); } catch (Exception ex) { ex.printStackTrace(); throw ex; } finally { // step 5: we close the document document.close(); } } } finally { process.setNodeIdType(oldNodeIdType); } }
From source file:com.centurylink.mdw.designer.pages.ExportHelper.java
License:Apache License
/** * Export multiple processes/*from w w w.j a va2 s . com*/ * @param filename the file name (including path) where the document will be generated * @param type can be pdf, rtf and html * @param flowchart the designer page (for using its canvas and report errors) * @param graphs the list of processes to be printed. * @param options options for printing, from the print dialog. */ public void exportProcesses(String filename, String type, FlowchartPage flowchart, List<Graph> graphs) throws Exception { initialize(false); options.add(SECTION_NUMBER); // step 1: creation of a document-object Document document = new Document(); try { // step 2: create PDF or RTF writer DocWriter writer; if (type.equals(RTF)) { writer = RtfWriter2.getInstance(document, new FileOutputStream(filename)); } else if (type.equals(PDF)) { writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); } else { boolean directHtml = true; if (directHtml) { StringBuffer sb = printPrologHtml("Processes"); Graph process; for (int i = 0; i < graphs.size(); i++) { process = graphs.get(i); flowchart.setProcess(process); this.printProcessHtml(sb, flowchart.canvas, i + 1, process, filename); } printEpilogHtml(sb, filename); return; } writer = HtmlWriter.getInstance(document, new FileOutputStream(filename)); } // step 3: we open the document document.open(); // step 4: we add contents to the document document.setPageSize(PageSize.LETTER); Graph process; Chapter chapter; Rectangle page_size = document.getPageSize(); for (int i = 0; i < graphs.size(); i++) { process = graphs.get(i); process.setNodeIdType(nodeIdType); flowchart.setProcess(process); chapter = printOneProcessPdf(writer, flowchart.canvas, type, i + 1, process, filename, page_size); document.add(chapter); } } finally { // step 5: we close the document document.close(); } }