Java Code Examples for com.lowagie.text.pdf.PdfContentByte#createTemplate()
The following examples show how to use
com.lowagie.text.pdf.PdfContentByte#createTemplate() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OptionalContentTest.java From itext2 with GNU Lesser General Public License v3.0 | 7 votes |
/** * Demonstrates the use of layers. * * @param args * no arguments needed */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(PageSize.A4, 50, 50, 50, 50); // step 2: creation of the writer PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("optionalcontent.pdf")); writer.setPdfVersion(PdfWriter.VERSION_1_5); writer.setViewerPreferences(PdfWriter.PageModeUseOC); // step 3: opening the document document.open(); // step 4: content PdfContentByte cb = writer.getDirectContent(); Phrase explanation = new Phrase( "Automatic layers, form fields, images, templates and actions", new Font(Font.HELVETICA, 18, Font.BOLD, Color.red)); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, explanation, 50, 650, 0); PdfLayer l1 = new PdfLayer("Layer 1", writer); PdfLayer l2 = new PdfLayer("Layer 2", writer); PdfLayer l3 = new PdfLayer("Layer 3", writer); PdfLayer l4 = new PdfLayer("Form and XObject Layer", writer); PdfLayerMembership m1 = new PdfLayerMembership(writer); m1.addMember(l2); m1.addMember(l3); Phrase p1 = new Phrase("Text in layer 1"); Phrase p2 = new Phrase("Text in layer 2 or layer 3"); Phrase p3 = new Phrase("Text in layer 3"); cb.beginLayer(l1); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p1, 50, 600, 0f); cb.endLayer(); cb.beginLayer(m1); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p2, 50, 550, 0); cb.endLayer(); cb.beginLayer(l3); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, p3, 50, 500, 0); cb.endLayer(); TextField ff = new TextField(writer, new Rectangle(200, 600, 300, 620), "field1"); ff.setBorderColor(Color.blue); ff.setBorderStyle(PdfBorderDictionary.STYLE_SOLID); ff.setBorderWidth(TextField.BORDER_WIDTH_THIN); ff.setText("I'm a form field"); PdfFormField form = ff.getTextField(); form.setLayer(l4); writer.addAnnotation(form); Image img = Image.getInstance(PdfTestBase.RESOURCES_DIR + "pngnow.png"); img.setLayer(l4); img.setAbsolutePosition(200, 550); cb.addImage(img); PdfTemplate tp = cb.createTemplate(100, 20); Phrase pt = new Phrase("I'm a template", new Font(Font.HELVETICA, 12, Font.NORMAL, Color.magenta)); ColumnText.showTextAligned(tp, Element.ALIGN_LEFT, pt, 0, 0, 0); tp.setLayer(l4); tp.setBoundingBox(new Rectangle(0, -10, 100, 20)); cb.addTemplate(tp, 200, 500); ArrayList<Object> state = new ArrayList<Object>(); state.add("toggle"); state.add(l1); state.add(l2); state.add(l3); state.add(l4); PdfAction action = PdfAction.setOCGstate(state, true); Chunk ck = new Chunk("Click here to toggle the layers", new Font( Font.HELVETICA, 18, Font.NORMAL, Color.yellow)).setBackground( Color.blue).setAction(action); ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, new Phrase(ck), 250, 400, 0); cb.sanityCheck(); // step 5: closing the document document.close(); }
Example 2
Source File: Image.java From gcs with Mozilla Public License 2.0 | 6 votes |
/** * Gets an instance of a Image from a java.awt.Image. The image is added as a JPEG with a user * defined quality. * * @param cb the <CODE>PdfContentByte</CODE> object to which the image will be added * @param awtImage the <CODE>java.awt.Image</CODE> to convert * @param quality a float value between 0 and 1 * @return an object of type <CODE>PdfTemplate</CODE> * @throws BadElementException on error * @throws IOException */ public static Image getInstance(PdfContentByte cb, java.awt.Image awtImage, float quality) throws BadElementException, IOException { java.awt.image.PixelGrabber pg = new java.awt.image.PixelGrabber(awtImage, 0, 0, -1, -1, true); try { pg.grabPixels(); } catch (InterruptedException e) { throw new IOException("java.awt.Image Interrupted waiting for pixels!"); } if ((pg.getStatus() & java.awt.image.ImageObserver.ABORT) != 0) { throw new IOException("java.awt.Image fetch aborted or errored"); } int w = pg.getWidth(); int h = pg.getHeight(); PdfTemplate tp = cb.createTemplate(w, h); Graphics2D g2d = tp.createGraphics(w, h, true, quality); g2d.drawImage(awtImage, 0, 0, null); g2d.dispose(); return getInstance(tp); }
Example 3
Source File: Image.java From itext2 with GNU Lesser General Public License v3.0 | 6 votes |
/** * Gets an instance of a Image from a java.awt.Image. * The image is added as a JPEG with a user defined quality. * * @param cb * the <CODE>PdfContentByte</CODE> object to which the image will be added * @param awtImage * the <CODE>java.awt.Image</CODE> to convert * @param quality * a float value between 0 and 1 * @return an object of type <CODE>PdfTemplate</CODE> * @throws BadElementException * on error * @throws IOException */ public static Image getInstance(PdfContentByte cb, java.awt.Image awtImage, float quality) throws BadElementException, IOException { java.awt.image.PixelGrabber pg = new java.awt.image.PixelGrabber(awtImage, 0, 0, -1, -1, true); try { pg.grabPixels(); } catch (InterruptedException e) { throw new IOException( "java.awt.Image Interrupted waiting for pixels!"); } if ((pg.getStatus() & java.awt.image.ImageObserver.ABORT) != 0) { throw new IOException("java.awt.Image fetch aborted or errored"); } int w = pg.getWidth(); int h = pg.getHeight(); PdfTemplate tp = cb.createTemplate(w, h); Graphics2D g2d = tp.createGraphics(w, h, true, quality); g2d.drawImage(awtImage, 0, 0, null); g2d.dispose(); return getInstance(tp); }
Example 4
Source File: JFreeChartTest.java From itext2 with GNU Lesser General Public License v3.0 | 5 votes |
/** * Converts a JFreeChart to PDF syntax. * @param filename the name of the PDF file * @param chart the JFreeChart * @param width the width of the resulting PDF * @param height the height of the resulting PDF */ public static void convertToPdf(JFreeChart chart, int width, int height, String filename) { // step 1 Document document = new Document(new Rectangle(width, height)); try { // step 2 PdfWriter writer; writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream(filename)); // step 3 document.open(); // step 4 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(); tp.sanityCheck(); cb.addTemplate(tp, 0, 0); cb.sanityCheck(); } catch(DocumentException de) { de.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } // step 5 document.close(); }
Example 5
Source File: MapperFrameOld.java From beast-mcmc with GNU Lesser General Public License v2.1 | 5 votes |
public final void doExportPDF() { FileDialog dialog = new FileDialog(this, "Export PDF Image...", FileDialog.SAVE); dialog.setVisible(true); if (dialog.getFile() != null) { File file = new File(dialog.getDirectory(), dialog.getFile()); Rectangle2D bounds = mapperPanel.getExportableComponent().getBounds(); Document document = new Document(new com.lowagie.text.Rectangle((float) bounds.getWidth(), (float) bounds.getHeight())); try { // step 2 PdfWriter writer; writer = PdfWriter.getInstance(document, new FileOutputStream(file)); // step 3 document.open(); // step 4 PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate((float) bounds.getWidth(), (float) bounds.getHeight()); Graphics2D g2d = tp.createGraphics((float) bounds.getWidth(), (float) bounds.getHeight(), new DefaultFontMapper()); mapperPanel.getExportableComponent().print(g2d); g2d.dispose(); cb.addTemplate(tp, 0, 0); } catch (DocumentException de) { JOptionPane.showMessageDialog(this, "Error writing PDF file: " + de, "Export PDF Error", JOptionPane.ERROR_MESSAGE); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(this, "Error writing PDF file: " + e, "Export PDF Error", JOptionPane.ERROR_MESSAGE); } document.close(); } }
Example 6
Source File: ImageExporter.java From rapidminer-studio with GNU Affero General Public License v3.0 | 5 votes |
private void exportVectorGraphics(String formatName, File outputFile) throws ImageExportException { Component component = printableComponent.getExportComponent(); int width = component.getWidth(); int height = component.getHeight(); try (FileOutputStream fs = new FileOutputStream(outputFile)) { switch (formatName) { case PDF: // create pdf document with slightly increased width and height // (otherwise the image gets cut off) Document document = new Document(new Rectangle(width + 5, height + 5)); PdfWriter writer = PdfWriter.getInstance(document, fs); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper()); component.print(g2); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); break; case SVG: exportFreeHep(component, fs, new SVGGraphics2D(fs, new Dimension(width, height))); break; case EPS: exportFreeHep(component, fs, new PSGraphics2D(fs, new Dimension(width, height))); break; default: // cannot happen break; } } catch (Exception e) { throw new ImageExportException(I18N.getMessage(I18N.getUserErrorMessagesBundle(), "error.image_export.export_failed"), e); } }
Example 7
Source File: PdfExportHelper.java From mdw with Apache License 2.0 | 5 votes |
private void printDiagram(DocWriter writer, Chapter chapter, Process process, Rectangle pageSize) throws Exception { ProcessCanvas canvas = new ProcessCanvas(project, process); canvas.prepare(); Dimension size = new PngProcessExporter(project).getDiagramSize(process); // create a template and a Graphics2D object that corresponds with it int w; int h; float scale; if ((float) size.width < pageSize.getWidth() * 0.8 && (float) size.height < pageSize.getHeight() * 0.8) { w = size.width + 36; h = size.height + 36; scale = -1f; } else { scale = pageSize.getWidth() * 0.8f / (float) size.width; if (scale > pageSize.getHeight() * 0.8f / (float) size.height) scale = pageSize.getHeight() * 0.8f / (float) size.height; w = (int) (size.width * scale) + 36; h = (int) (size.height * scale) + 36; } PdfContentByte cb = ((PdfWriter) writer).getDirectContent(); PdfTemplate tp = cb.createTemplate(w, h); Graphics2D g2 = tp.createGraphics(w, h); if (scale > 0) g2.scale(scale, scale); tp.setWidth(w); tp.setHeight(h); canvas.paintComponent(g2); g2.dispose(); Image img = new ImgTemplate(tp); chapter.add(img); canvas.dispose(); }
Example 8
Source File: LogoTest.java From itext2 with GNU Lesser General Public License v3.0 | 4 votes |
/** * Draws the iText logo. */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(); // step 2: creation of the writer PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("logo.pdf")); // step 3: we open the document document.open(); // step 4: BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); PdfContentByte cb = writer.getDirectContent(); PdfTemplate template = cb.createTemplate(500, 200); template.setLineWidth(2f); template.rectangle(2.5f, 2.5f, 495f, 195f); template.stroke(); template.setLineWidth(12f); template.arc(40f - (float) Math.sqrt(12800), 120f + (float) Math.sqrt(12800), 200f - (float) Math.sqrt(12800), -40f + (float) Math.sqrt(12800), 281.25f, 33.75f); template.arc(40f, 120f, 200f, -40f, 90f, 45f); template.stroke(); template.setLineCap(1); template.setLineWidth(12f); template.arc(80f, 40f, 160f, 120f, 90f, 180f); template.arc(115f, 75f, 125f, 85f, 0f, 360f); template.stroke(); template.beginText(); template.setFontAndSize(bf, 180); template.setRGBColorFill(0xFF, 0x00, 0x00); template.showTextAligned(PdfContentByte.ALIGN_LEFT, "T", 125f, 35f, 0f); template.resetRGBColorFill(); template.showTextAligned(PdfContentByte.ALIGN_LEFT, "ext", 220f, 35f, 0f); template.endText(); template.sanityCheck(); cb.addTemplate(template, 0, 1, -1, 0, 500, 200); cb.addTemplate(template, .5f, 0, 0, .5f, 100, 400); cb.addTemplate(template, 0.25f, 0, 0, 0.25f, 100, 100); cb.sanityCheck(); // step 5: we close the document document.close(); }
Example 9
Source File: VisualizePanelCharts2D.java From KEEL with GNU General Public License v3.0 | 4 votes |
private void topdfjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_topdfjButtonActionPerformed // Save chart as a PDF file JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle("Save chart"); KeelFileFilter fileFilter = new KeelFileFilter(); fileFilter.addExtension("pdf"); fileFilter.setFilterName("PDF images (.pdf)"); chooser.setFileFilter(fileFilter); chooser.setCurrentDirectory(Path.getFilePath()); int opcion = chooser.showSaveDialog(this); Path.setFilePath(chooser.getCurrentDirectory()); if (opcion == JFileChooser.APPROVE_OPTION) { String nombre = chooser.getSelectedFile().getAbsolutePath(); if (!nombre.toLowerCase().endsWith(".pdf")) { // Add correct extension nombre += ".pdf"; } File tmp = new File(nombre); if (!tmp.exists() || JOptionPane.showConfirmDialog(this, "File " + nombre + " already exists. Do you want to replace it?", "Confirm", JOptionPane.YES_NO_OPTION, 3) == JOptionPane.YES_OPTION) { try { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(nombre)); document.addAuthor("KEEL"); document.addSubject("Attribute comparison"); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(550, 412); Graphics2D g2 = tp.createGraphics(550, 412, new DefaultFontMapper()); Rectangle2D r2D = new Rectangle2D.Double(0, 0, 550, 412); chart2.setBackgroundPaint(Color.white); chart2.draw(g2, r2D); g2.dispose(); cb.addTemplate(tp, 20, 350); document.close(); } catch (Exception exc) { } } } }
Example 10
Source File: ColumnIrregularTest.java From itext2 with GNU Lesser General Public License v3.0 | 4 votes |
/** * Demonstrates the use of ColumnText. */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(); // step 2: creation of the writer PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("columnirregular.pdf")); // step 3: we open the document document.open(); // step 4: // we grab the contentbyte and do some stuff with it PdfContentByte cb = writer.getDirectContent(); PdfTemplate t = cb.createTemplate(600, 800); Image caesar = Image.getInstance(PdfTestBase.RESOURCES_DIR + "caesar_coin.jpg"); cb.addImage(caesar, 100, 0, 0, 100, 260, 595); t.setGrayFill(0.75f); t.moveTo(310, 112); t.lineTo(280, 60); t.lineTo(340, 60); t.closePath(); t.moveTo(310, 790); t.lineTo(310, 710); t.moveTo(310, 580); t.lineTo(310, 122); t.stroke(); cb.addTemplate(t, 0, 0); ColumnText ct = new ColumnText(cb); ct.addText(new Phrase( "GALLIA est omnis divisa in partes tres, quarum unam incolunt Belgae, aliam Aquitani, tertiam qui ipsorum lingua Celtae, nostra Galli appellantur. Hi omnes lingua, institutis, legibus inter se differunt. Gallos ab Aquitanis Garumna flumen, a Belgis Matrona et Sequana dividit. Horum omnium fortissimi sunt Belgae, propterea quod a cultu atque humanitate provinciae longissime absunt, minimeque ad eos mercatores saepe commeant atque ea quae ad effeminandos animos pertinent important, proximique sunt Germanis, qui trans Rhenum incolunt, quibuscum continenter bellum gerunt. Qua de causa Helvetii quoque reliquos Gallos virtute praecedunt, quod fere cotidianis proeliis cum Germanis contendunt, cum aut suis finibus eos prohibent aut ipsi in eorum finibus bellum gerunt.\n", FontFactory.getFont(FontFactory.HELVETICA, 12))); ct.addText(new Phrase( "[Eorum una, pars, quam Gallos obtinere dictum est, initium capit a flumine Rhodano, continetur Garumna flumine, Oceano, finibus Belgarum, attingit etiam ab Sequanis et Helvetiis flumen Rhenum, vergit ad septentriones. Belgae ab extremis Galliae finibus oriuntur, pertinent ad inferiorem partem fluminis Rheni, spectant in septentrionem et orientem solem. Aquitania a Garumna flumine ad Pyrenaeos montes et eam partem Oceani quae est ad Hispaniam pertinet; spectat inter occasum solis et septentriones.]\n", FontFactory.getFont(FontFactory.HELVETICA, 12))); ct.addText(new Phrase( "Apud Helvetios longe nobilissimus fuit et ditissimus Orgetorix. Is M. Messala, [et P.] M. Pisone consulibus regni cupiditate inductus coniurationem nobilitatis fecit et civitati persuasit ut de finibus suis cum omnibus copiis exirent: perfacile esse, cum virtute omnibus praestarent, totius Galliae imperio potiri. Id hoc facilius iis persuasit, quod undique loci natura Helvetii continentur: una ex parte flumine Rheno latissimo atque altissimo, qui agrum Helvetium a Germanis dividit; altera ex parte monte Iura altissimo, qui est inter Sequanos et Helvetios; tertia lacu Lemanno et flumine Rhodano, qui provinciam nostram ab Helvetiis dividit. His rebus fiebat ut et minus late vagarentur et minus facile finitimis bellum inferre possent; qua ex parte homines bellandi cupidi magno dolore adficiebantur. Pro multitudine autem hominum et pro gloria belli atque fortitudinis angustos se fines habere arbitrabantur, qui in longitudinem milia passuum CCXL, in latitudinem CLXXX patebant.\n", FontFactory.getFont(FontFactory.HELVETICA, 12))); ct.addText(new Phrase( "His rebus adducti et auctoritate Orgetorigis permoti constituerunt ea quae ad proficiscendum pertinerent comparare, iumentorum et carrorum quam maximum numerum coemere, sementes quam maximas facere, ut in itinere copia frumenti suppeteret, cum proximis civitatibus pacem et amicitiam confirmare. Ad eas res conficiendas biennium sibi satis esse duxerunt; in tertium annum profectionem lege confirmant. Ad eas res conficiendas Orgetorix deligitur. Is sibi legationem ad civitates suscipit. In eo itinere persuadet Castico, Catamantaloedis filio, Sequano, cuius pater regnum in Sequanis multos annos obtinuerat et a senatu populi Romani amicus appellatus erat, ut regnum in civitate sua occuparet, quod pater ante habuerit; itemque Dumnorigi Haeduo, fratri Diviciaci, qui eo tempore principatum in civitate obtinebat ac maxime plebi acceptus erat, ut idem conaretur persuadet eique filiam suam in matrimonium dat. Perfacile factu esse illis probat conata perficere, propterea quod ipse suae civitatis imperium obtenturus esset: non esse dubium quin totius Galliae plurimum Helvetii possent; se suis copiis suoque exercitu illis regna conciliaturum confirmat. Hac oratione adducti inter se fidem et ius iurandum dant et regno occupato per tres potentissimos ac firmissimos populos totius Galliae sese potiri posse sperant.\n", FontFactory.getFont(FontFactory.HELVETICA, 12))); ct.addText(new Phrase( "Ea res est Helvetiis per indicium enuntiata. Moribus suis Orgetoricem ex vinculis causam dicere coegerunt; damnatum poenam sequi oportebat, ut igni cremaretur. Die constituta causae dictionis Orgetorix ad iudicium omnem suam familiam, ad hominum milia decem, undique coegit, et omnes clientes obaeratosque suos, quorum magnum numerum habebat, eodem conduxit; per eos ne causam diceret se eripuit. Cum civitas ob eam rem incitata armis ius suum exequi conaretur multitudinemque hominum ex agris magistratus cogerent, Orgetorix mortuus est; neque abest suspicio, ut Helvetii arbitrantur, quin ipse sibi mortem consciverit.", FontFactory.getFont(FontFactory.HELVETICA, 12))); float[] left1 = { 70, 790, 70, 60 }; float[] right1 = { 300, 790, 300, 700, 240, 700, 240, 590, 300, 590, 300, 106, 270, 60 }; float[] left2 = { 320, 790, 320, 700, 380, 700, 380, 590, 320, 590, 320, 106, 350, 60 }; float[] right2 = { 550, 790, 550, 60 }; int status = 0; int column = 0; while ((status & ColumnText.NO_MORE_TEXT) == 0) { if (column == 0) { ct.setColumns(left1, right1); column = 1; } else { ct.setColumns(left2, right2); column = 0; } status = ct.go(); ct.setYLine(790); ct.setAlignment(Element.ALIGN_JUSTIFIED); status = ct.go(); if ((column == 0) && ((status & ColumnText.NO_MORE_COLUMN) != 0)) { document.newPage(); cb.addTemplate(t, 0, 0); cb.addImage(caesar, 100, 0, 0, 100, 260, 595); } } // step 5: we close the document document.close(); }
Example 11
Source File: DestinationsTest.java From itext2 with GNU Lesser General Public License v3.0 | 4 votes |
/** * Creates a document with some goto actions. * */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(); // step 2: PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("Destinations.pdf")); // step 3: writer.setViewerPreferences(PdfWriter.PageModeUseOutlines); document.open(); // step 4: we grab the ContentByte and do some stuff with it PdfContentByte cb = writer.getDirectContent(); // we create a PdfTemplate PdfTemplate template = cb.createTemplate(25, 25); // we add some crosses to visualize the destinations template.moveTo(13, 0); template.lineTo(13, 25); template.moveTo(0, 13); template.lineTo(50, 13); template.stroke(); // we add the template on different positions cb.addTemplate(template, 287, 787); cb.addTemplate(template, 187, 487); cb.addTemplate(template, 487, 287); cb.addTemplate(template, 87, 87); // we define the destinations PdfDestination d1 = new PdfDestination(PdfDestination.XYZ, 300, 800, 0); PdfDestination d2 = new PdfDestination(PdfDestination.FITH, 500); PdfDestination d3 = new PdfDestination(PdfDestination.FITR, 200, 300, 400, 500); PdfDestination d4 = new PdfDestination(PdfDestination.FITBV, 100); PdfDestination d5 = new PdfDestination(PdfDestination.FIT); // we define the outlines PdfOutline out1 = new PdfOutline(cb.getRootOutline(), d1, "root"); PdfOutline out2 = new PdfOutline(out1, d2, "sub 1"); new PdfOutline(out1, d3, "sub 2"); new PdfOutline(out2, d4, "sub 2.1"); new PdfOutline(out2, d5, "sub 2.2"); // step 5: we close the document document.close(); }
Example 12
Source File: SpotColorsTest.java From itext2 with GNU Lesser General Public License v3.0 | 4 votes |
/** * Demonstrates the use of spotcolors. */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(); // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("spotcolor.pdf")); BaseFont bf = BaseFont.createFont("Helvetica", "winansi", BaseFont.NOT_EMBEDDED); // step 3: we open the document document.open(); // step 4: we grab the ContentByte and do some stuff with it PdfContentByte cb = writer.getDirectContent(); // step 5: we instantiate PdfSpotColor // Note: I made up these names unless someone give me a PANTONE swatch as gift ([email protected]) PdfSpotColor spc_cmyk = new PdfSpotColor("PANTONE 280 CV", new CMYKColor(0.9f, .2f, .3f, .1f)); PdfSpotColor spc_rgb = new PdfSpotColor("PANTONE 147", new Color(114, 94, 38)); PdfSpotColor spc_g = new PdfSpotColor("PANTONE 100 CV", new GrayColor(0.9f)); // Stroke a rectangle with CMYK alternate cb.setColorStroke(spc_cmyk, .5f); cb.setLineWidth(10f); // draw a rectangle cb.rectangle(100, 700, 100, 100); // add the diagonal cb.moveTo(100, 700); cb.lineTo(200, 800); // stroke the lines cb.stroke(); // Fill a rectangle with CMYK alternate cb.setColorFill(spc_cmyk, 0.25f); cb.rectangle(250, 700, 100, 100); cb.fill(); // Stroke a circle with RGB alternate cb.setColorStroke(spc_rgb, 0.9f); cb.setLineWidth(5f); cb.circle(150f, 500f, 100f); cb.stroke(); // Fill the circle with RGB alternate cb.setColorFill(spc_rgb, 0.9f); cb.circle(150f, 500f, 50f); cb.fill(); // example with colorfill cb.setColorFill(spc_g, 0.5f); cb.moveTo(100f, 200f); cb.lineTo(200f, 250f); cb.lineTo(400f, 150f); cb.fill(); // cb.sanityCheck is called during newPage(). document.newPage(); String text = "Some text to show"; document.add(new Paragraph(text, new Font(Font.HELVETICA, 24, Font.NORMAL, new SpotColor(spc_cmyk, 0.25f)))); document.add(new Paragraph(text, new Font(Font.HELVETICA, 24, Font.NORMAL, new SpotColor(spc_cmyk, 0.5f)))); // example with template PdfTemplate t = cb.createTemplate(500f, 500f); // Stroke a rectangle with CMYK alternate t.setColorStroke(new SpotColor(spc_cmyk, .5f)); t.setLineWidth(10f); // draw a rectangle t.rectangle(100, 10, 100, 100); // add the diagonal t.moveTo(100, 10); t.lineTo(200, 100); // stroke the lines t.stroke(); // Fill a rectangle with CMYK alternate t.setColorFill(spc_g, 0.5f); t.rectangle(100, 125, 100, 100); t.fill(); t.beginText(); t.setFontAndSize(bf, 20f); t.setTextMatrix(1f, 0f, 0f, 1f, 10f, 10f); t.showText("Template text upside down"); t.endText(); t.rectangle(0, 0, 499, 499); t.stroke(); t.sanityCheck(); cb.addTemplate(t, -1.0f, 0.00f, 0.00f, -1.0f, 550f, 550f); cb.sanityCheck(); // step 5: we close the document document.close(); }
Example 13
Source File: PatternTest.java From itext2 with GNU Lesser General Public License v3.0 | 4 votes |
/** * Painting Patterns. * * @param args * no arguments needed */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(PageSize.A4, 50, 50, 50, 50); // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("pattern.pdf")); // step 3: we open the document document.open(); // step 4: we add some content PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(400, 300); PdfPatternPainter pat = cb.createPattern(15, 15, null); pat.rectangle(5, 5, 5, 5); pat.fill(); pat.sanityCheck(); PdfSpotColor spc_cmyk = new PdfSpotColor("PANTONE 280 CV", new CMYKColor(0.9f, .2f, .3f, .1f)); SpotColor spot = new SpotColor(spc_cmyk, 0.25f); tp.setPatternFill(pat, spot, .9f); tp.rectangle(0, 0, 400, 300); tp.fill(); tp.sanityCheck(); cb.addTemplate(tp, 50, 50); PdfPatternPainter pat2 = cb.createPattern(10, 10, null); pat2.setLineWidth(2); pat2.moveTo(-5, 0); pat2.lineTo(10, 15); pat2.stroke(); pat2.moveTo(0, -5); pat2.lineTo(15, 10); pat2.stroke(); cb.setLineWidth(1); cb.setColorStroke(Color.black); cb.setPatternFill(pat2, Color.red); cb.rectangle(100, 400, 30, 210); cb.fillStroke(); cb.setPatternFill(pat2, Color.green); cb.rectangle(150, 400, 30, 100); cb.fillStroke(); cb.setPatternFill(pat2, Color.blue); cb.rectangle(200, 400, 30, 130); cb.fillStroke(); cb.setPatternFill(pat2, new GrayColor(0.5f)); cb.rectangle(250, 400, 30, 80); cb.fillStroke(); cb.setPatternFill(pat2, new GrayColor(0.7f)); cb.rectangle(300, 400, 30, 170); cb.fillStroke(); cb.setPatternFill(pat2, new GrayColor(0.9f)); cb.rectangle(350, 400, 30, 40); cb.fillStroke(); cb.sanityCheck(); // step 5: we close the document document.close(); }
Example 14
Source File: GroupsTest.java From itext2 with GNU Lesser General Public License v3.0 | 4 votes |
/** * Demonstrates the Transparency functionality. */ @Test public void main() { // step 1: creation of a document-object Document document = new Document(PageSize.A4, 50, 50, 50, 50); try { // step 2: creation of a writer PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("groups.pdf")); // step 3: we open the document document.open(); // step 4: content PdfContentByte cb = writer.getDirectContent(); float gap = (document.getPageSize().getWidth() - 400) / 3; pictureBackdrop(gap, 500, cb); pictureBackdrop(200 + 2 * gap, 500, cb); pictureBackdrop(gap, 500 - 200 - gap, cb); pictureBackdrop(200 + 2 * gap, 500 - 200 - gap, cb); PdfTemplate tp; PdfTransparencyGroup group; tp = cb.createTemplate(200, 200); pictureCircles(0, 0, tp); group = new PdfTransparencyGroup(); group.setIsolated(true); group.setKnockout(true); tp.setGroup(group); tp.sanityCheck(); cb.addTemplate(tp, gap, 500); tp = cb.createTemplate(200, 200); pictureCircles(0, 0, tp); group = new PdfTransparencyGroup(); group.setIsolated(true); group.setKnockout(false); tp.setGroup(group); tp.sanityCheck(); cb.addTemplate(tp, 200 + 2 * gap, 500); tp = cb.createTemplate(200, 200); pictureCircles(0, 0, tp); group = new PdfTransparencyGroup(); group.setIsolated(false); group.setKnockout(true); tp.setGroup(group); tp.sanityCheck(); cb.addTemplate(tp, gap, 500 - 200 - gap); tp = cb.createTemplate(200, 200); pictureCircles(0, 0, tp); group = new PdfTransparencyGroup(); group.setIsolated(false); group.setKnockout(false); tp.setGroup(group); tp.sanityCheck(); cb.addTemplate(tp, 200 + 2 * gap, 500 - 200 - gap); cb.sanityCheck(); } catch (Exception de) { de.printStackTrace(); } // step 5: we close the document document.close(); }
Example 15
Source File: ExportHighCharts.java From Knowage-Server with GNU Affero General Public License v3.0 | 4 votes |
public static void transformSVGIntoPDF(InputStream inputStream, OutputStream outputStream) throws IOException, DocumentException { Rectangle pageSize = PageSize.A4; Document document = new Document(pageSize); int orientation = PageFormat.PORTRAIT; try { PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); double a4WidthInch = 8.26771654; // Equals 210mm double a4HeightInch = 11.6929134; // Equals 297mm Paper paper = new Paper(); // 72 DPI paper.setSize((a4WidthInch * 72), (a4HeightInch * 72)); // 1 inch margins paper.setImageableArea(72, 72, (a4WidthInch * 72 - 144), (a4HeightInch * 72 - 144)); PageFormat pageFormat = new PageFormat(); pageFormat.setPaper(paper); pageFormat.setOrientation(orientation); float width = ((float) pageFormat.getWidth()); float height = ((float) pageFormat.getHeight()); PdfContentByte cb = writer.getDirectContent(); PdfTemplate template = cb.createTemplate(width, height); Graphics2D g2 = template.createGraphics(width, height); PrintTranscoder prm = new PrintTranscoder(); TranscoderInput ti = new TranscoderInput(inputStream); prm.transcode(ti, null); prm.print(g2, pageFormat, 0); g2.dispose(); ImgTemplate img = new ImgTemplate(template); img.setWidthPercentage(100); img.setAlignment(Image.ALIGN_CENTER); document.add(img); } catch (DocumentException e) { logger.error("Error exporting Highcharts to PDF: " + e); } document.close(); }
Example 16
Source File: AffineTransformationTest.java From itext2 with GNU Lesser General Public License v3.0 | 4 votes |
/** * Changes the transformation matrix with AffineTransform. */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(PageSize.A4); // step 2: creation of the writer PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("affinetransformation.pdf")); // step 3: we open the document document.open(); // step 4: PdfContentByte cb = writer.getDirectContent(); cb.transform(AffineTransform.getScaleInstance(1.2, 0.75)); // we create a PdfTemplate PdfTemplate template = cb.createTemplate(25, 25); // we add some crosses to visualize the coordinates template.moveTo(13, 0); template.lineTo(13, 25); template.moveTo(0, 13); template.lineTo(50, 13); template.stroke(); template.sanityCheck(); // we add the template on different positions cb.addTemplate(template, 216 - 13, 720 - 13); cb.addTemplate(template, 360 - 13, 360 - 13); cb.addTemplate(template, 360 - 13, 504 - 13); cb.addTemplate(template, 72 - 13, 144 - 13); cb.addTemplate(template, 144 - 13, 288 - 13); cb.moveTo(216, 720); cb.lineTo(360, 360); cb.lineTo(360, 504); cb.lineTo(72, 144); cb.lineTo(144, 288); cb.stroke(); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.beginText(); cb.setFontAndSize(bf, 12); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "(3\" * 1.2, 10\" * .75)", 216 + 25, 720 + 5, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "(5\" * 1.2, 5\" * .75)", 360 + 25, 360 + 5, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "(5\" * 1.2, 7\" * .75)", 360 + 25, 504 + 5, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "(1\" * 1.2, 2\" * .75)", 72 + 25, 144 + 5, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "(2\" * 1.2, 4\" * .75)", 144 + 25, 288 + 5, 0); cb.endText(); cb.sanityCheck(); // step 5: we close the document document.close(); }
Example 17
Source File: UpsideDownTest.java From itext2 with GNU Lesser General Public License v3.0 | 4 votes |
/** * Changes the default coordinate system so that the origin is in the upper left corner * instead of the lower left corner. */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(PageSize.A4); try { // step 2: creation of the writer PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream( "upsidedown.pdf")); // step 3: we open the document document.open(); // step 4: PdfContentByte cb = writer.getDirectContent(); cb.concatCTM(1f, 0f, 0f, -1f, 0f, PageSize.A4.getHeight()); // we create a PdfTemplate PdfTemplate template = cb.createTemplate(25, 25); // we add some crosses to visualize the coordinates template.moveTo(13, 0); template.lineTo(13, 25); template.moveTo(0, 13); template.lineTo(50, 13); template.stroke(); template.sanityCheck(); // we add the template on different positions cb.addTemplate(template, 216 - 13, 720 - 13); cb.addTemplate(template, 360 - 13, 360 - 13); cb.addTemplate(template, 360 - 13, 504 - 13); cb.addTemplate(template, 72 - 13, 144 - 13); cb.addTemplate(template, 144 - 13, 288 - 13); cb.moveTo(216, 720); cb.lineTo(360, 360); cb.lineTo(360, 504); cb.lineTo(72, 144); cb.lineTo(144, 288); cb.stroke(); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.beginText(); cb.setFontAndSize(bf, 12); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "(3\", 10\")", 216 + 25, 720 + 5, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "(5\", 5\")", 360 + 25, 360 + 5, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "(5\", 7\")", 360 + 25, 504 + 5, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "(1\", 2\")", 72 + 25, 144 + 5, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "(2\", 4\")", 144 + 25, 288 + 5, 0); cb.endText(); cb.sanityCheck(); } catch(DocumentException de) { System.err.println(de.getMessage()); } catch(IOException ioe) { System.err.println(ioe.getMessage()); } // step 5: we close the document document.close(); }
Example 18
Source File: TransformationsTest.java From itext2 with GNU Lesser General Public License v3.0 | 4 votes |
/** * Adding a template using different transformation matrices. */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(PageSize.A4); // step 2: creation of the writer PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("transformations.pdf")); // step 3: we open the document document.open(); // step 4: PdfContentByte cb = writer.getDirectContent(); // we create a PdfTemplate PdfTemplate template = cb.createTemplate(120, 120); // we add some graphics template.moveTo(30, 10); template.lineTo(90, 10); template.lineTo(90, 80); template.lineTo(110, 80); template.lineTo(60, 110); template.lineTo(10, 80); template.lineTo(30, 80); template.closePath(); template.stroke(); template.sanityCheck(); // we add the template on different positions cb.addTemplate(template, 0, 0); cb.addTemplate(template, 0, 1, -1, 0, 200, 600); cb.addTemplate(template, .5f, 0, 0, .5f, 100, 400); cb.sanityCheck(); // we go to a new page document.newPage(); cb.addTemplate(template, 0, 500); cb.addTemplate(template, 2, 0, -1, 2, 200, 300); cb.sanityCheck(); // step 5: we close the document document.close(); }
Example 19
Source File: XandYcoordinatesTest.java From itext2 with GNU Lesser General Public License v3.0 | 4 votes |
/** * Creates a PDF document with shapes, lines and text at specific X and Y coordinates. */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(); try { // step 2: creation of the writer PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream( "XandY.pdf")); // step 3: we open the document document.open(); // step 4: PdfContentByte cb = writer.getDirectContent(); // we create a PdfTemplate PdfTemplate template = cb.createTemplate(25, 25); // we add some crosses to visualize the coordinates template.moveTo(13, 0); template.lineTo(13, 25); template.moveTo(0, 13); template.lineTo(50, 13); template.stroke(); template.sanityCheck(); // we add the template on different positions cb.addTemplate(template, 216 - 13, 720 - 13); cb.addTemplate(template, 360 - 13, 360 - 13); cb.addTemplate(template, 360 - 13, 504 - 13); cb.addTemplate(template, 72 - 13, 144 - 13); cb.addTemplate(template, 144 - 13, 288 - 13); cb.moveTo(216, 720); cb.lineTo(360, 360); cb.lineTo(360, 504); cb.lineTo(72, 144); cb.lineTo(144, 288); cb.stroke(); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.beginText(); cb.setFontAndSize(bf, 12); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "(3\", 10\")", 216 + 25, 720 + 5, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "(5\", 5\")", 360 + 25, 360 + 5, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "(5\", 7\")", 360 + 25, 504 + 5, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "(1\", 2\")", 72 + 25, 144 + 5, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "(2\", 4\")", 144 + 25, 288 + 5, 0); cb.endText(); cb.sanityCheck(); } catch(DocumentException de) { System.err.println(de.getMessage()); } catch(IOException ioe) { System.err.println(ioe.getMessage()); } // step 5: we close the document document.close(); }
Example 20
Source File: CharacterSheet.java From gcs with Mozilla Public License 2.0 | 4 votes |
/** * @param path The path to save to. * @return {@code true} on success. */ public boolean saveAsPDF(Path path) { Set<Row> changed = expandAllContainers(); try { PrintManager settings = mCharacter.getPageSettings(); PageFormat format = settings != null ? settings.createPageFormat() : createDefaultPageFormat(); float width = (float) format.getWidth(); float height = (float) format.getHeight(); adjustToPageSetupChanges(true); setPrinting(true); com.lowagie.text.Document pdfDoc = new com.lowagie.text.Document(new com.lowagie.text.Rectangle(width, height)); try (OutputStream out = Files.newOutputStream(path)) { PdfWriter writer = PdfWriter.getInstance(pdfDoc, out); int pageNum = 0; PdfContentByte cb; pdfDoc.open(); cb = writer.getDirectContent(); while (true) { PdfTemplate template = cb.createTemplate(width, height); Graphics2D g2d = template.createGraphics(width, height, new DefaultFontMapper()); if (print(g2d, format, pageNum) == NO_SUCH_PAGE) { g2d.dispose(); break; } if (pageNum != 0) { pdfDoc.newPage(); } g2d.setClip(0, 0, (int) width, (int) height); print(g2d, format, pageNum++); g2d.dispose(); cb.addTemplate(template, 0, 0); } pdfDoc.close(); } return true; } catch (Exception exception) { Log.error(exception); return false; } finally { setPrinting(false); closeContainers(changed); } }