/* (non-Javadoc) * @see de.offis.health.icardea.cied.pdf.interfaces.PDFExtractor#getPDFPages(int, int) */ public byte[] getPDFPages(int fromPageNumber, int toPageNumber) { ByteArrayOutputStream byteArrayOutputStream = null; boolean extractionSuccessful = false; if (pdfReader != null) { int numberOfPages = getNumberOfPages(); /* * Check if the given page numbers are in the allowed range. */ if (fromPageNumber > 0 && fromPageNumber <= numberOfPages && toPageNumber > 0 && toPageNumber <= numberOfPages) { /* * Now check if the given fromPageNumber is smaller * as the given toPageNumber. If not swap the numbers. */ if (fromPageNumber > toPageNumber) { int tmpPageNumber = toPageNumber; toPageNumber = fromPageNumber; fromPageNumber = tmpPageNumber; } Document newDocument = new Document(); try { byteArrayOutputStream = new ByteArrayOutputStream(); PdfSmartCopy pdfCopy = new PdfSmartCopy(newDocument, byteArrayOutputStream); newDocument.open(); for (int currentPage = fromPageNumber; currentPage <= toPageNumber; currentPage++) { pdfCopy.addPage(pdfCopy.getImportedPage(pdfReader, currentPage)); } // end for pdfCopy.flush(); pdfCopy.close(); newDocument.close(); extractionSuccessful = true; } catch (DocumentException ex) { // TODO: Create an own exception for PDF processing errors. logger.error( "An exception occurred while extracting " + "pages from the input PDF file.", ex); } catch (IOException ex) { // TODO: Create an own exception for PDF processing errors. logger.error( "An exception occurred while extracting " + "pages from the input PDF file.", ex); } finally { if (!extractionSuccessful) { byteArrayOutputStream = null; } } // end try..catch..finally } // end if checking range of given pages } // end if (pdfReader != null) if (byteArrayOutputStream != null) { return byteArrayOutputStream.toByteArray(); } return null; }
@Test public void testNoBreakSpace() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); writer.setPageEvent( new PdfPageEventHelper() { public void onParagraph(PdfWriter writer, Document document, float position) { PdfContentByte cb = writer.getDirectContent(); PdfDestination destination = new PdfDestination(PdfDestination.FITH, position); new PdfOutline(cb.getRootOutline(), destination, TITLE); } }); document.add(new Paragraph("Hello World")); document.close(); // read bookmark back PdfReader r = new PdfReader(baos.toByteArray()); List<?> bookmarks = SimpleBookmark.getBookmark(r); assertEquals("bookmark size", 1, bookmarks.size()); @SuppressWarnings("unchecked") HashMap<String, Object> b = (HashMap<String, Object>) bookmarks.get(0); String title = (String) b.get("Title"); assertEquals("bookmark title", TITLE, title); }
/** * Demonstrates creating a footer with the current page number * * @param args Unused */ public static void main(String[] args) { System.out.println("Demonstrates creating a footer with a page number"); try { Document document = new Document(); RtfWriter2.getInstance(document, new FileOutputStream("PageNumber.rtf")); // Create a new Paragraph for the footer Paragraph par = new Paragraph("Page "); par.setAlignment(Element.ALIGN_RIGHT); // Add the RtfPageNumber to the Paragraph par.add(new RtfPageNumber()); // Create an RtfHeaderFooter with the Paragraph and set it // as a footer for the document RtfHeaderFooter footer = new RtfHeaderFooter(par); document.setFooter(footer); document.open(); for (int i = 1; i <= 300; i++) { document.add(new Paragraph("Line " + i + ".")); } document.close(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (DocumentException de) { de.printStackTrace(); } }
public void toPDFGraphicFile(File file, int width, int height) throws IOException { // otherwise toolbar appears plotToolBar.setVisible(false); com.lowagie.text.Document document = new com.lowagie.text.Document(); document.setPageSize(new Rectangle(width, height)); FileOutputStream fos = new FileOutputStream(file); PdfWriter writer = null; try { writer = PdfWriter.getInstance(document, fos); } catch (DocumentException ex) { Logger.getLogger(PlotPanel.class.getName()).log(Level.SEVERE, null, ex); } document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2d = tp.createGraphics(width, height); Image image = createImage(getWidth(), getHeight()); paint(image.getGraphics()); image = new ImageIcon(image).getImage(); g2d.drawImage(image, 0, 0, Color.WHITE, null); g2d.dispose(); cb.addTemplate(tp, 1, 0, 0, 1, 0, 0); document.close(); // make it reappear plotToolBar.setVisible(true); }
/** * An example using MultiColumnText with irregular columns. * * @param args no arguments needed */ public static void main(String[] args) { System.out.println("Simple MultiColumnText"); try { Document document = new Document(); OutputStream out = new FileOutputStream("multicolumnsimple.pdf"); PdfWriter.getInstance(document, out); document.open(); MultiColumnText mct = new MultiColumnText(); // set up 3 even columns with 10pt space between mct.addRegularColumns(document.left(), document.right(), 10f, 3); // Write some iText poems for (int i = 0; i < 30; i++) { mct.addElement(new Paragraph(String.valueOf(i + 1))); mct.addElement(newPara(randomWord(noun), Element.ALIGN_CENTER, Font.BOLDITALIC)); for (int j = 0; j < 4; j++) { mct.addElement(newPara(poemLine(), Element.ALIGN_LEFT, Font.NORMAL)); } mct.addElement(newPara(randomWord(adverb), Element.ALIGN_LEFT, Font.NORMAL)); mct.addElement(newPara("\n\n", Element.ALIGN_LEFT, Font.NORMAL)); } document.add(mct); document.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } }
public void dispose() { if (document != null) { g2.dispose(); document.close(); // can't be done in finalize, not always called document = null; } // new Exception().printStackTrace(System.out); }
public static void main(String[] args) throws Exception { Document doc = new Document(); PdfWriter.getInstance(doc, new FileOutputStream("htmlToPdfAuto.pdf")); doc.open(); HtmlParser.parse( doc, new InputSource(HtmlToPdfAuto.class.getResourceAsStream("/htmlToPdfSaxAuto.html"))); doc.close(); }
/** * Generates simple PDF, RTF and HTML files using only one Document object. * * @param args no arguments needed here */ public static void main(String[] args) { System.out.println("Hello World in PDF, RTF and HTML"); // step 1: creation of a document-object Document document = new Document(); try { // step 2: // we create 3 different writers that listen to the document File file1 = new File("HelloWorldPdf.pdf"); File file2 = new File("HelloWorldRtf.rtf"); File file3 = new File("HelloWorldHtml.html"); if (!file1.exists()) { file1.canWrite(); } if (!file2.exists()) { file2.canWrite(); } if (!file3.exists()) { file3.canWrite(); } PdfWriter pdf = PdfWriter.getInstance(document, new FileOutputStream(file1)); RtfWriter2 rtf = RtfWriter2.getInstance(document, new FileOutputStream(file2)); HtmlWriter.getInstance(document, new FileOutputStream(file3)); // step 3: we open the document document.open(); // step 4: we add a paragraph to the document document.add(new Paragraph("Hello World")); // we make references Anchor pdfRef = new Anchor("see Hello World in PDF."); pdfRef.setReference("./HelloWorldPdf.pdf"); Anchor rtfRef = new Anchor("see Hello World in RTF."); rtfRef.setReference("./HelloWorldRtf.rtf"); // we add the references, but only to the HTML page: pdf.pause(); rtf.pause(); document.add(pdfRef); document.add(Chunk.NEWLINE); document.add(rtfRef); pdf.resume(); rtf.resume(); } catch (DocumentException de) { System.err.println(de.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } // step 5: we close the document document.close(); }
public void close() { if (pdfDocument != null) { pdfDocument.close(); } if (pdfCopy != null) { pdfCopy.close(); } closed = true; }
private boolean txt2Pdf(File inputFile, File outputFile, Charset inputFileCharset) { // // 先将txt转成odt // String fileName = inputFile.getAbsolutePath(); // if (fileName.endsWith(".txt")) { BufferedReader bufferedReader = null; try { // 判断原始txt文件的编码格式,获取响应的文件读入 bufferedReader = new BufferedReader( new InputStreamReader(new FileInputStream(inputFile), inputFileCharset)); // 将txt内容直接生成pdf Document document = new Document(); BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); Font font_normal = new Font(bfChinese, 10, Font.NORMAL); // 设置字体大小 document.setPageSize(PageSize.A4); // 设置页面大小 if (!outputFile.exists()) { outputFile.createNewFile(); } try { PdfWriter.getInstance(document, new FileOutputStream(outputFile)); document.open(); } catch (Exception e) { e.printStackTrace(); } String content = null; while ((content = bufferedReader.readLine()) != null) { document.add(new Paragraph(content, font_normal)); } document.close(); bufferedReader.close(); return true; } catch (ConnectException cex) { cex.printStackTrace(); // System.out.println("转换失败!"); return false; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } catch (DocumentException e) { e.printStackTrace(); return false; } finally { // close the connection if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } // } }
public static void main(String[] args) throws Exception { Document doc = new Document(); PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream("unsigned_signature_field.pdf")); doc.open(); doc.add(new Paragraph("Hello world with digital signature block.")); PdfAcroForm acroForm = writer.getAcroForm(); acroForm.addSignature("sig", 73, 705, 149, 759); doc.close(); }
/** * This closes the pdf file created by createPDF, after you have written things to g2D. * * @param oar the object[] returned from createPdf * @throwsException if trouble */ public static void closePdf(Object oar[]) throws Exception { Graphics2D g2D = (Graphics2D) oar[0]; Document document = (Document) oar[1]; PdfContentByte pdfContentByte = (PdfContentByte) oar[2]; PdfTemplate pdfTemplate = (PdfTemplate) oar[3]; g2D.dispose(); // center it if (verbose) String2.log( "SgtUtil.closePdf" + " left=" + document.left() + " right=" + document.right() + " bottom=" + document.bottom() + " top=" + document.top() + " template.width=" + pdfTemplate.getWidth() + " template.height=" + pdfTemplate.getHeight()); // x device = ax user + by user + e // y device = cx user + dy user + f pdfContentByte.addTemplate( pdfTemplate, // a,b,c,d,e,f //x,y location in points 0.5f, 0, 0, 0.5f, document.left() + (document.right() - document.left() - pdfTemplate.getWidth() / 2) / 2, document.bottom() + (document.top() - document.bottom() - pdfTemplate.getHeight() / 2) / 2); /* //if boundingBox is small, center it //if boundingBox is large, shrink and center it //document.left/right/top/bottom include 1/2" margins float xScale = (document.right() - document.left()) / pdfTemplate.getWidth(); float yScale = (document.top() - document.bottom()) / pdfTemplate.getHeight(); float scale = Math.min(Math.min(xScale, yScale), 1); float xSize = pdfTemplate.getWidth() / scale; float ySize = pdfTemplate.getHeight() / scale; //x device = ax user + by user + e //y device = cx user + dy user + f pdfContentByte.addTemplate(pdfTemplate, //a,b,c,d,e,f scale, 0, 0, scale, document.left() + (document.right() - document.left() - xSize) / 2, document.bottom() + (document.top() - document.bottom() - ySize) / 2); */ document.close(); }
/** * Creates a document with some goto actions. * * @param args no arguments needed */ public static void main(String[] args) { System.out.println("Destinations"); // step 1: creation of a document-object Document document = new Document(); try { // step 2: PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("Destinations.pdf")); // step 3: writer.setViewerPreferences(PdfWriter.PageModeUseOutlines); document.open(); // step 4: we grab the ContentByte and do some stuff with it PdfContentByte cb = writer.getDirectContent(); // we create a PdfTemplate PdfTemplate template = cb.createTemplate(25, 25); // we add some crosses to visualize the destinations template.moveTo(13, 0); template.lineTo(13, 25); template.moveTo(0, 13); template.lineTo(50, 13); template.stroke(); // we add the template on different positions cb.addTemplate(template, 287, 787); cb.addTemplate(template, 187, 487); cb.addTemplate(template, 487, 287); cb.addTemplate(template, 87, 87); // we define the destinations PdfDestination d1 = new PdfDestination(PdfDestination.XYZ, 300, 800, 0); PdfDestination d2 = new PdfDestination(PdfDestination.FITH, 500); PdfDestination d3 = new PdfDestination(PdfDestination.FITR, 200, 300, 400, 500); PdfDestination d4 = new PdfDestination(PdfDestination.FITBV, 100); PdfDestination d5 = new PdfDestination(PdfDestination.FIT); // we define the outlines PdfOutline out1 = new PdfOutline(cb.getRootOutline(), d1, "root"); PdfOutline out2 = new PdfOutline(out1, d2, "sub 1"); new PdfOutline(out1, d3, "sub 2"); new PdfOutline(out2, d4, "sub 2.1"); new PdfOutline(out2, d5, "sub 2.2"); } catch (Exception de) { de.printStackTrace(); } // step 5: we close the document document.close(); }
/** * Generates a PDF file with the text 'Hello World' * * @param args no arguments needed here */ public static byte[] getDashboardPDFAsByteArray() { String localProviderURL = "t3://localhost:7001"; System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); System.setProperty(Context.PROVIDER_URL, localProviderURL); System.out.println("Generating VINSight DashBoard Reports"); // step 1: creation of a document-object Document document = new Document(); ByteArrayOutputStream baos = new ByteArrayOutputStream(100000); try { // step 2 PdfWriter writer; writer = PdfWriter.getInstance(document, baos); // step 3 document.open(); // step 4: we add a paragraph to the document document.add(new Paragraph("VINSight Health Check")); document.add(new Paragraph("Report 1")); // create the chart1 image JFreeChart chart1 = VINSightDashboardReport.createVINSightDashBoardChart1(); BufferedImage image1 = chart1.createBufferedImage(350, 350); image1.flush(); document.add(com.lowagie.text.Image.getInstance(image1, null)); document.add(new Paragraph("Report 2")); JFreeChart chart2 = VINSightDashboardReport.createVINSightDashBoardChart2(); BufferedImage image2 = chart2.createBufferedImage(350, 350); image2.flush(); document.add(com.lowagie.text.Image.getInstance(image2, null)); } catch (DocumentException de) { de.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { // step 5 document.close(); try { baos.close(); } catch (IOException ioe) { /*ignore*/ } } return baos.toByteArray(); }
public void close() { if (document != null) { // cleanup.. document.close(); try { outputStream.flush(); } catch (IOException e) { RTFPrinter.logger.info("Failed to flush the RTF-Output stream."); } finally { document = null; } } }
public void exportGraphic(Picture picture, OutputStream out) throws IOException { int width = picture.getPictureWidth(); int height = picture.getPictureHeight(); Document doc = new Document(new com.lowagie.text.Rectangle(width, height)); try { PdfWriter pWriter = PdfWriter.getInstance(doc, out); doc.open(); Graphics2D g = pWriter.getDirectContent().createGraphics(width, height); picture.paintPicture(g); g.dispose(); doc.close(); } catch (DocumentException e) { throw (IOException) new IOException(e.getMessage()).initCause(e); } }
/** * Extended headers / footers example * * @param args Unused */ public static void main(String[] args) { System.out.println("Demonstrates use of the RtfHeaderFooter for extended headers and footers"); try { Document document = new Document(); RtfWriter2.getInstance(document, new FileOutputStream("ExtendedHeaderFooter.rtf")); // Create the Paragraphs that will be used in the header. Paragraph date = new Paragraph("01.01.2010"); date.setAlignment(Paragraph.ALIGN_RIGHT); Paragraph address = new Paragraph("TheFirm\nTheRoad 24, TheCity\n" + "+00 99 11 22 33 44"); // Create the RtfHeaderFooter with an array containing the Paragraphs to add RtfHeaderFooter header = new RtfHeaderFooter(new Element[] {date, address}); // Set the header document.setHeader(header); // Create the table that will be used as the footer Table footer = new Table(2); footer.setBorder(0); footer.getDefaultCell().setBorder(0); footer.setWidth(100); footer.addCell(new Cell("(c) Mark Hall")); Paragraph pageNumber = new Paragraph("Page "); // The RtfPageNumber is an RTF specific element that adds a page number field pageNumber.add(new RtfPageNumber()); pageNumber.setAlignment(Paragraph.ALIGN_RIGHT); footer.addCell(new Cell(pageNumber)); // Create the RtfHeaderFooter and set it as the footer to use document.setFooter(new RtfHeaderFooter(footer)); document.open(); document.add( new Paragraph( "This document has headers and footers created" + " using the RtfHeaderFooter class.")); document.close(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (DocumentException de) { de.printStackTrace(); } }
public void manipulatePdf(String src, String dest, int pow) throws IOException, DocumentException { PdfReader reader = new PdfReader(src); Rectangle pageSize = reader.getPageSize(1); Rectangle newSize = (pow % 2) == 0 ? new Rectangle(pageSize.getWidth(), pageSize.getHeight()) : new Rectangle(pageSize.getHeight(), pageSize.getWidth()); Rectangle unitSize = new Rectangle(pageSize.getWidth(), pageSize.getHeight()); for (int i = 0; i < pow; i++) { unitSize = new Rectangle(unitSize.getHeight() / 2, unitSize.getWidth()); } int n = (int) Math.pow(2, pow); int r = (int) Math.pow(2, pow / 2); int c = n / r; Document document = new Document(newSize, 0, 0, 0, 0); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(String.format(dest, n))); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfImportedPage page; Rectangle currentSize; float offsetX, offsetY, factor; int total = reader.getNumberOfPages(); for (int i = 0; i < total; ) { if (i % n == 0) { document.newPage(); } currentSize = reader.getPageSize(++i); factor = Math.min( unitSize.getWidth() / currentSize.getWidth(), unitSize.getHeight() / currentSize.getHeight()); offsetX = unitSize.getWidth() * ((i % n) % c) + (unitSize.getWidth() - (currentSize.getWidth() * factor)) / 2f; offsetY = newSize.getHeight() - (unitSize.getHeight() * (((i % n) / c) + 1)) + (unitSize.getHeight() - (currentSize.getHeight() * factor)) / 2f; page = writer.getImportedPage(reader, i); cb.addTemplate(page, factor, 0, 0, factor, offsetX, offsetY); } document.close(); }
private ByteArrayOutputStream getPdfData( JSONArray data, JSONArray res, HttpServletRequest request) throws ServiceException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { String[] colHeader = getColHeader(); String[] colIndex = getColIndexes(); String[] val = getColValues(colHeader, data); String[] resources = getResourcesColHeader(res, data); String[] mainHeader = {"Dates", "Duration", "Work", "Cost", "Tasks", "Resources"}; Document document = null; if (landscape) { Rectangle recPage = new Rectangle(PageSize.A4.rotate()); recPage.setBackgroundColor(new java.awt.Color(255, 255, 255)); document = new Document(recPage, 15, 15, 30, 30); } else { Rectangle recPage = new Rectangle(PageSize.A4); recPage.setBackgroundColor(new java.awt.Color(255, 255, 255)); document = new Document(recPage, 15, 15, 30, 30); } PdfWriter writer = PdfWriter.getInstance(document, baos); writer.setPageEvent(new EndPage()); document.open(); if (showLogo) { getCompanyDetails(request); addComponyLogo(document, request); } addTitleSubtitle(document); addTable(data, resources, colIndex, colHeader, mainHeader, val, document); document.close(); writer.close(); baos.close(); } catch (ConfigurationException ex) { throw ServiceException.FAILURE("ExportProjectReport.getPdfData", ex); } catch (DocumentException ex) { throw ServiceException.FAILURE("ExportProjectReport.getPdfData", ex); } catch (JSONException e) { throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e); } catch (IOException e) { throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e); } catch (Exception e) { throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e); } return baos; }
/** @see com.lowagie.toolbox.AbstractTool#execute() */ public void execute() { try { if (getValue("odd") == null) throw new InstantiationException("You need to choose a sourcefile for the odd pages"); File odd_file = (File) getValue("odd"); if (getValue("even") == null) throw new InstantiationException("You need to choose a sourcefile for the even pages"); File even_file = (File) getValue("even"); if (getValue("destfile") == null) throw new InstantiationException("You need to choose a destination file"); File pdf_file = (File) getValue("destfile"); RandomAccessFileOrArray odd = new RandomAccessFileOrArray(odd_file.getAbsolutePath()); RandomAccessFileOrArray even = new RandomAccessFileOrArray(even_file.getAbsolutePath()); Image img = TiffImage.getTiffImage(odd, 1); Document document = new Document(new Rectangle(img.getScaledWidth(), img.getScaledHeight())); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdf_file)); document.open(); PdfContentByte cb = writer.getDirectContent(); int count = Math.max(TiffImage.getNumberOfPages(odd), TiffImage.getNumberOfPages(even)); for (int c = 0; c < count; ++c) { try { Image imgOdd = TiffImage.getTiffImage(odd, c + 1); Image imgEven = TiffImage.getTiffImage(even, count - c); document.setPageSize(new Rectangle(imgOdd.getScaledWidth(), imgOdd.getScaledHeight())); document.newPage(); imgOdd.setAbsolutePosition(0, 0); cb.addImage(imgOdd); document.setPageSize(new Rectangle(imgEven.getScaledWidth(), imgEven.getScaledHeight())); document.newPage(); imgEven.setAbsolutePosition(0, 0); cb.addImage(imgEven); } catch (Exception e) { System.out.println("Exception page " + (c + 1) + " " + e.getMessage()); } } odd.close(); even.close(); document.close(); } catch (Exception e) { e.printStackTrace(); } }
/** * Writing vertical text. * * @param args no arguments needed */ public static void main(String[] args) { Document document = new Document(PageSize.A4, 50, 50, 50, 50); try { texts[3] = convertCid(texts[0]); texts[4] = convertCid(texts[1]); texts[5] = convertCid(texts[2]); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("vertical.pdf")); int idx = 0; document.open(); PdfContentByte cb = writer.getDirectContent(); for (int j = 0; j < 2; ++j) { BaseFont bf = BaseFont.createFont("KozMinPro-Regular", encs[j], false); cb.setRGBColorStroke(255, 0, 0); cb.setLineWidth(0); float x = 400; float y = 700; float height = 400; float leading = 30; int maxLines = 6; for (int k = 0; k < maxLines; ++k) { cb.moveTo(x - k * leading, y); cb.lineTo(x - k * leading, y - height); } cb.rectangle(x, y, -leading * (maxLines - 1), -height); cb.stroke(); int status; VerticalText vt = new VerticalText(cb); vt.setVerticalLayout(x, y, height, maxLines, leading); vt.addText(new Chunk(texts[idx++], new Font(bf, 20))); vt.addText(new Chunk(texts[idx++], new Font(bf, 20, 0, Color.blue))); status = vt.go(); System.out.println(status); vt.setAlignment(Element.ALIGN_RIGHT); vt.addText(new Chunk(texts[idx++], new Font(bf, 20, 0, Color.orange))); status = vt.go(); System.out.println(status); document.newPage(); } document.close(); } catch (Exception de) { de.printStackTrace(); } }
public static void exportAsPdf( List<EventoBean> eventi, ByteArrayOutputStream baos, IEventiService eventiService) throws DocumentException, UtilsException { Document document = new Document(); PdfWriter.getInstance(document, baos); document.open(); addMetaData(document); addTitlePage(document); // Start a new page document.newPage(); addContent(document, eventi, eventiService); document.close(); }
/* * crea un file pdf contenente lo stack trace dell'eccezione */ private void createErrorFile(String url, File outputFile, Exception exception) { Document document = new Document(); PdfWriter pdfwriter = null; try { pdfwriter = PdfWriter.getInstance(document, new FileOutputStream(outputFile)); document.open(); StringBuilder buffer = new StringBuilder("Non è stato possibile generare"); buffer.append(" il file pdf per l'URL\n\n"); buffer.append(url); buffer.append("\n\na causa del seguente errore:\n\n"); document.add(new Paragraph(buffer.toString())); StringWriter stringWriter = new StringWriter(); exception.printStackTrace(new PrintWriter(stringWriter)); document.add(new Paragraph(stringWriter.toString())); document.close(); pdfwriter.close(); } catch (FileNotFoundException | DocumentException e) { log.error("errore di scrittura del file di errore", e); } }
public void pv() { try { Document document = new Document(PageSize.A4, 36, 72, 108, 180); PdfWriter.getInstance(document, new FileOutputStream("pdfFile.pdf")); File f = new File("abc.txt"); FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); String i; while ((i = br.readLine()) != null) { document.open(); document.add(new Paragraph(i)); } System.out.println("fetched database is inserted into pdf file"); document.close(); } catch (Exception e) { } }
/** * @see org.kuali.kfs.module.bc.service.PayrateImportService#generatePdf(java.lang.StringBuilder, * java.io.ByteArrayOutputStream) */ @NonTransactional public void generatePdf(List<ExternalizedMessageWrapper> logMessages, ByteArrayOutputStream baos) throws DocumentException { Document document = new Document(); PdfWriter.getInstance(document, baos); document.open(); for (ExternalizedMessageWrapper messageWrapper : logMessages) { String message; if (messageWrapper.getParams().length == 0) message = SpringContext.getBean(KualiConfigurationService.class) .getPropertyString(messageWrapper.getMessageKey()); else { String temp = SpringContext.getBean(KualiConfigurationService.class) .getPropertyString(messageWrapper.getMessageKey()); message = MessageFormat.format(temp, (Object[]) messageWrapper.getParams()); } document.add(new Paragraph(message)); } document.close(); }
protected final void renderMergedOutputModel( Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { // The following simple method doesn't work in IE, which // needs to know the content length. // PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream()); // document.open(); // buildPdfDocument(model, document, writer, request, response); // document.close(); // See http://www.lowagie.com/iText/faq.html#msie // for an explanation of why we can't use the obvious form above. // IE workaround: write into byte array first. ByteArrayOutputStream baos = new ByteArrayOutputStream(OUTPUT_BYTE_ARRAY_INITIAL_SIZE); Document document = getDocument(); PdfWriter writer = newWriter(document, baos); // Apply preferences and build metadata. prepareWriter(model, writer, request); buildPdfMetadata(model, document, request); // Build PDF document. document.open(); buildPdfDocument(model, document, writer, request, response); document.close(); // Write content type and also length (determined via byte array). response.setContentType(getContentType()); response.setContentLength(baos.size()); // Flush byte array to servlet output stream. ServletOutputStream out = response.getOutputStream(); baos.writeTo(out); out.flush(); }
/** * Extended font example. * * @param args Unused */ public static void main(String[] args) { System.out.println("Demonstrates the extended font support"); try { Document document = new Document(); RtfWriter2.getInstance(document, new FileOutputStream("ExtendedFont.rtf")); document.open(); // Create a RtfFont with the desired font name. RtfFont msComicSans = new RtfFont("Comic Sans MS"); // Use the RtfFont like any other Font. document.add(new Paragraph("This paragraph uses the" + " Comic Sans MS font.", msComicSans)); // Font size, font style and font colour can also be specified. RtfFont bigBoldGreenArial = new RtfFont("Arial", 36, Font.BOLD, Color.GREEN); document.add(new Paragraph("This is a really big bold green Arial text", bigBoldGreenArial)); document.close(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (DocumentException de) { de.printStackTrace(); } }
private void renderPDF(OutputStream out, Request request, Response response) throws Exception { Map<?, ?> properties = Play.configuration; String uri = request.getBase() + request.url; if (docs.documents.size() == 1) { renderDoc(docs.documents.get(0), uri, properties, out); } else { // we need to concatenate them all Document resultDocument = new Document(); PdfCopy copy = new PdfCopy(resultDocument, out); resultDocument.open(); ByteArrayOutputStream os = new ByteArrayOutputStream(); for (PDFDocument doc : docs.documents) { os.reset(); renderDoc(doc, uri, properties, os); PdfReader pdfReader = new PdfReader(os.toByteArray()); int n = pdfReader.getNumberOfPages(); for (int i = 0; i < n; i++) { copy.addPage(copy.getImportedPage(pdfReader, i + 1)); } copy.freeReader(pdfReader); } resultDocument.close(); } }
private void print() { Document document = new Document(PageSize.A4.rotate()); try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("jTable.pdf")); document.open(); PdfContentByte cb = writer.getDirectContent(); cb.saveState(); Graphics2D g2 = cb.createGraphicsShapes(500, 500); Shape oldClip = g2.getClip(); g2.clipRect(0, 0, 500, 500); table.print(g2); g2.setClip(oldClip); g2.dispose(); cb.restoreState(); } catch (Exception e) { System.err.println(e.getMessage()); } document.close(); }
/** * Performs the action: generate a PDF from a GET or POST. * * @param request the Servlets request object * @param response the Servlets request object * @param methodGetPost the method that was used in the form */ public void makePdf( HttpServletRequest request, HttpServletResponse response, String methodGetPost) { try { // take the message from the URL or create default message String msg = request.getParameter("msg"); if (msg == null || msg.trim().length() <= 0) msg = "[ specify a message in the 'msg' argument on the URL ]"; // create simple doc and write to a ByteArrayOutputStream Document document = new Document(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(document, baos); document.open(); document.add(new Paragraph(msg)); document.add(Chunk.NEWLINE); document.add(new Paragraph("The method used to generate this PDF was: " + methodGetPost)); document.close(); // setting some response headers response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); // setting the content type response.setContentType("application/pdf"); // the contentlength is needed for MSIE!!! response.setContentLength(baos.size()); // write ByteArrayOutputStream to the ServletOutputStream ServletOutputStream out = response.getOutputStream(); baos.writeTo(out); out.flush(); } catch (Exception e2) { System.out.println("Error in " + getClass().getName() + "\n" + e2); } }