List of usage examples for com.itextpdf.text.pdf PdfWriter getDirectContent
public PdfContentByte getDirectContent()
From source file:Modelo.CotizacionDAO.java
public void writePdf(OutputStream outputStream, Cotizacion x, int idcotizacion) throws Exception { DateFormat df = new SimpleDateFormat("dd/MM/YYYY"); Calendar cdos = Calendar.getInstance(); Date datediamas = new Date(); Date dateaniomas = new Date(); cdos.add(Calendar.DATE, 1);/*from w w w.j av a 2s . c o m*/ datediamas = cdos.getTime(); String fechadiamas = df.format(datediamas); cdos.add(Calendar.YEAR, 1); dateaniomas = cdos.getTime(); String fechavencimiento = df.format(dateaniomas); Document document = new Document(PageSize.LETTER, 50, 50, 50, 30); Font boldFontTitulo = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD); Font boldFontTexto = new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD); Font FontTexto = new Font(Font.FontFamily.HELVETICA, 10); // document.setPageSize(null); PdfWriter writer = PdfWriter.getInstance(document, outputStream); Image imagen = Image.getInstance("http://54.67.56.185/BSeguros_pa18/img/BSeguroLogo.png"); // Image imagen = Image.getInstance("D:\\ALEX\\Bseguros\\web\\img\\Aseguradoras\\BSeguroLogo.png"); Image imagen2 = Image.getInstance( "http://54.67.56.185/BSeguros_pa18/img/Aseguradoras/" + x.getId_aseguradora() + ".png"); //Image imagen2 = Image.getInstance("D:\\ALEX\\Bseguros\\web\\img\\Aseguradoras\\Mapfre.png"); document.open(); PdfContentByte canvas = writer.getDirectContent(); Rectangle rect = new Rectangle(36, 36, 579, 756); rect.setBorder(Rectangle.BOX); rect.setBorderWidth(2); canvas.rectangle(rect); document.addTitle("Cotizacion"); document.addSubject("Cotizacion"); document.addKeywords("Cotizacion, seguros"); document.addAuthor("BSeguro"); document.addCreator("Bseguro"); imagen.scaleAbsoluteHeight(30f); imagen.setAbsolutePosition(45f, 720f); imagen2.scaleAbsoluteHeight(30f); imagen2.setAbsolutePosition(450f, 720f); document.add(imagen); document.add(imagen2); Paragraph paragraph2 = new Paragraph("DATOS DE TU POLIZA", boldFontTitulo); paragraph2.setAlignment(Element.ALIGN_CENTER); document.add(paragraph2); //creas una tabla con un ancho de 3 celdas, el salto a la siguiente fila sera automatico PdfPTable table = new PdfPTable(3); table.getDefaultCell().setBorder(0); PdfPCell cell; Paragraph saltodelinea = new Paragraph(" "); document.add(saltodelinea); document.add(new Paragraph(" Datos de tu poliza folio: " + "BC" + x.getId_aseguradora().substring(0, 1) + x.getMetododepago().substring(0, 1) + ": 0000" + idcotizacion, boldFontTitulo)); document.add(new Paragraph(" Vigencia de la poliza del: " + fechadiamas + " al: " + fechavencimiento, boldFontTitulo)); document.add(saltodelinea); document.add(new Paragraph(" Datos del Contratante: ", boldFontTitulo)); //document.add(saltodelinea); //agrego otra tabla table = new PdfPTable(6); table.setWidthPercentage(100); table.getDefaultCell().setBorder(0); table.addCell(new Paragraph("Nombre: ", boldFontTexto)); PdfPCell celdaNombre = new PdfPCell( new Paragraph(x.getNombre_contratante() + " " + x.getApellido_paterno(), FontTexto)); celdaNombre.setColspan(5); celdaNombre.setBorder(0); table.addCell(celdaNombre); table.addCell(new Paragraph("RFC : ", boldFontTexto)); PdfPCell celdaRFC = new PdfPCell(new Paragraph(x.getRfc(), FontTexto)); celdaRFC.setColspan(5); celdaRFC.setBorder(0); table.addCell(celdaRFC); table.addCell(new Paragraph("Direccion: ", boldFontTexto)); PdfPCell celdaDir = new PdfPCell( new Paragraph(x.getCall() + ", " + x.getNo_ext() + ", " + x.getNo_int() + ", " + x.getColonia() + ", " + x.getDelegacion() + ", " + x.getEstado() + ", " + x.getCp(), FontTexto)); celdaDir.setColspan(5); celdaDir.setBorder(0); table.addCell(celdaDir); table.addCell(new Paragraph("Email: ", boldFontTexto)); table.addCell(AddCell(x.getMail(), 5)); table.addCell(new Paragraph("Telefono ", boldFontTexto)); PdfPCell celdaTel = new PdfPCell(new Paragraph(x.getTelefono(), FontTexto)); celdaTel.setColspan(5); celdaTel.setBorder(0); table.addCell(celdaTel); document.add(table); document.add(saltodelinea); document.add(new Paragraph(" Datos del Vehiculo: ", boldFontTitulo)); // document.add(saltodelinea); //agrego otra tabla table = new PdfPTable(6); table.setWidthPercentage(100); table.getDefaultCell().setBorder(0); table.addCell(new Paragraph("Marca: ", boldFontTexto)); table.addCell(AddCell(x.getId_marca(), 5)); table.addCell(new Paragraph("Modelo:", boldFontTexto)); table.addCell(AddCell(x.getId_anio().toString(), 5)); table.addCell(new Paragraph("Tipo: ", boldFontTexto)); table.addCell(AddCell(x.getId_submarca(), 5)); table.addCell(new Paragraph("Version: ", boldFontTexto)); table.addCell(AddCell(x.getId_modelo(), 5)); table.addCell(new Paragraph("No. De Serie: ", boldFontTexto)); table.addCell(AddCell(x.getSerie(), 5)); document.add(table); document.add(saltodelinea); document.add(new Paragraph(" Informacion de la Poliza: ", boldFontTitulo)); // document.add(saltodelinea); //agrego otra tabla table = new PdfPTable(6); table.setWidthPercentage(100); table.getDefaultCell().setBorder(0); table.addCell(new Paragraph("Pago: ", boldFontTexto)); table.addCell(AddCell(x.getTipo_pago(), 5)); table.addCell(new Paragraph("Aseguradora: ", boldFontTexto)); table.addCell(AddCell(x.getId_aseguradora(), 5)); document.add(table); document.add(saltodelinea); document.add(new Paragraph(" Detalles de la Cobertura: Cobertura Amplia ", boldFontTitulo)); // document.add(saltodelinea); //agrego otra tabla table = new PdfPTable(3); table.setWidthPercentage(100); table.getDefaultCell().setBorder(0); table.addCell(new Paragraph("Cobertura ", boldFontTexto)); table.addCell(new Paragraph("Responsabilidad Civil", boldFontTexto)); table.addCell(new Paragraph("Deducible ", boldFontTexto)); table.addCell(new Paragraph("Daos Materiales", FontTexto)); table.addCell(new Paragraph("Valor Comercial", FontTexto)); table.addCell(new Paragraph("5%", FontTexto)); table.addCell(new Paragraph("Robo Total", FontTexto)); table.addCell(new Paragraph("Valor Comercial", FontTexto)); table.addCell(new Paragraph("10%", FontTexto)); table.addCell(new Paragraph("Responsabilidad Civil", FontTexto)); table.addCell(new Paragraph("$4,000,000.00", FontTexto)); table.addCell(new Paragraph("", FontTexto)); table.addCell(new Paragraph("Gastos Medicos Ocupantes", FontTexto)); table.addCell(new Paragraph("$500,000.00", FontTexto)); table.addCell(new Paragraph("", FontTexto)); table.addCell(new Paragraph("Asistencia Legal", FontTexto)); table.addCell(new Paragraph("Amparada", FontTexto)); table.addCell(new Paragraph("", FontTexto)); table.addCell(new Paragraph("Asistencia Vial", FontTexto)); table.addCell(new Paragraph("Amparada", FontTexto)); table.addCell(new Paragraph("", FontTexto)); document.add(table); document.add(saltodelinea); document.add(new Paragraph(" Informacion del Pago ", boldFontTitulo)); document.add(new Paragraph(" Instrumento de Pago: " + x.getMetododepago(), boldFontTexto)); //agrego otra tabla table = new PdfPTable(6); table.setWidthPercentage(100); table.getDefaultCell().setBorder(0); table.addCell(AddCell("Concepto ", 2)); table.addCell(AddCell("Monto", 4)); table.addCell(AddCell("Prima Total ", 2)); table.addCell(AddCell(x.getMonto(), 4)); table.addCell(AddCell("Prima Inicial", 2)); table.addCell(AddCell(x.getMonto(), 4)); table.addCell(AddCell("Pago Subsecuente ", 2)); table.addCell(AddCell("0", 4)); document.add(table); document.add(saltodelinea); if (x.getCobertura_auto_siempre() == true) { document.add(new Paragraph(" Informacion de Modulos HDI ", boldFontTitulo)); table = new PdfPTable(6); table.setWidthPercentage(100); table.getDefaultCell().setBorder(0); table.addCell(AddCell("Modulos ", 2)); table.addCell(AddCell("Contratados", 4)); table.addCell(AddCell("HDI - Autos por Siempre ", 2)); table.addCell(AddCell("$ 1,799.00", 4)); document.add(table); } else { if (x.getCobertura_auto_amante() == true) { document.add(new Paragraph(" Informacion de Modulos HDI ", boldFontTitulo)); table = new PdfPTable(6); table.setWidthPercentage(100); table.getDefaultCell().setBorder(0); table.addCell(AddCell("Modulos ", 2)); table.addCell(AddCell("Contratados", 4)); table.addCell(AddCell("HDI - Amante de los Autos ", 2)); table.addCell(AddCell("$ 1,799.00", 4)); document.add(table); } else { } document.add(saltodelinea); } document.add(new Paragraph("* Estaras asegurado a partir de las 12 horas del siguiente dia habil.", boldFontTexto)); document.close(); }
From source file:mymoney.Multi_cal.java
private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton11ActionPerformed getContentPane().setLayout(new BorderLayout()); DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); JFileChooser cho = new JFileChooser(); cho.showSaveDialog(null);// w w w .jav a 2 s . co m File f = cho.getSelectedFile(); String filename = f.getAbsolutePath(); com.itextpdf.text.Document document = new com.itextpdf.text.Document(); try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename + ".pdf")); document.open(); PdfContentByte cb = writer.getDirectContent(); cb.saveState(); PdfTemplate pdfTemplate = cb.createTemplate(jTable1.getWidth(), jTable1.getHeight()); Graphics2D g2 = cb.createGraphicsShapes(800, 500); Shape oldClip = g2.getClip(); g2.clipRect(0, 0, 800, 500); jTable1.print(g2); g2.setClip(oldClip); g2.dispose(); cb.restoreState(); JOptionPane.showMessageDialog(null, "Data Exported to pdf"); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error"); } document.close(); // TODO add your handling code here: }
From source file:mymoney.view.java
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed getContentPane().setLayout(new BorderLayout()); DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); JFileChooser cho = new JFileChooser(); cho.showSaveDialog(null);/* w w w. j av a 2s . c om*/ File f = cho.getSelectedFile(); String filename = f.getAbsolutePath(); com.itextpdf.text.Document document = new com.itextpdf.text.Document(); try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename + ".pdf")); document.open(); PdfContentByte cb = writer.getDirectContent(); cb.saveState(); PdfTemplate pdfTemplate = cb.createTemplate(jTable1.getWidth(), jTable1.getHeight()); Graphics2D g2 = cb.createGraphicsShapes(800, 500); Shape oldClip = g2.getClip(); g2.clipRect(0, 0, 800, 500); jTable1.print(g2); g2.setClip(oldClip); g2.dispose(); cb.restoreState(); JOptionPane.showMessageDialog(null, "Data Exported to pdf"); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error"); } document.close(); // TODO add your handling code here: }
From source file:mymoney.view.java
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed getContentPane().setLayout(new BorderLayout()); DefaultTableModel model = (DefaultTableModel) jTable2.getModel(); JFileChooser cho = new JFileChooser(); cho.showSaveDialog(null);/*from ww w. ja v a 2 s.c o m*/ File f = cho.getSelectedFile(); String filename = f.getAbsolutePath(); com.itextpdf.text.Document document = new com.itextpdf.text.Document(); try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename + ".pdf")); document.open(); PdfContentByte cb = writer.getDirectContent(); cb.saveState(); PdfTemplate pdfTemplate = cb.createTemplate(jTable2.getWidth(), jTable2.getHeight()); Graphics2D g2 = cb.createGraphicsShapes(800, 500); Shape oldClip = g2.getClip(); g2.clipRect(0, 0, 800, 500); jTable2.print(g2); g2.setClip(oldClip); g2.dispose(); cb.restoreState(); JOptionPane.showMessageDialog(null, "Data Exported to pdf"); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error"); } document.close(); // TODO add your handling code here: }
From source file:net.algem.billing.InvoiceView.java
License:Open Source License
private void drawPdf(Document document, PdfWriter writer) { PdfContentByte cb = writer.getDirectContent(); Graphics2D g = cb.createGraphics(document.getPageSize().getWidth(), document.getPageSize().getHeight()); Quote quote = get();/*from ww w . j a va 2s .co m*/ String genericLabel = invoice.getClass() == Quote.class ? BundleUtil.getLabel("Quotation.label") : BundleUtil.getLabel("Invoice.label"); int left = ImageUtil.mmToPoints(110); int top = ImageUtil.mmToPoints(50); int bottom = ImageUtil.mmToPoints(297 - 20);// hauteur de page - 20 mm de marge int margin = ImageUtil.mmToPoints(15); Font defaultFont = g.getFont(); g.setFont(serif); int itemsHeight = ((g.getFontMetrics().getHeight() * 2) * (quote.getItems().size() - 1)); // average int footerHeight = InvoiceFooterEditor.getFooter().size() * 10; int maxHeight = top + 160 + 20 + itemsHeight + ImageUtil.mmToPoints(50); drawHeader(g, defaultFont, quote, genericLabel, top, left, margin); int tablebottom = drawContent(g, quote, top, margin); if (maxHeight > (bottom - footerHeight)) { g.setFont(serif.deriveFont(Font.ITALIC)); g.drawString(MessageUtil.getMessage("see.back.page.label"), margin, tablebottom + 10); drawFooter(g, margin, bottom); //IMPORTANT g.dispose(); document.newPage(); g = cb.createGraphics(document.getPageSize().getWidth(), document.getPageSize().getHeight()); g.setFont(serif.deriveFont(Font.ITALIC)); g.drawString("(page 2)", margin, top + 90); g.setFont(serif); g.drawString(genericLabel + " : " + quote.getNumber(), margin, top + 100); // description g.drawString(BundleUtil.getLabel("Invoice.description.label") + " : " + quote.getDescription(), margin, top + 140); // pied tableau new InvoiceFooterElement(margin, top + 160, quote).draw(g); // infos lgales drawFooter(g, margin, bottom); g.dispose(); } else { // pied tableau new InvoiceFooterElement(margin, tablebottom + 20, quote).draw(g); // infos lgales drawFooter(g, margin, bottom); g.dispose(); } }
From source file:net.FilterLogic.imaging.ToPDF.java
License:Apache License
private void writeMultiPagePDF(String fileName) throws Exception { float STD_WIDTH = 620; float STD_HEIGHT = 775; float newWidth = 0; float newHeight = 0; float xPos = 0; float yPos = 0; boolean scaleImage = true; boolean pdfAutoOrientation = true; boolean autoCenter = false; boolean portrait = true; BufferedImage img = null;//from www . j a v a2s . c om Document pdf; PdfWriter writer; try { // scale image String si = this.documentProperties.getProperty(KEY_SCALE_TO_FIT, KEY_SCALE_TO_FIT_DEFAULT); scaleImage = Boolean.parseBoolean(si); // auto-orientation String ao = this.documentProperties.getProperty(KEY_AUTO_ORIENTATION, KEY_AUTO_ORIENTATION_DEFAULT); pdfAutoOrientation = Boolean.parseBoolean(ao); // auto-center String ac = this.documentProperties.getProperty(KEY_AUTO_CENTER, KEY_AUTO_CENTER_DEFAULT); autoCenter = Boolean.parseBoolean(ac); if (document.size() > 0) img = document.get(0); if (img != null) { // if dpi set, calculate new width/height if (horizontalDPI > 0 && verticalDPI > 0) { float xd = (float) horizontalDPI / 100; float yd = (float) verticalDPI / 100; newWidth = img.getWidth() / xd; newHeight = img.getHeight() / yd; } else { newWidth = img.getWidth(); newHeight = img.getHeight(); } // if image width or height changed, scale if (newWidth != img.getWidth() || newHeight != img.getHeight()) scaleImage = true; // if auto orientation, set portrait or landscape if (pdfAutoOrientation) { if (newWidth >= newHeight) { pdf = new Document(PageSize.LETTER.rotate()); portrait = false; } else { pdf = new Document(PageSize.LETTER); portrait = true; } } else { // else, always portrait pdf = new Document(PageSize.LETTER); portrait = true; } writer = PdfWriter.getInstance(pdf, new FileOutputStream(fileName)); writer.setFullCompression(); pdf.open(); // set document props setDocumentProperties(pdf); int t = 0; float pdfPageWidth = pdf.getPageSize().getWidth(); float pdfPageHeight = pdf.getPageSize().getHeight(); // if new image larger than standard size, override and enable image scaling if (newWidth > pdfPageWidth || newHeight > pdfPageHeight) { scaleImage = true; if (newWidth > pdfPageWidth) newWidth = pdfPageWidth; if (newHeight > pdfPageHeight) newHeight = pdfPageHeight; } // break out each page to single file while (t < totalPages) { PdfContentByte cb = writer.getDirectContent(); com.itextpdf.text.Image pdfImage; if (img != null) { pdfImage = com.itextpdf.text.Image.getInstance(img, null); // calculate center if (autoCenter) { if (portrait) { xPos = (pdfPageWidth - newWidth) / 2; yPos = (pdfPageHeight - newHeight) / 2; } else { //xPos = ((pdfPageHeight * (float)1.60) - newWidth) / 2; xPos = (pdfPageHeight - newWidth) / 2; yPos = (pdfPageWidth - newHeight) / 2; } } else { // if not scaling, set image to top left if (!scaleImage) { xPos = 0; // calculate top left corner yPos = pdfPageWidth - newHeight; } else { xPos = 0; yPos = 0; } } // check if x and y pos >=0 if (xPos < 0) xPos = 0; if (yPos < 0) yPos = 0; if (scaleImage) { if (!portrait) { pdfImage.scaleToFit(newHeight, newWidth); } else { pdfImage.scaleToFit(newWidth, newHeight); } // check is scaled height/width match new width/height // if not, recalculate center if autcenter enabled. if (newWidth != pdfImage.getScaledWidth() || newHeight != pdfImage.getScaledHeight()) { newWidth = pdfImage.getScaledWidth(); newHeight = pdfImage.getScaledHeight(); // calculate center if (autoCenter) { xPos = (pdfPageWidth - newWidth) / 2; yPos = (pdfPageHeight - newHeight) / 2; // check if x and y pos >=0 if (xPos < 0) xPos = 0; if (yPos < 0) yPos = 0; } } pdfImage.setAbsolutePosition(xPos, yPos); } else { pdfImage.setAbsolutePosition(xPos, yPos); } cb.addImage(pdfImage); // inc counter ++t; if (t < totalPages) { img = document.get(t); // if dpi set, calculate new width/height if (horizontalDPI > 0 && verticalDPI > 0) { float xd = (float) horizontalDPI / 100; float yd = (float) verticalDPI / 100; newWidth = img.getWidth() / xd; newHeight = img.getHeight() / yd; } else { newWidth = img.getWidth(); newHeight = img.getHeight(); } // if auto orientation, set portrait or landscape if (pdfAutoOrientation) { if (newWidth >= newHeight) { pdf.setPageSize(PageSize.LETTER.rotate()); portrait = false; } else { pdf.setPageSize(PageSize.LETTER); portrait = true; } } else { // else, always portrait pdf.setPageSize(PageSize.LETTER); portrait = true; } // create new page. must happen after setting page orientation pdf.newPage(); writer.newPage(); // get new pages width/height pdfPageWidth = pdf.getPageSize().getWidth(); pdfPageHeight = pdf.getPageSize().getHeight(); // set width/height to something normal if (newWidth > pdfPageWidth) newWidth = pdfPageWidth; if (newHeight > pdfPageHeight) newHeight = pdfPageHeight; } } } pdf.close(); // add file name to list fileNames = new ArrayList<String>(); fileNames.add(fileName); } } catch (Exception e) { throw new Exception(e); } }
From source file:net.panthema.BispanningGame.GamePanel.java
License:Open Source License
public void writePdf() throws FileNotFoundException, DocumentException { // Query user for filename JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle("Specify PDF file to save"); chooser.setCurrentDirectory(new File(".")); FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF Documents", "pdf"); chooser.setFileFilter(filter);// w ww . java 2 s.c o m if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return; File outfile = chooser.getSelectedFile(); if (!outfile.getAbsolutePath().endsWith(".pdf")) { outfile = new File(outfile.getAbsolutePath() + ".pdf"); } // Calculate page size rectangle Dimension size = mVV.getSize(); Rectangle rsize = new Rectangle(size.width, size.height); // Open the PDF file for writing - and create a Graphics2D object Document document = new Document(rsize); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outfile)); document.open(); PdfContentByte contentByte = writer.getDirectContent(); PdfGraphics2D graphics2d = new PdfGraphics2D(contentByte, size.width, size.height, new DefaultFontMapper()); // Create a container to hold the visualization Container container = new Container(); container.addNotify(); container.add(mVV); container.setVisible(true); container.paintComponents(graphics2d); // Dispose of the graphics and close the document graphics2d.dispose(); document.close(); // Put mVV back onto visible plane setLayout(new BorderLayout()); add(mVV, BorderLayout.CENTER); }
From source file:net.pickapack.chart.ChartPdfExporter.java
License:Open Source License
/** * Export the specified chart to the specified PDF file. * * @param chart the chart/*from ww w. j a v a2 s.co m*/ * @param width the width of the PDF file * @param height the height of the PDF file * @param fileName the PDF file name */ public static void exportPdf(JFreeChart chart, int width, int height, String fileName) { try { Document document = new Document(new Rectangle(width, height)); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName)); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2d = tp.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D r2d = new Rectangle2D.Double(0, 0, width, height); chart.draw(g2d, r2d); g2d.dispose(); cb.addTemplate(tp, 0, 0); document.close(); } catch (DocumentException e) { throw new RuntimeException(e); } catch (FileNotFoundException e) { throw new RuntimeException(e); } }
From source file:net.sf.mzmine.chartbasics.graphicsexport.ChartExportUtil.java
License:Open Source License
/** * This method saves a chart as a PDF with given dimensions * //from www. jav a2 s. c o m * @param chart * @param width * @param height * @param fileName is a full path */ public static void writeChartToPDF(JFreeChart chart, int width, int height, File fileName) throws Exception { PdfWriter writer = null; Document document = new Document(new Rectangle(width, height)); try { writer = PdfWriter.getInstance(document, new FileOutputStream(fileName)); document.open(); PdfContentByte contentByte = writer.getDirectContent(); PdfTemplate template = contentByte.createTemplate(width, height); Graphics2D graphics2d = template.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width, height); chart.draw(graphics2d, rectangle2d); graphics2d.dispose(); contentByte.addTemplate(template, 0, 0); } catch (Exception e) { e.printStackTrace(); throw e; } finally { document.close(); } }
From source file:nz.ac.waikato.cms.doc.HyperLinkGrades.java
License:Open Source License
/** * Adds the index with locations to the existing PDF. * * @param locations the locations to index * @param input the input PDF// w w w. j a va 2 s . c o m * @param output the output PDF * @return true if successfully generated */ public static boolean addIndex(List<Location> locations, File input, File output) { try { // copy pages, add target PdfReader reader = new PdfReader(input.getAbsolutePath()); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(output.getAbsolutePath())); document.open(); PdfContentByte canvas = writer.getDirectContent(); PdfImportedPage page; float height = 0; for (int i = 1; i <= reader.getNumberOfPages(); i++) { document.newPage(); page = writer.getImportedPage(reader, i); canvas.addTemplate(page, 1f, 0, 0, 1, 0, 0); Chunk loc = new Chunk(" "); loc.setLocalDestination("loc" + i); height = page.getHeight(); ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(loc), 50, height - 50, 0); } // add index for (int i = 0; i < locations.size(); i++) { Location loc = locations.get(i); if (i % MAX_ITEMS_PER_PAGE == 0) document.newPage(); String text = loc.getID() + " " + (loc.getName() == null ? "???" : loc.getName()); Chunk chunk = new Chunk("Page " + (loc.getPage() + 1) + ": " + text); chunk.setAction(PdfAction.gotoLocalPage("loc" + (loc.getPage() + 1), false)); ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(chunk), 50, height - 100 - (i % MAX_ITEMS_PER_PAGE) * 20, 0); } document.close(); return true; } catch (Exception e) { System.err.println("Failed to overlay locations!"); e.printStackTrace(); return false; } }