List of usage examples for com.itextpdf.text.pdf PdfContentByte createTemplate
public PdfTemplate createTemplate(final float width, final float height)
From source file:org.orbisgis.core.ui.plugins.editors.mapEditor.ExportMapAsPDFPlugIn.java
License:Open Source License
public void save(File outputFile, Scale scale, BufferedImage img, Envelope envelope, ILayer layer) { int width = img.getWidth(); int height = img.getHeight(); Document document = new Document(PageSize.A4.rotate()); EditorManager em = Services.getService(EditorManager.class); MapEditorPlugIn mapEditor = (MapEditorPlugIn) em.getActiveEditor(); MapContext mapContext = (MapContext) mapEditor.getElement().getObject(); try {/*from w w w. j a v a 2 s . c om*/ Renderer r = new Renderer(); if (outputFile.getName().toLowerCase().endsWith("pdf")) { //$NON-NLS-1$ FileOutputStream fos = new FileOutputStream(outputFile); PdfWriter writer = PdfWriter.getInstance(document, fos); document.open(); float pageWidth = document.getPageSize().getWidth(); float pageHeight = document.getPageSize().getHeight(); // Add the north final java.net.URL url = IconLoader.getIconUrl("simplenorth.png"); //$NON-NLS-1$ PdfContentByte cb = writer.getDirectContent(); PdfTemplate templateMap = cb.createTemplate(pageWidth, pageHeight); PdfTemplate templateLegend = cb.createTemplate(150, pageHeight); PdfTemplate templateScale = cb.createTemplate(pageWidth, 50); Graphics2D g2dLegend = templateLegend.createGraphicsShapes(150, pageHeight); Graphics2D g2dMap = templateMap.createGraphicsShapes(pageWidth, pageHeight); Graphics2D g2dScale = templateScale.createGraphicsShapes(pageWidth, 50); g2dMap.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); r.draw(g2dMap, width, height, envelope, layer, new NullProgressMonitor()); ILayer[] layers = mapContext.getLayerModel().getLayersRecursively(); g2dLegend.setColor(Color.BLACK); g2dLegend.drawRect(0, 0, 150, (int) pageHeight); g2dLegend.setColor(Color.white); g2dLegend.fillRect(0, 0, 150, (int) pageHeight); g2dLegend.setColor(Color.BLACK); int maxHeight = 30; g2dLegend.translate(10, 10); g2dLegend.drawString(I18N.getString("orbisgis.org.orbisgis.ui.map.exportMapAsPDFPlugIn.legend"), 0, //$NON-NLS-1$ 10); for (int i = 0; i < layers.length; i++) { g2dLegend.translate(0, maxHeight + 10); maxHeight = 0; if (layers[i].isVisible()) { Legend[] legends = layers[i].getRenderingLegend(); g2dLegend.drawString(layers[i].getName(), 0, 0); for (int j = 0; j < legends.length; j++) { Legend vectorLegend = legends[j]; vectorLegend.drawImage(g2dLegend); int[] size = vectorLegend.getImageSize(g2dLegend); if (size[1] > maxHeight) { maxHeight = size[1]; } g2dLegend.translate(0, 20); } } } g2dScale.translate(150, 0); g2dScale.setColor(Color.BLACK); g2dScale.drawRect(0, 0, (int) pageWidth, 50); g2dScale.setColor(Color.white); g2dScale.fillRect(0, 0, (int) pageWidth, 50); g2dScale.setColor(Color.BLACK); g2dScale.translate(30, 10); // draw scale if (scale != null) { scale.drawScale(g2dScale, 90); } BufferedImage image = ImageIO.read(url); AffineTransform tx = new AffineTransform(); tx.scale(0.5, 0.5); AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR); image = op.filter(image, null); g2dScale.drawImage(image, 200, 0, null); g2dMap.dispose(); g2dLegend.dispose(); g2dScale.dispose(); cb.addTemplate(templateMap, 0, 0); cb.addTemplate(templateLegend, 0, 0); cb.addTemplate(templateScale, 0, 0); JOptionPane.showMessageDialog(UIFactory.getMainFrame(), I18N.getString("orbisgis.core.file.fileSaved")); //$NON-NLS-1$ } } catch (FileNotFoundException e) { ErrorMessages.error(ErrorMessages.CannotWriteOnDisk, e); } catch (DocumentException e) { ErrorMessages.error(ErrorMessages.CannotWritePDF, e); } catch (Exception e) { ErrorMessages.error(ErrorMessages.CannotWritePDF, e); } document.close(); }
From source file:org.orbisgis.core_export.GeoSpatialPDF.java
License:Open Source License
/** * Process all layers in the layermodel and build the corresponding pdf tree * layer/* w w w. ja v a 2s . c o m*/ * * @param layer */ private void processSubLayer(ILayer layer, MapTransform mt, PdfWriter writer, PdfContentByte cb, ProgressMonitor pm, PdfLayer mainLayer) { if (layer.acceptsChilds() && layer.getLayerCount() > 0) { PdfLayer groupLayer = new PdfLayer(layer.getName(), writer); //To manage group of layers for (ILayer subLayer : layer.getChildren()) { processSubLayer(subLayer, mt, writer, cb, pm, groupLayer); } } else { if (layer.isVisible() && layer.getEnvelope().intersects(mt.getAdjustedExtent())) { PdfLayer mapLayer = new PdfLayer(layer.getName(), writer); if (mainLayer != null) { mainLayer.addChild(mapLayer); } PdfTemplate layerTemplate = cb.createTemplate(width, height); Graphics2D g2dLayer = layerTemplate.createGraphics(width, height); cb.beginLayer(mapLayer); PdfRenderer renderer2 = new PdfRenderer(layerTemplate, width, height); renderer2.draw(mt, g2dLayer, (int) width, (int) height, layer, pm); cb.addTemplate(layerTemplate, 0, 0); g2dLayer.dispose(); cb.endLayer(); } } }
From source file:org.orbisgis.mapcomposer.controller.utils.exportThreads.ExportPDFThread.java
License:Open Source License
@Override public void run() { try {/*from ww w. j av a2s. co m*/ Document pdfDocument = null; //Find the Document GE to create the BufferedImage where all the GE will be drawn for (GraphicalElement ge : geIsVectorMap.keySet()) { if (ge instanceof org.orbisgis.mapcomposer.model.graphicalelement.element.Document) { pdfDocument = new Document(new Rectangle(ge.getWidth(), ge.getHeight())); height = ge.getHeight(); } } //If no Document was created, throw an exception if (pdfDocument == null) { throw new IllegalArgumentException(i18n.tr( "Error on export : The list of GraphicalElement to export does not contain any Document GE.")); } //Open the document PdfWriter writer = PdfWriter.getInstance(pdfDocument, new FileOutputStream(path)); writer.setUserProperties(true); writer.setRgbTransparencyBlending(true); writer.setTagged(); pdfDocument.open(); PdfContentByte cb = writer.getDirectContent(); progressBar.setIndeterminate(true); progressBar.setStringPainted(true); progressBar.setString(i18n.tr("Exporting the document ...")); int geCount = 0; int numberOfGe[] = new int[geManager.getRegisteredGEClasses().size()]; for (int i = 0; i < numberOfGe.length; i++) { numberOfGe[i] = 0; } //Draw each GraphicalElement in the BufferedImage for (GraphicalElement ge : geStack) { if ((ge instanceof org.orbisgis.mapcomposer.model.graphicalelement.element.Document)) continue; double rad = Math.toRadians(ge.getRotation()); double newHeight = Math.abs(sin(rad) * ge.getWidth()) + Math.abs(cos(rad) * ge.getHeight()); double newWidth = Math.abs(sin(rad) * ge.getHeight()) + Math.abs(cos(rad) * ge.getWidth()); int maxWidth = Math.max((int) newWidth, ge.getWidth()); int maxHeight = Math.max((int) newHeight, ge.getHeight()); String layerName = ge.getGEName() + numberOfGe[geManager.getRegisteredGEClasses().indexOf(ge.getClass())]; if (geIsVectorMap.get(ge)) { PdfTemplate pdfTemplate = cb.createTemplate(maxWidth, maxHeight); Graphics2D g2dTemplate = pdfTemplate.createGraphics(maxWidth, maxHeight); PdfLayer layer = new PdfLayer(layerName, writer); cb.beginLayer(layer); ((RendererVector) geManager.getRenderer(ge.getClass())).drawGE(g2dTemplate, ge); cb.addTemplate(pdfTemplate, ge.getX() + (ge.getWidth() - maxWidth) / 2, -ge.getY() + height - ge.getHeight() + (ge.getHeight() - maxHeight) / 2); g2dTemplate.dispose(); cb.endLayer(); } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedImage bi = ((RendererRaster) geManager.getRenderer(ge.getClass())).createGEImage(ge, null); ImageIO.write(bi, "png", baos); Image image = Image.getInstance(baos.toByteArray()); image.setAbsolutePosition(ge.getX() + (ge.getWidth() - maxWidth) / 2, -ge.getY() + height - ge.getHeight() + (ge.getHeight() - maxHeight) / 2); PdfTemplate pdfTemplate = cb.createTemplate(maxWidth, maxHeight); Graphics2D g2dTemplate = pdfTemplate.createGraphics(maxWidth, maxHeight); PdfLayer layer = new PdfLayer(layerName, writer); cb.beginLayer(layer); g2dTemplate.drawImage(bi, 0, 0, null); cb.addTemplate(pdfTemplate, ge.getX() + (ge.getWidth() - maxWidth) / 2, -ge.getY() + height - ge.getHeight() + (ge.getHeight() - maxHeight) / 2); g2dTemplate.dispose(); cb.endLayer(); } numberOfGe[geManager.getRegisteredGEClasses().indexOf(ge.getClass())]++; progressBar.setIndeterminate(false); progressBar.setValue((geCount * 100) / geIsVectorMap.keySet().size()); progressBar.revalidate(); geCount++; } pdfDocument.close(); //Wait a bit before erasing the progress bar progressBar.setValue(progressBar.getMaximum()); progressBar.setString(i18n.tr("Document successfully exported.")); try { Thread.sleep(1500); } catch (InterruptedException e) { LoggerFactory.getLogger(ExportPDFThread.class).error(e.getMessage()); } progressBar.setValue(0); progressBar.setStringPainted(false); } catch (IllegalArgumentException | IOException | DocumentException ex) { LoggerFactory.getLogger(ExportPDFThread.class).error(ex.getMessage()); } }
From source file:org.ujmp.itext.ExportPDF.java
License:Open Source License
public static final void save(File file, Component c, int width, int height) { if (file == null) { logger.log(Level.WARNING, "no file selected"); return;//from w ww. j a va 2s . c om } if (c == null) { logger.log(Level.WARNING, "no component provided"); return; } try { Document document = new Document(new Rectangle(width, height)); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file.getAbsolutePath())); document.addAuthor("UJMP v" + UJMP.UJMPVERSION); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = new PdfGraphics2D(cb, width, height, new DefaultFontMapper()); if (c instanceof CanRenderGraph) { ((CanRenderGraph) c).renderGraph(g2); } else { c.paint(g2); } g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); writer.close(); } catch (Exception e) { logger.log(Level.WARNING, "could not save PDF file", e); } }
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 ww w .j a v a 2 s . co 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. jav a 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 ww. j a v a2 s. co 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 ww. j a v a 2 s . co 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./* w w w . ja v a 2s . 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(); }