List of usage examples for com.itextpdf.text.pdf PdfContentByte addTemplate
public void addTemplate(final PdfTemplate template, final double x, final double y)
From source file:pdf.SplitPDF.java
public static void splitPDF(InputStream inputStream, OutputStream outputStream, int fromPage, int toPage) { Document document = new Document(); try {//from w w w .j a v a 2s .c om PdfReader inputPDF = new PdfReader(inputStream); int totalPages = inputPDF.getNumberOfPages(); //make fromPage equals to toPage if it is greater if (fromPage > toPage) { fromPage = toPage; } if (toPage > totalPages) { toPage = totalPages; } // Create a writer for the outputstream PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); PdfContentByte cb = writer.getDirectContent(); // Holds the PDF data PdfImportedPage page; while (fromPage <= toPage) { document.newPage(); page = writer.getImportedPage(inputPDF, fromPage); cb.addTemplate(page, 0, 0); fromPage++; } outputStream.flush(); document.close(); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (document.isOpen()) { document.close(); } try { if (outputStream != null) { outputStream.close(); } } catch (IOException ioe) { ioe.printStackTrace(); } } }
From source file:ptolemy.vergil.basic.export.itextpdf.ExportPDFAction.java
License:Open Source License
/** Export PDF to a file. * This uses the iText library at http://itextpdf.com/. * * <p>If {@link ptolemy.gui.PtGUIUtilities#useFileDialog()} returns true * then a java.awt.FileDialog is used, otherwise a javax.swing.JFileChooser * is used.</p>/*from w w w . j a v a2s . c o m*/ */ private void _exportPDF() { Dimension size = _frame.getContentSize(); Rectangle pageSize = null; try { pageSize = new Rectangle(size.width, size.height); } catch (Throwable ex) { // This exception will occur if the iText library is not installed. MessageHandler.error("iText library is not installed. See http://itextpdf.com/." + " You must have iText.jar in your classpath. Sometimes, " + "iText.jar may be found in $PTII/vendors/itext/iText.jar.", ex); return; } Document document = new Document(pageSize); JFileChooserBugFix jFileChooserBugFix = new JFileChooserBugFix(); Color background = null; PtFileChooser ptFileChooser = null; try { background = jFileChooserBugFix.saveBackground(); ptFileChooser = new PtFileChooser(_frame, "Specify a pdf file to be written.", JFileChooser.SAVE_DIALOG); LinkedList extensions = new LinkedList(); extensions.add("pdf"); ptFileChooser.addChoosableFileFilter(new ExtensionFilenameFilter(extensions)); BasicGraphFrame basicGraphFrame = null; if (_frame instanceof BasicGraphFrame) { basicGraphFrame = (BasicGraphFrame) _frame; ptFileChooser.setCurrentDirectory(basicGraphFrame.getLastDirectory()); ptFileChooser.setSelectedFile(new File(basicGraphFrame.getModel().getName() + ".pdf")); } int returnVal = ptFileChooser.showDialog(_frame, "Export PDF"); if (returnVal == JFileChooser.APPROVE_OPTION) { if (basicGraphFrame != null) { basicGraphFrame.setLastDirectory(ptFileChooser.getCurrentDirectory()); } File pdfFile = ptFileChooser.getSelectedFile().getCanonicalFile(); if (pdfFile.getName().indexOf(".") == -1) { // If the user has not given the file an extension, add it pdfFile = new File(pdfFile.getAbsolutePath() + ".pdf"); } // The Mac OS X FileDialog will ask if we want to save before this point. if (pdfFile.exists() && !PtGUIUtilities.useFileDialog()) { if (!MessageHandler.yesNoQuestion("Overwrite " + pdfFile.getName() + "?")) { return; } } PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfFile)); // To ensure Latex compatibility, use earlier PDF version. writer.setPdfVersion(PdfWriter.VERSION_1_3); document.open(); PdfContentByte contentByte = writer.getDirectContent(); PdfTemplate template = contentByte.createTemplate(size.width, size.height); Graphics2D graphics = template.createGraphics(size.width, size.height); template.setWidth(size.width); template.setHeight(size.height); Paper paper = new Paper(); paper.setSize(size.width, size.height); paper.setImageableArea(0.0, 0.0, size.width, size.height); PageFormat format = new PageFormat(); format.setPaper(paper); ((Printable) _frame).print(graphics, format, 0); graphics.dispose(); contentByte.addTemplate(template, 0, 0); // Open the PDF file. // FIXME: _read is protected in BasicGraphFrame //_read(pdfFile.toURI().toURL()); // Open the image pdfFile. if (basicGraphFrame == null) { MessageHandler.message("PDF file exported to " + pdfFile.getName()); /* Remove the following. The extra click is annoying... } else { if (MessageHandler.yesNoQuestion("Open \"" + pdfFile.getCanonicalPath() + "\" in a browser?")) { Configuration configuration = basicGraphFrame .getConfiguration(); try { URL imageURL = new URL(pdfFile.toURI().toURL() .toString() + "#in_browser"); configuration.openModel(imageURL, imageURL, imageURL.toExternalForm(), BrowserEffigy.staticFactory); } catch (Throwable throwable) { MessageHandler.error( "Failed to open \"" + pdfFile.getName() + "\".", throwable); } } */ } } } catch (Exception e) { MessageHandler.error("Export to PDF failed", e); } finally { try { document.close(); } finally { jFileChooserBugFix.restoreBackground(background); } } }
From source file:registrosql.Registrar.java
public void PrintFrameToPDF(File file) { try {/*from w ww.j ava 2 s . c o m*/ Document d = new Document(); PdfWriter writer = PdfWriter.getInstance(d, new FileOutputStream(file)); d.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate template = cb.createTemplate(PageSize.LETTER.getWidth(), PageSize.LETTER.getHeight()); cb.addTemplate(template, 0, 0); Graphics2D g2d = template.createGraphics(PageSize.LETTER.getWidth(), PageSize.LETTER.getHeight()); g2d.scale(0.4, 0.4); for (int i = 0; i < this.getContentPane().getComponents().length; i++) { Component c = this.getContentPane().getComponent(i); if (c instanceof JLabel || c instanceof JScrollPane) { g2d.translate(c.getBounds().x, c.getBounds().y); if (c instanceof JScrollPane) { c.setBounds(0, 0, (int) PageSize.LETTER.getWidth() * 2, (int) PageSize.LETTER.getHeight() * 2); } c.paintAll(g2d); c.addNotify(); } } g2d.dispose(); d.close(); } catch (Exception e) { System.out.println("ERROR: " + e.toString()); } }
From source file:se.billes.pdf.renderer.model.Image.java
License:Open Source License
@Override public void onRender(PdfContentByte cb) throws PdfRenderException { ImageInstance instance = null;/*from w w w.ja v a2 s. c o m*/ try { instance = new ImageFactory().getImageByFile(cb, file); } catch (Exception e) { throw new PdfRenderException(e); } float pageHeight = getPage().getPdfDocument().getSize()[1]; float pageWidth = getPage().getPdfDocument().getSize()[0]; float x = 0; float y = 0; float fitHeight = 0f; float imageHeight = 0; float imageWidth = 0; boolean alignImage = false; float[] positions = new BlockFactory().getBoundsInPs(this); float width = positions[2]; float height = positions[3]; com.itextpdf.text.Image image = instance.getImage(); int dpiX = image.getDpiX(); if (dpiX == 0) { dpiX = 300; } if (!new ImageFactory().isPdf(file)) { dpiX = getDotsPerInch(); alignImage = true; // always align jpg } float realPercent = 72f / dpiX * 100; // only jpg if (isScaleToFit()) { image.scaleToFit(width, height); imageHeight = image.getScaledHeight(); imageWidth = image.getScaledWidth(); } else if (isFitContentProportionally()) { image.scaleToFit(width, height); imageHeight = image.getScaledHeight(); imageWidth = image.getScaledWidth(); fitHeight = height - imageHeight; alignImage = true; } else { if (isFillFrameProportionally()) { float percentWidth = width / image.getWidth(); float percentHeight = height / image.getHeight(); realPercent = Math.max(percentHeight, percentWidth) * 100; alignImage = true; if (new ImageFactory().isPdf(file)) { image.scalePercent(realPercent); imageHeight = image.getScaledHeight(); imageWidth = image.getScaledWidth(); fitHeight = height - imageHeight; } } if (isCenterImageToPageWidth() && new ImageFactory().isPdf(file)) { imageWidth = image.getScaledWidth(); float middle = (pageWidth / 2) - (imageWidth / 2); positions[0] = SizeFactory.PostscriptPointsToMillimeters(middle); } if (!new ImageFactory().isPdf(file)) { image.scalePercent(realPercent); imageHeight = image.getScaledHeight(); imageWidth = image.getScaledWidth(); fitHeight = height - imageHeight; } } if (alignImage) { float[] result = handleAlignment(width, imageWidth, height, imageHeight, fitHeight); x = result[0]; y = result[1]; } try { PdfTemplate tp = cb.createTemplate(width, height); image.setAbsolutePosition(x, y); tp.roundRectangle(0, 0, width, height, SizeFactory.millimetersToPostscriptPoints(getRadius())); tp.clip(); tp.newPath(); tp.addImage(image); float left = getPosition()[0]; float top = getPosition()[1]; if (getPage().getPdfDocument().getCutmarks() != null) { left += SizeFactory.CUT_MARK; top -= SizeFactory.CUT_MARK; } cb.addTemplate(tp, SizeFactory.millimetersToPostscriptPoints(left), SizeFactory.millimetersToPostscriptPoints(pageHeight - (top + getPosition()[3]))); if (getBorder() != null) { cb.setLineWidth(SizeFactory.millimetersToPostscriptPoints(getBorder().getThickness())); cb.setColorStroke(getBorder().getBaseColor()); cb.roundRectangle(SizeFactory.millimetersToPostscriptPoints(left), SizeFactory.millimetersToPostscriptPoints(pageHeight - (top + getPosition()[3])), width, height, SizeFactory.millimetersToPostscriptPoints(getRadius())); cb.stroke(); } } catch (Exception e) { throw new PdfRenderException(e); } }
From source file:se.billes.pdf.renderer.request.factory.BlockFactory.java
License:Open Source License
public void createRoundRectangle(PdfContentByte cb, Block block) { PdfDocument request = getPdfDocument(block); float[] positions = getBoundsInPs(block); float[] mmPositions = getBoundsInMMIncludeCutmark(block); PdfTemplate tp = cb.createTemplate(positions[2], positions[3]); tp.roundRectangle(0, 0, positions[2], positions[3], SizeFactory.millimetersToPostscriptPoints(block.getRadius())); // because pdf i calculated from bottom up cb.addTemplate(tp, positions[0], SizeFactory .millimetersToPostscriptPoints(request.getSize()[1] - (mmPositions[1] + mmPositions[3]))); }
From source file:se.billes.pdf.renderer.request.factory.CellBlockEvent.java
License:Open Source License
public PdfPCellEvent createEvent(final Block block) { return new PdfPCellEvent() { public void cellLayout(PdfPCell cell, Rectangle rect, PdfContentByte[] canvas) { float radiusInPs = SizeFactory.millimetersToPostscriptPoints(block.getRadius()); PdfContentByte cb = canvas[PdfPTable.LINECANVAS]; PdfTemplate template = cb.createTemplate(rect.getWidth(), rect.getHeight()); template.roundRectangle(0, 0, rect.getWidth(), rect.getHeight(), radiusInPs); template.clip();/*from w w w .j a v a2 s.c o m*/ template.newPath(); if (block.getBaseColor() != null) { template.setColorFill(block.getBaseColor()); } Border border = block.getBorder(); if (border != null) { template.setLineWidth(SizeFactory.millimetersToPostscriptPoints(border.getThickness())); template.setColorStroke(border.getBaseColor()); } template.roundRectangle(0, 0, rect.getWidth(), rect.getHeight(), radiusInPs); if (block.getBaseColor() != null || border != null) { if (block.getBaseColor() != null && border != null) { template.fillStroke(); } else if (block.getBaseColor() != null) { template.fill(); } else { template.stroke(); } } cb.addTemplate(template, rect.getLeft(), rect.getBottom()); } }; }
From source file:shared.SVGtoPDF.java
License:Open Source License
/** * Creates a PDF document.//from w w w . jav a 2 s.c o m * @param path * @param filename the path to the new PDF document * @throws DocumentException * @throws IOException * @throws SQLException */ public void createPdf(String svgDocument, Point size, String path) throws IOException, DocumentException { svgDocument = convertSVG(svgDocument); Document document = new Document(new Rectangle(size.x, size.y)); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path)); //writer.setRgbTransparencyBlending(false); writer.setDefaultColorspace(PdfName.DEFAULTCMYK, PdfName.DEFAULTCMYK); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate template = cb.createTemplate(size.x, size.y); drawSvg(svgDocument, template, size); cb.addTemplate(template, 0, 0); // step 5 document.close(); }
From source file:sim.util.media.PDFEncoder.java
License:Academic Free License
public static void generatePDF(Component component, File file) { int width = component.getWidth(); int height = component.getHeight(); try {//from ww w . j a v a 2 s.c o m Document document = new Document(new com.lowagie.text.Rectangle(width, height)); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); document.addAuthor("MASON"); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics g2 = tp.createGraphics(width, height, new DefaultFontMapper()); component.paint(g2); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:sim.util.media.PDFEncoder.java
License:Academic Free License
public static void generatePDF(JFreeChart chart, int width, int height, File file) { try {/*from ww w. ja v a2s.com*/ Document document = new Document(new com.lowagie.text.Rectangle(width, height)); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); document.addAuthor("MASON"); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height); chart.draw(g2, rectangle2D); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:sistemacontrole.MainWindow.java
public void MainClass() throws Exception { Document document = new Document(); PdfWriter writer;/* w w w .java2 s .co m*/ writer = PdfWriter.getInstance(document, new FileOutputStream("my_jtable_shapes.pdf")); // writer = PdfWriter.getInstance(document, new // FileOutputStream("my_jtable_fonts.pdf")); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(500, 500); Graphics2D g2; g2 = tp.createGraphicsShapes(500, 500); // g2 = tp.createGraphics(500, 500); this.tabelaDetalhes.print(g2); g2.dispose(); cb.addTemplate(tp, 30, 300); // step 5: we close the document document.close(); }