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:org.imos.abos.plot.JfreeChartDemo.java
License:Open Source License
protected void createPDF(String filename) { try {// w ww .j av a 2 s. c o m Rectangle page = PageSize.A4.rotate(); // step 1 Document document = new Document(page); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3 document.open(); // step 4 PdfContentByte cb = writer.getDirectContent(); float width = page.getWidth(); float height = page.getHeight(); // add chart PdfTemplate pie = cb.createTemplate(width, height); Graphics2D g2d1 = new PdfGraphics2D(pie, width, height); Rectangle2D r2d1 = new Rectangle2D.Double(0, 0, width, height); chart.draw(g2d1, r2d1); g2d1.dispose(); cb.addTemplate(pie, 0, 0); // step 5 document.close(); } catch (DocumentException ex) { Logger.getLogger(JfreeChartDemo.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(JfreeChartDemo.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("PDF finsihed"); }
From source file:org.jfree.chart.swt.ChartPdf.java
License:Open Source License
protected static void writeChart(JFreeChart chart, int width, int height, PdfContentByte cb) { PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = new PdfGraphics2D(cb, width, height); Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height); chart.draw(g2, r2D, null);//from w w w . j a v a 2 s . c om g2.dispose(); cb.addTemplate(tp, 0, 0); }
From source file:org.niord.core.fm.pdf.SVGReplacedElement.java
License:Apache License
/** {@inheritDoc} **/ @Override// w w w .j a va2 s . c om public void paint(RenderingContext renderingContext, ITextOutputDevice outputDevice, BlockBox blockBox) { PdfContentByte cb = outputDevice.getWriter().getDirectContent(); float width = cssWidth / outputDevice.getDotsPerPoint(); float height = cssHeight / outputDevice.getDotsPerPoint(); PdfTemplate template = cb.createTemplate(width, height); Graphics2D g2d = new PdfGraphics2D(template, width, height); PrintTranscoder prm = new PrintTranscoder(); TranscoderInput ti = new TranscoderInput(svg); prm.transcode(ti, null); PageFormat pg = new PageFormat(); Paper pp = new Paper(); pp.setSize(width, height); pp.setImageableArea(0, 0, width, height); pg.setPaper(pp); prm.print(g2d, pg, 0); g2d.dispose(); PageBox page = renderingContext.getPage(); float x = blockBox.getAbsX() + page.getMarginBorderPadding(renderingContext, CalculatedStyle.LEFT); float y = (page.getBottom() - (blockBox.getAbsY() + cssHeight)) + page.getMarginBorderPadding(renderingContext, CalculatedStyle.BOTTOM); x /= outputDevice.getDotsPerPoint(); y /= outputDevice.getDotsPerPoint(); cb.addTemplate(template, x, y); }
From source file:org.openlmis.web.view.pdf.PdfPageEventHandler.java
License:Open Source License
private void writePageNumber(PdfWriter writer, Document document, PdfContentByte contentByte) { String pageNumberText = messageService.message("label.page.of", writer.getPageNumber()) + " "; float pageNumberTextSize = baseFont.getWidthPoint(pageNumberText, FOOTER_TEXT_SIZE); contentByte.setTextMatrix(document.right() - pageNumberTextSize - textAdjustment, document.bottom()); contentByte.showText(pageNumberText); contentByte.addTemplate(pageNumberTemplate, document.right() - textAdjustment, document.bottom()); }
From source file:org.openscience.cdk.applications.taverna.basicutilities.ChartTool.java
License:Open Source License
/** * Adds a chart to the pdf file.//from w w w . j a v a2s . c o m * * @param chart * @param cb */ private void addChartPageToPDF(JFreeChart chart, PdfContentByte cb) { PdfTemplate tp = cb.createTemplate(this.width, this.height); Graphics2D g2 = tp.createGraphics(this.width, this.height, new DefaultFontMapper()); Rectangle2D r2D = new Rectangle2D.Double(0, 0, this.width, this.height); chart.draw(g2, r2D); g2.dispose(); cb.addTemplate(tp, 0, 0); }
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 {/*w ww .j a v a2 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// ww w .ja v a 2 s .co 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 w w w. j a va 2 s . c o 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.smap.sdal.managers.MiscPDFManager.java
License:Open Source License
public void createUsagePdf(Connection sd, OutputStream outputStream, String basePath, HttpServletResponse response, int o_id, int month, int year, String period, String org_name) { PreparedStatement pstmt = null; if (org_name == null) { org_name = "None"; }/* w w w . j a v a2 s.co m*/ try { String filename; // Get fonts and embed them String os = System.getProperty("os.name"); log.info("Operating System:" + os); if (os.startsWith("Mac")) { FontFactory.register("/Library/Fonts/fontawesome-webfont.ttf", "Symbols"); FontFactory.register("/Library/Fonts/Arial Unicode.ttf", "default"); FontFactory.register("/Library/Fonts/NotoNaskhArabic-Regular.ttf", "arabic"); FontFactory.register("/Library/Fonts/NotoSans-Regular.ttf", "notosans"); } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0) { // Linux / Unix FontFactory.register("/usr/share/fonts/truetype/fontawesome-webfont.ttf", "Symbols"); FontFactory.register("/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf", "default"); FontFactory.register("/usr/share/fonts/truetype/NotoNaskhArabic-Regular.ttf", "arabic"); FontFactory.register("/usr/share/fonts/truetype/NotoSans-Regular.ttf", "notosans"); } Symbols = FontFactory.getFont("Symbols", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12); defaultFont = FontFactory.getFont("default", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10); filename = org_name + "_" + year + "_" + month + ".pdf"; /* * Get the usage results */ String sql = "SELECT users.id as id," + "users.ident as ident, " + "users.name as name, " + "(select count (*) from upload_event ue, subscriber_event se " + "where ue.ue_id = se.ue_id " + "and se.status = 'success' " + "and se.subscriber = 'results_db' " + "and extract(month from upload_time) = ? " // current month + "and extract(year from upload_time) = ? " // current year + "and ue.user_name = users.ident) as month, " + "(select count (*) from upload_event ue, subscriber_event se " + "where ue.ue_id = se.ue_id " + "and se.status = 'success' " + "and se.subscriber = 'results_db' " + "and ue.user_name = users.ident) as all_time " + "from users " + "where users.o_id = ? " + "and not users.temporary " + "order by users.ident;"; pstmt = sd.prepareStatement(sql); pstmt.setInt(1, month); pstmt.setInt(2, year); pstmt.setInt(3, o_id); log.info("Get Usage Data: " + pstmt.toString()); // If the PDF is to be returned in an http response then set the file name now if (response != null) { log.info("Setting filename to: " + filename); setFilenameInResponse(filename, response); } /* * Get a template for the PDF report if it exists * The template name will be the same as the XLS form name but with an extension of pdf */ String stationaryName = basePath + File.separator + "misc" + File.separator + "UsageReportTemplate.pdf"; File stationaryFile = new File(stationaryName); ByteArrayOutputStream baos = null; ByteArrayOutputStream baos_s = null; PdfWriter writer = null; /* * Create document in two passes, the second pass adds the letter head */ // Create the underlying document as a byte array Document document = new Document(PageSize.A4); document.setMargins(marginLeft, marginRight, marginTop_1, marginBottom_1); if (stationaryFile.exists()) { baos = new ByteArrayOutputStream(); baos_s = new ByteArrayOutputStream(); writer = PdfWriter.getInstance(document, baos); } else { writer = PdfWriter.getInstance(document, outputStream); } writer.setInitialLeading(12); writer.setPageEvent(new PageSizer()); document.open(); // Write the usage data ResultSet resultSet = pstmt.executeQuery(); PdfPTable table = new PdfPTable(4); // Add the header row table.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY); table.getDefaultCell().setBackgroundColor(VLG); table.addCell("User Id"); table.addCell("User Name"); table.addCell("Usage in Period"); table.addCell("All Time Usage"); table.setHeaderRows(1); // Add the user data int total = 0; int totalAllTime = 0; table.getDefaultCell().setBackgroundColor(null); while (resultSet.next()) { String ident = resultSet.getString("ident"); String name = resultSet.getString("name"); String monthUsage = resultSet.getString("month"); int monthUsageInt = resultSet.getInt("month"); String allTime = resultSet.getString("all_time"); int allTimeInt = resultSet.getInt("all_time"); table.addCell(ident); table.addCell(name); table.addCell(monthUsage); table.addCell(allTime); total += monthUsageInt; totalAllTime += allTimeInt; } // Add the totals table.getDefaultCell().setBackgroundColor(VLG); table.addCell("Totals: "); table.addCell(" "); table.addCell(String.valueOf(total)); table.addCell(String.valueOf(totalAllTime)); document.add(table); document.close(); if (stationaryFile.exists()) { // Step 2 - Populate the fields in the stationary PdfReader s_reader = new PdfReader(stationaryName); PdfStamper s_stamper = new PdfStamper(s_reader, baos_s); AcroFields pdfForm = s_stamper.getAcroFields(); Set<String> fields = pdfForm.getFields().keySet(); for (String key : fields) { log.info("Field: " + key); } pdfForm.setField("billing_period", period); pdfForm.setField("organisation", org_name); s_stamper.setFormFlattening(true); s_stamper.close(); // Step 3 - Apply the stationary to the underlying document PdfReader reader = new PdfReader(baos.toByteArray()); // Underlying document PdfReader f_reader = new PdfReader(baos_s.toByteArray()); // Filled in stationary PdfStamper stamper = new PdfStamper(reader, outputStream); PdfImportedPage letter1 = stamper.getImportedPage(f_reader, 1); int n = reader.getNumberOfPages(); PdfContentByte background; for (int i = 0; i < n; i++) { background = stamper.getUnderContent(i + 1); if (i == 0) { background.addTemplate(letter1, 0, 0); } } stamper.close(); reader.close(); } } catch (SQLException e) { log.log(Level.SEVERE, "SQL Error", e); } catch (Exception e) { log.log(Level.SEVERE, "Exception", e); } finally { try { if (pstmt != null) { pstmt.close(); } } catch (SQLException e) { } } }
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 www. jav a 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); } }