Java Code Examples for com.lowagie.text.pdf.PdfContentByte#addTemplate()
The following examples show how to use
com.lowagie.text.pdf.PdfContentByte#addTemplate() .
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: PurchaseOrderQuoteRequestsPdf.java From kfs with GNU Affero General Public License v3.0 | 6 votes |
/** * Overrides the method in PdfPageEventHelper from itext to compose the footer and show the * footer. * * @param writer The PdfWriter for this document. * @param document The document. * @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document) */ public void onEndPage(PdfWriter writer, Document document) { LOG.debug("onEndPage() started."); PdfContentByte cb = writer.getDirectContent(); cb.saveState(); // compose the footer String text = "Page " + writer.getPageNumber() + " of "; float textSize = helv.getWidthPoint(text, 12); float textBase = document.bottom() - 20; cb.beginText(); cb.setFontAndSize(helv, 12); // show the footer float adjust = helv.getWidthPoint("0", 12); cb.setTextMatrix(document.right() - textSize - adjust, textBase); cb.showText(text); cb.endText(); cb.addTemplate(tpl, document.right() - adjust, textBase); cb.saveState(); }
Example 3
Source File: PurapPdf.java From kfs with GNU Affero General Public License v3.0 | 6 votes |
/** * Overrides the method in PdfPageEventHelper from itext to write the headerTable, compose the footer and show the * footer. * * @param writer The PdfWriter for this document. * @param document The document. * @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document) */ @Override public void onEndPage(PdfWriter writer, Document document) { LOG.debug("onEndPage() started."); PdfContentByte cb = writer.getDirectContent(); cb.saveState(); // write the headerTable headerTable.setTotalWidth(document.right() - document.left()); headerTable.writeSelectedRows(0, -1, document.left(), document.getPageSize().height() - 10, cb); // compose the footer String text = "Page " + writer.getPageNumber() + " of "; float textSize = helv.getWidthPoint(text, 12); float textBase = document.bottom() - 20; cb.beginText(); cb.setFontAndSize(helv, 12); // show the footer float adjust = helv.getWidthPoint("0", 12); cb.setTextMatrix(document.right() - textSize - adjust, textBase); cb.showText(text); cb.endText(); cb.addTemplate(tpl, document.right() - adjust, textBase); cb.saveState(); }
Example 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
Source File: PaperightPdfConverter.java From website with GNU Affero General Public License v3.0 | 4 votes |
private String createOneUp(String originalPdfFile) throws IOException, DocumentException { logger.debug("Started create 1-up file from " + originalPdfFile); String filename = FilenameUtils.getBaseName(originalPdfFile) + "_1up." + FilenameUtils.getExtension(originalPdfFile); String tempFilename = FilenameUtils.concat(System.getProperty("java.io.tmpdir"), filename + ".tmp"); filename = FilenameUtils.concat(getPdfFileFolder(), filename); File tempFile = new File(tempFilename); //float scale = 0.80f; PdfReader reader = new PdfReader(originalPdfFile); Document doc = new Document(PageSize.A4, 0, 0, 0, 0); //Document doc = new Document(new RectangleReadOnly(606.96f, 850.32f), 0, 0, 0, 0); PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(tempFile)); doc.open(); for (int i = 1; i <= reader.getNumberOfPages(); i++) { doc.newPage(); PdfContentByte cb = writer.getDirectContent(); PdfImportedPage page = writer.getImportedPage(reader, i); float documentWidth = doc.getPageSize().getWidth(); float documentHeight = doc.getPageSize().getHeight(); if (i > 1) { documentHeight = documentHeight - 65f; } /*float documentHeight = doc.getPageSize().getHeight(); if (i > 1) { documentHeight = documentHeight - 65f; } float documentWidth = doc.getPageSize().getWidth();*/ float pageWidth = page.getWidth(); float pageHeight = page.getHeight(); float widthScale = documentWidth / pageWidth; float heightScale = documentHeight / pageHeight; float scale = Math.min(widthScale, heightScale); float offsetX = (documentWidth - (pageWidth * scale)) / 2; float offsetY = 0f; if (i > 1) { offsetY = 65f; } /* float offsetX = 0f; if (i > 1) { offsetX = 65f; //100f } //float offsetX = 65f; float offsetY = ((documentHeight) - (pageHeight * scale)) / 2;*/ cb.addTemplate(page, scale, 0, 0, scale, offsetX, offsetY); } doc.close(); overlayLicenceArea(tempFilename, filename, PageLayout.ONE_UP); logger.debug("Deleting temporary file " + tempFile.getAbsolutePath()); FileUtils.deleteQuietly(tempFile); logger.debug("Completed create 1-up file from " + originalPdfFile); return filename; }
Example 13
Source File: PageNumbersWatermarkTest.java From itext2 with GNU Lesser General Public License v3.0 | 4 votes |
/** * @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document) */ public void onEndPage(PdfWriter writer, Document document) { PdfContentByte cb = writer.getDirectContent(); cb.saveState(); // write the headertable table.setTotalWidth(document.right() - document.left()); table.writeSelectedRows(0, -1, document.left(), document.getPageSize().getHeight() - 50, cb); // compose the footer String text = "Page " + writer.getPageNumber() + " of "; float textSize = helv.getWidthPoint(text, 12); float textBase = document.bottom() - 20; cb.beginText(); cb.setFontAndSize(helv, 12); // for odd pagenumbers, show the footer at the left if ((writer.getPageNumber() & 1) == 1) { cb.setTextMatrix(document.left(), textBase); cb.showText(text); cb.endText(); cb.addTemplate(tpl, document.left() + textSize, textBase); } // for even numbers, show the footer at the right else { float adjust = helv.getWidthPoint("0", 12); cb.setTextMatrix(document.right() - textSize - adjust, textBase); cb.showText(text); cb.endText(); cb.addTemplate(tpl, document.right() - adjust, textBase); } // draw a Rectangle around the page cb.setColorStroke(Color.orange); cb.setLineWidth(2); cb.rectangle(20, 20, document.getPageSize().getWidth() - 40, document.getPageSize().getHeight() - 40); cb.stroke(); // starting on page 3, a watermark with an Image that is made transparent if (writer.getPageNumber() >= 3) { cb.setGState(gstate); cb.setColorFill(Color.red); cb.beginText(); cb.setFontAndSize(helv, 48); cb.showTextAligned(Element.ALIGN_CENTER, "Watermark Opacity " + writer.getPageNumber(), document.getPageSize().getWidth() / 2, document.getPageSize().getHeight() / 2, 45); cb.endText(); try { cb.addImage(headerImage, headerImage.getWidth(), 0, 0, headerImage.getHeight(), 440, 80); } catch(Exception e) { throw new ExceptionConverter(e); } } cb.restoreState(); cb.sanityCheck(); }
Example 14
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); } }
Example 15
Source File: PaperightPdfConverter.java From website with GNU Affero General Public License v3.0 | 4 votes |
private String createA5(String originalPdfFile) throws IOException, DocumentException { logger.debug("Started create A5 file from " + originalPdfFile); String filename = FilenameUtils.getBaseName(originalPdfFile) + "_a5." + FilenameUtils.getExtension(originalPdfFile); String tempFilename = FilenameUtils.concat(System.getProperty("java.io.tmpdir"), filename + ".tmp"); filename = FilenameUtils.concat(getPdfFileFolder(), filename); File tempFile = new File(tempFilename); //float scale = 0.72906403940886699507389162561576f; PdfReader reader = new PdfReader(originalPdfFile); //new RectangleReadOnly(425.16f, 606.96f) Document doc = new Document(PageSize.A5, 0, 0, 0, 0); PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(tempFile)); doc.open(); for (int i = 1; i <= reader.getNumberOfPages(); i++) { doc.newPage(); PdfContentByte cb = writer.getDirectContent(); PdfImportedPage page = writer.getImportedPage(reader, i); // page #1 float documentWidth = doc.getPageSize().getWidth(); float documentHeight = doc.getPageSize().getHeight(); if (i > 1) { documentHeight = documentHeight - 65f; } //float documentHeight = doc.getPageSize().getHeight() - 65f; float pageWidth = page.getWidth(); float pageHeight = page.getHeight(); float widthScale = documentWidth / pageWidth; float heightScale = documentHeight / pageHeight; float scale = Math.min(widthScale, heightScale); //float offsetX = 50f; float offsetX = (documentWidth - (pageWidth * scale)) / 2; float offsetY = 0f; if (i > 1) { offsetY = 65f; } //float offsetY = ((documentHeight) - (pageHeight * scale)) / 2; cb.addTemplate(page, scale, 0, 0, scale, offsetX, offsetY); //cb.addTemplate(page, scale, 0, 0, scale, 50f, 100f); } doc.close(); //FileUtils.moveFile(tempFile, new File(filename)); overlayLicenceArea(tempFilename, filename, PageLayout.A5); logger.debug("Deleting temporary file " + tempFile.getAbsolutePath()); FileUtils.deleteQuietly(tempFile); logger.debug("Completed create A5 file from " + originalPdfFile); return filename; }
Example 16
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 17
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 18
Source File: TemplatesTest.java From itext2 with GNU Lesser General Public License v3.0 | 4 votes |
/** */ @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("templates.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(); // we create a PdfTemplate PdfTemplate template = cb.createTemplate(500, 200); // we add some graphics template.moveTo(0, 200); template.lineTo(500, 0); template.stroke(); template.setRGBColorStrokeF(255f, 0f, 0f); template.circle(250f, 100f, 80f); template.stroke(); // we add some text template.beginText(); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); template.setFontAndSize(bf, 12); template.setTextMatrix(100, 100); template.showText("Text at the position 100,100 (relative to the template!)"); template.endText(); template.sanityCheck(); // we add the template on different positions cb.addTemplate(template, 0, 0); cb.addTemplate(template, 0, 1, -1, 0, 500, 200); cb.addTemplate(template, .5f, 0, 0, .5f, 100, 400); // we go to a new page document.newPage(); cb.addTemplate(template, 0, 400); cb.addTemplate(template, 2, 0, 0, 2, -200, 400); cb.sanityCheck(); // step 5: we close the document document.close(); }
Example 19
Source File: TwoOnOneTest.java From itext2 with GNU Lesser General Public License v3.0 | 4 votes |
/** * Reads the pages of an existing PDF file and puts 2 pages from the * existing doc into one of the new doc. */ @Test public void main() throws Exception { // we create a reader for a certain document PdfReader reader = new PdfReader(PdfTestBase.RESOURCES_DIR + "ChapterSection.pdf"); // we retrieve the total number of pages int n = reader.getNumberOfPages(); // we retrieve the size of the first page Rectangle psize = reader.getPageSize(1); float width = psize.getHeight(); float height = psize.getWidth(); // step 1: creation of a document-object Document document = new Document(new Rectangle(width, height)); // step 2: we create a writer that listens to the document PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("2on1.pdf")); // step 3: we open the document document.open(); // step 4: we add content PdfContentByte cb = writer.getDirectContent(); int i = 0; int p = 0; while (i < n) { document.newPage(); p++; i++; PdfImportedPage page1 = writer.getImportedPage(reader, i); cb.addTemplate(page1, .5f, 0, 0, .5f, 60, 120); if (i < n) { i++; PdfImportedPage page2 = writer.getImportedPage(reader, i); cb.addTemplate(page2, .5f, 0, 0, .5f, width / 2 + 60, 120); } BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.beginText(); cb.setFontAndSize(bf, 14); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "page " + p + " of " + ((n / 2) + (n % 2 > 0 ? 1 : 0)), width / 2, 40, 0); cb.endText(); } // step 5: we close the document document.close(); }
Example 20
Source File: SplitPdf.java From itext2 with GNU Lesser General Public License v3.0 | 4 votes |
/** * This class can be used to split an existing PDF file. * @param args the command line arguments */ public static void main(String args[]) { if (args.length != 4) { System.err.println("arguments: srcfile destfile1 destfile2 pagenumber"); } else { try { int pagenumber = Integer.parseInt(args[3]); // we create a reader for a certain document PdfReader reader = new PdfReader(args[0]); // we retrieve the total number of pages int n = reader.getNumberOfPages(); System.out.println("There are " + n + " pages in the original file."); if (pagenumber < 2 || pagenumber > n) { throw new DocumentException("You can't split this document at page " + pagenumber + "; there is no such page."); } // step 1: creation of a document-object Document document1 = new Document(reader.getPageSizeWithRotation(1)); Document document2 = new Document(reader.getPageSizeWithRotation(pagenumber)); // step 2: we create a writer that listens to the document PdfWriter writer1 = PdfWriter.getInstance(document1, new FileOutputStream(args[1])); PdfWriter writer2 = PdfWriter.getInstance(document2, new FileOutputStream(args[2])); // step 3: we open the document document1.open(); PdfContentByte cb1 = writer1.getDirectContent(); document2.open(); PdfContentByte cb2 = writer2.getDirectContent(); PdfImportedPage page; int rotation; int i = 0; // step 4: we add content while (i < pagenumber - 1) { i++; document1.setPageSize(reader.getPageSizeWithRotation(i)); document1.newPage(); page = writer1.getImportedPage(reader, i); rotation = reader.getPageRotation(i); if (rotation == 90 || rotation == 270) { cb1.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight()); } else { cb1.addTemplate(page, 1f, 0, 0, 1f, 0, 0); } } while (i < n) { i++; document2.setPageSize(reader.getPageSizeWithRotation(i)); document2.newPage(); page = writer2.getImportedPage(reader, i); rotation = reader.getPageRotation(i); if (rotation == 90 || rotation == 270) { cb2.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight()); } else { cb2.addTemplate(page, 1f, 0, 0, 1f, 0, 0); } System.out.println("Processed page " + i); } // step 5: we close the document document1.close(); document2.close(); } catch(Exception e) { e.printStackTrace(); } } }