List of usage examples for com.itextpdf.text.pdf PdfWriter getDirectContent
public PdfContentByte getDirectContent()
From source file:org.kalypso.ogc.gml.map.handlers.utils.PDFExporter.java
License:Open Source License
public IStatus doExport(final File targetFile, IProgressMonitor monitor) { /* If no monitor is given, take a null progress monitor. */ if (monitor == null) monitor = new NullProgressMonitor(); /* The output streams. */ BufferedOutputStream os = null; try {/*from w w w .j a v a 2 s. c om*/ /* Monitor. */ monitor.beginTask(Messages.getString("PDFExporter_0"), 1000); //$NON-NLS-1$ monitor.subTask(Messages.getString("PDFExporter_1")); //$NON-NLS-1$ /* Create the image. */ final Insets insets = new Insets(10, 10, 10, 10); final BufferedImage image = MapModellHelper.createWellFormedImageFromModel(m_mapPanel, (int) PageSize.A4.getHeight(), (int) PageSize.A4.getWidth(), insets, 1); /* Convert to an itext image. */ final Image img = Image.getInstance(image, null); /* Monitor. */ monitor.worked(500); monitor.subTask(Messages.getString("PDFExporter_2")); //$NON-NLS-1$ /* Create the output stream. */ os = new BufferedOutputStream(new FileOutputStream(targetFile)); /* Create a new document. */ final Document document = new Document( new com.itextpdf.text.Rectangle(PageSize.A4.getHeight(), PageSize.A4.getWidth()), 30, 30, 30, 30); /* Create the pdf writter. */ final PdfWriter writer = PdfWriter.getInstance(document, os); writer.setCompressionLevel(0); /* Open the document. */ document.open(); /* Set the position. */ img.setAbsolutePosition(0, 0); /* Set to the pdf. */ writer.getDirectContent().addImage(img, true); /* Close the document. */ document.close(); /* Monitor. */ monitor.worked(500); return new Status(IStatus.OK, KalypsoGisPlugin.getId(), Messages.getString("PDFExporter_3")); //$NON-NLS-1$ } catch (final Exception ex) { return new Status(IStatus.ERROR, KalypsoGisPlugin.getId(), ex.getLocalizedMessage(), ex); } finally { /* Close the output streams. */ IOUtils.closeQuietly(os); /* Monitor. */ monitor.done(); } }
From source file:org.me.modelos.HeaderFooterPageEvent.java
@Override public void onStartPage(PdfWriter writer, Document document) { Rectangle rect = writer.getBoxSize("art"); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(motelNombre + " " + direccion + " " + telefono, font), rect.getLeft(), rect.getTop(), 0); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(fecha, font), rect.getRight(), rect.getTop(), 0); }
From source file:org.openlmis.web.view.pdf.PdfPageEventHandler.java
License:Open Source License
@Override public void onOpenDocument(PdfWriter writer, Document document) { pageNumberTemplate = writer.getDirectContent().createTemplate(PAGE_TEXT_WIDTH, PAGE_TEXT_HEIGHT); }
From source file:org.openlmis.web.view.pdf.PdfPageEventHandler.java
License:Open Source License
private void addPageFooterInfo(PdfWriter writer, Document document) { PdfContentByte contentByte = writer.getDirectContent(); contentByte.saveState();/*from w w w .jav a 2 s. c o m*/ contentByte.setFontAndSize(baseFont, FOOTER_TEXT_SIZE); contentByte.beginText(); writeCurrentDate(document, contentByte); writePageNumber(writer, document, contentByte); contentByte.endText(); contentByte.restoreState(); }
From source file:org.openscience.cdk.applications.taverna.basicutilities.ChartTool.java
License:Open Source License
/** * Writes given charts into target PDF file. * //from www . ja v a2 s. c o m * @param file * @param charts * @param annotations * @throws IOException */ public synchronized void writeChartAsPDF(File file, List<Object> chartObjects) throws IOException { Rectangle pagesize = new Rectangle(this.width, this.height); Document document = new Document(pagesize, 50, 50, 50, 50); try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); document.addAuthor("CDK-Taverna 2.0"); document.open(); PdfContentByte cb = writer.getDirectContent(); for (int i = 0; i < chartObjects.size(); i++) { Object obj = chartObjects.get(i); if (obj instanceof JFreeChart) { JFreeChart chart = (JFreeChart) obj; this.addChartPageToPDF(chart, cb); } else if (obj instanceof String) { String annotation = (String) obj; this.addAnnotationToPDF(annotation, document); } document.newPage(); } } catch (DocumentException e) { ErrorLogger.getInstance().writeError(CDKTavernaException.CANT_CREATE_PDF_FILE + file.getPath(), this.getClass().getSimpleName(), e); } document.close(); }
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 av a 2 s.co m 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
/** * Create the PDF document and a the geospatial tags * * @param out/* w w w .j a va 2s .c o m*/ * @param mt * @param pm * @throws IOException */ public void createPDF(OutputStream out, MapTransform mt, ProgressMonitor pm) throws IOException { Document document = new Document(new Rectangle(width, height)); try { PdfWriter writer = PdfWriter.getInstance(document, out); writer.setTagged(); writer.setUserProperties(true); document.open(); PdfContentByte cb = writer.getDirectContent(); int numLayers = rootLayer.getLayerCount(); for (int i = numLayers - 1; i >= 0; i--) { ILayer layer = rootLayer.getLayer(i); processSubLayer(layer, mt, writer, cb, pm, null); } georefPdf(writer, mt); } catch (DocumentException ex) { throw new IOException("Cannot create the pdf", ex); } document.close(); }
From source file:org.orbisgis.mapcomposer.controller.utils.exportThreads.ExportPDFThread.java
License:Open Source License
@Override public void run() { try {/* ww w .j a v a 2 s . 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.primaresearch.pdf.PageToPdfConverter.java
License:Apache License
/** * Adds the specified outlines of the given page to the current PDF page. * @param writer/*from w w w .ja v a 2s .c o m*/ * @param page * @param type */ private void addOutlines(PdfWriter writer, Page page, ContentType type) { int pageHeight = page.getLayout().getHeight(); try { PdfContentByte cb = writer.getDirectContent(); cb.saveState(); for (ContentIterator it = page.getLayout().iterator(type); it.hasNext();) { ContentObject contentObj = it.next(); drawLayoutObject(contentObj, cb, pageHeight); } cb.restoreState(); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.saiku.web.export.PdfReport.java
License:Apache License
public byte[] pdf(QueryResult qr, String svg) throws Exception { int resultWidth = qr != null && qr.getCellset() != null && qr.getCellset().size() > 0 ? qr.getCellset().get(0).length : 0;// w w w . j av a 2s .c om if (resultWidth == 0) { throw new SaikuServiceException("Cannot convert empty result to PDF"); } Rectangle size = PageSize.A4.rotate(); if (resultWidth > 8) { size = PageSize.A3.rotate(); } if (resultWidth > 16) { size = PageSize.A2.rotate(); } if (resultWidth > 32) { size = PageSize.A1.rotate(); } if (resultWidth > 64) { size = PageSize.A0.rotate(); } Document document = new Document(size, 15, 15, 10, 10); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); populatePdf(document, writer, qr); // do we want to add a svg image? if (StringUtils.isNotBlank(svg)) { document.newPage(); StringBuffer s1 = new StringBuffer(svg); if (!svg.startsWith("<svg xmlns=\"http://www.w3.org/2000/svg\" ")) { s1.insert(s1.indexOf("<svg") + 4, " xmlns='http://www.w3.org/2000/svg'"); } String t = "<?xml version='1.0' encoding='ISO-8859-1'" + " standalone='no'?>" + s1.toString(); PdfContentByte cb = writer.getDirectContent(); cb.saveState(); cb.concatCTM(1.0f, 0, 0, 1.0f, 36, 0); float width = document.getPageSize().getWidth() - 20; float height = document.getPageSize().getHeight() - 20; Graphics2D g2 = cb.createGraphics(width, height); //g2.rotate(Math.toRadians(-90), 100, 100); PrintTranscoder prm = new PrintTranscoder(); TranscoderInput ti = new TranscoderInput(new StringReader(t)); prm.transcode(ti, null); PageFormat pg = new PageFormat(); Paper pp = new Paper(); pp.setSize(width, height); pp.setImageableArea(5, 5, width, height); pg.setPaper(pp); prm.print(g2, pg, 0); g2.dispose(); cb.restoreState(); } document.close(); return baos.toByteArray(); }