public void buildPdfDocument(OutputStream toWrite, final String name, final int treeCount, String[] codeFragments, String imagePath) throws Exception { // create pdf final Document doc = new Document(); final PdfWriter pdfWriter = PdfWriter.getInstance(doc, toWrite); pdfWriter.setEncryption(null, null, PdfWriter.ALLOW_DEGRADED_PRINTING | PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128); _imagePath = imagePath; doc.open(); PdfContentByte cb = pdfWriter.getDirectContent(); PdfHelper.createHeaderBlock(cb,1,1); PdfHelper.createCircleAndText(cb, "Gutschein", 298f, 705f, 75, textFontForCircle, 0x7F, 0xAD, 0x09); createBlueBlock(cb, treeCount); createGreyBlock(cb, codeFragments); pdfHelper.addLogo(cb, _imagePath, 262f, 35f); doc.close(); }
public ImageInstance getImageByFile( PdfContentByte cb , File file ) throws IOException, BadElementException{ Image image = null; ImageInstance instance = null; if( file.getName().toLowerCase().endsWith( ".pdf")){ PdfReader reader = new PdfReader( file.getAbsolutePath() ); PdfImportedPage p = cb.getPdfWriter().getImportedPage(reader, 1); image = Image.getInstance(p); instance = new ImageInstance(image, reader); }else{ image = Image.getInstance( file.getAbsolutePath() ); instance = new ImageInstance(image, null); } instances.add(instance); return instance; }
public void createRoundRectangle(PdfContentByte cb, Block block ){ PdfDocument request = getPdfDocument(block); float[] positions = getBoundsInPs(block); float[] mmPositions = getBoundsInMMIncludeCutmark(block); PdfTemplate tp = cb.createTemplate(positions[2],positions[3]); tp.roundRectangle( 0, 0, positions[2], positions[3], SizeFactory.millimetersToPostscriptPoints( block.getRadius() ) ); // because pdf i calculated from bottom up cb.addTemplate( tp, positions[0], SizeFactory.millimetersToPostscriptPoints( request.getSize()[1] - ( mmPositions[1] + mmPositions[3])) ); }
@Override public void onRender(PdfContentByte cb) throws PdfRenderException { Integer[] pageSizes = getPage().getPdfDocument().getSize(); float[] pos = getPosition(); float[] moveTo = getMoveTo(); cb.setLineWidth( getThickness() ); cb.setColorStroke( getBaseColor() ); float y1 = pageSizes[1] + SizeFactory.CUT_MARK - pos[1]; // seams strange but pdf starts bottom and up. float y2 = pageSizes[1] + SizeFactory.CUT_MARK - moveTo[1]; // x , y. y is backward in pdf so start pos is the entire page height cb.moveTo( SizeFactory.millimetersToPostscriptPoints( pos[0] + SizeFactory.CUT_MARK ) , SizeFactory.millimetersToPostscriptPoints( y1 ) ); cb.lineTo( SizeFactory.millimetersToPostscriptPoints( moveTo[0] + SizeFactory.CUT_MARK ) , SizeFactory.millimetersToPostscriptPoints( y2 ) ); cb.stroke(); }
public void print(String plot_pdf) { try { float width = jframe.getSize().width, height = jframe.getSize().height; Document document = new Document(new Rectangle(width, height)); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(plot_pdf)); document.open(); PdfContentByte canvas = writer.getDirectContent(); PdfTemplate template = canvas.createTemplate(width, height); Graphics2D g2d = new PdfGraphics2D(template, width, height); jframe.paint(g2d); g2d.dispose(); canvas.addTemplate(template, 0, 0); document.close(); } catch (FileNotFoundException | DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * The <code>closePassedStream</code> method closes the stream passed. * * @param reader {@link PdfReader} * @param document {@link Document} * @param contentByte {@link PdfContentByte} * @param writer {@link PdfWriter} * @param fileInputStream {@link FileInputStream} * @param fileOutputStream {@link FileOutputStream} * @throws IOException {@link} if unable to close input or output stream */ private static void closePassedStream(final PdfReader reader, final Document document, final PdfContentByte contentByte, final PdfWriter writer, final FileInputStream fileInputStream, final FileOutputStream fileOutputStream) throws IOException { if (null != reader) { reader.close(); } if (null != document) { document.close(); } if (null != contentByte) { contentByte.closePath(); } if (null != writer) { writer.close(); } if (null != fileInputStream) { fileInputStream.close(); } if (null != fileOutputStream) { fileOutputStream.flush(); fileOutputStream.close(); } }
void split(PdfReader reader, int page) throws IOException { PdfImportedPage importedPage = writer.getImportedPage(reader, page); Rectangle pageSizeToImport = reader.getPageSize(page); Iterable<Rectangle> rectangles = determineSplitRectangles(reader, page); for (Rectangle rectangle : rectangles) { newPage(rectangle); PdfContentByte directContent = writer.getDirectContent(); directContent.saveState(); directContent.rectangle(rectangle.getLeft(), rectangle.getBottom(), rectangle.getWidth(), rectangle.getHeight()); directContent.clip(); directContent.newPath(); writer.getDirectContent().addTemplate(importedPage, -pageSizeToImport.getLeft(), -pageSizeToImport.getBottom()); directContent.restoreState(); } }
@Override public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) { PdfContentByte canvas = canvases[PdfPTable.BACKGROUNDCANVAS]; float xTransition = position.getLeft() + (position.getRight() - position.getLeft()) * (percent/100.0f); float yTransition = (position.getTop() + position.getBottom()) / 2f; float radius = (position.getRight() - position.getLeft()) * 0.025f; PdfShading axial = PdfShading.simpleAxial(canvas.getPdfWriter(), xTransition - radius, yTransition, xTransition + radius, yTransition, leftColor, rightColor); PdfShadingPattern shading = new PdfShadingPattern(axial); canvas.saveState(); canvas.setShadingFill(shading); canvas.rectangle(position.getLeft(), position.getBottom(), position.getWidth(), position.getHeight()); // canvas.clip(); canvas.fill(); canvas.restoreState(); }
/** * The OP's original code transformed into Java */ void stampTextOriginal(InputStream source, OutputStream target) throws DocumentException, IOException { Date today = new Date(); PdfReader reader = new PdfReader(source); PdfStamper stamper = new PdfStamper(reader, target); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED); int tSize = 24; String mark = "DRAFT " + today; int angle = 45; float height = reader.getPageSizeWithRotation(1).getHeight()/2; float width = reader.getPageSizeWithRotation(1).getWidth()/2; PdfContentByte cb = stamper.getOverContent(1); cb.setColorFill(new BaseColor(255,200,200)); cb.setFontAndSize(bf, tSize); cb.beginText(); cb.showTextAligned(Element.ALIGN_CENTER, mark, width, height, angle); cb.endText(); stamper.close(); reader.close(); }
/** * The OP's code transformed into Java changed with the work-around. */ void stampTextChanged(InputStream source, OutputStream target) throws DocumentException, IOException { Date today = new Date(); PdfReader reader = new PdfReader(source); PdfStamper stamper = new PdfStamper(reader, target); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED); int tSize = 24; String mark = "DRAFT " + today; int angle = 45; float height = reader.getPageSizeWithRotation(1).getHeight()/2; float width = reader.getPageSizeWithRotation(1).getWidth()/2; PdfContentByte cb = stamper.getOverContent(1); cb.setFontAndSize(bf, tSize); cb.beginText(); cb.setColorFill(new BaseColor(255,200,200)); cb.showTextAligned(Element.ALIGN_CENTER, mark, width, height, angle); cb.endText(); stamper.close(); reader.close(); }
/** * <a href="http://stackoverflow.com/questions/35082653/adobe-reader-cant-display-unicode-font-of-pdf-added-with-itext"> * Adobe Reader can't display unicode font of pdf added with iText * </a> * <br/> * <a href="https://www.dropbox.com/s/erkv9wot9d460dg/sampleOriginal.pdf?dl=0"> * sampleOriginal.pdf * </a> * <p> * Indeed, just like in the iTextSharp version of the code, the resulting file has * issues in Adobe Reader. With a different starting file, though, it doesn't, cf. * {@link #testAddUnicodeStampEg_01()}. * </p> * <p> * As it eventually turns out, Adobe Reader treats PDF files with composite fonts * differently if they claim to be PDF-1.2 like the OP's sample file. * </p> */ @Test public void testAddUnicodeStampSampleOriginal() throws DocumentException, IOException { try ( InputStream resource = getClass().getResourceAsStream("sampleOriginal.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "sampleOriginal-unicodeStamp.pdf")) ) { PdfReader reader = new PdfReader(resource); PdfStamper stamper = new PdfStamper(reader, result); BaseFont bf = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); PdfContentByte cb = stamper.getOverContent(1); Phrase p = new Phrase(); p.setFont(new Font(bf, 25, Font.NORMAL, BaseColor.BLUE)); p.add("Sample Text"); ColumnText.showTextAligned(cb, PdfContentByte.ALIGN_LEFT, p, 200, 200, 0); stamper.close(); } }
/** * <a href="http://stackoverflow.com/questions/35082653/adobe-reader-cant-display-unicode-font-of-pdf-added-with-itext"> * Adobe Reader can't display unicode font of pdf added with iText * </a> * <br/> * <a href="https://www.dropbox.com/s/erkv9wot9d460dg/sampleOriginal.pdf?dl=0"> * sampleOriginal.pdf * </a> * <p> * Indeed, just like in the iTextSharp version of the code, the resulting file has * issues in Adobe Reader, cf. {@link #testAddUnicodeStampSampleOriginal()}. With * a different starting file, though, it doesn't as this test shows. * </p> * <p> * As it eventually turns out, Adobe Reader treats PDF files with composite fonts * differently if they claim to be PDF-1.2 like the OP's sample file. * </p> */ @Test public void testAddUnicodeStampEg_01() throws DocumentException, IOException { try ( InputStream resource = getClass().getResourceAsStream("eg_01.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "eg_01-unicodeStamp.pdf")) ) { PdfReader reader = new PdfReader(resource); PdfStamper stamper = new PdfStamper(reader, result); BaseFont bf = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); PdfContentByte cb = stamper.getOverContent(1); Phrase p = new Phrase(); p.setFont(new Font(bf, 25, Font.NORMAL, BaseColor.BLUE)); p.add("Sample Text"); ColumnText.showTextAligned(cb, PdfContentByte.ALIGN_LEFT, p, 200, 200, 0); stamper.close(); } }
public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) { PdfWriter writer = canvases[0].getPdfWriter(); float x = position.getLeft(); float y = position.getBottom(); Rectangle rect = new Rectangle(x-5, y-5, x+5, y+5); RadioCheckField checkbox = new RadioCheckField( writer, rect, name, "Yes"); checkbox.setCheckType(RadioCheckField.TYPE_CROSS); checkbox.setChecked(check); // change: set border color checkbox.setBorderColor(BaseColor.BLACK); try { pdfStamper.addAnnotation(checkbox.getCheckField(), page); } catch (Exception e) { throw new ExceptionConverter(e); } }
PdfAnnotation createAnnotation(PdfWriter writer, Rectangle rect, String contents) throws DocumentException, IOException { PdfContentByte cb = writer.getDirectContent(); PdfAppearance cs = cb.createAppearance(rect.getWidth(), rect.getHeight()); cs.rectangle(0 , 0, rect.getWidth(), rect.getHeight()); cs.fill(); cs.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED), 12); cs.beginText(); cs.setLeading(12 + 1.75f); cs.moveText(.75f, rect.getHeight() - 12 + .75f); cs.showText(contents); cs.endText(); return PdfAnnotation.createFreeText(writer, rect, contents, cs); }
/** * <a href="http://stackoverflow.com/questions/32162759/columntext-showtextaligned-vs-columntext-setsimplecolumn-top-alignment"> * ColumnText.ShowTextAligned vs ColumnText.SetSimpleColumn Top Alignment * </a> * <p> * Indeed, the coordinates do not line up. The y coordinate of * {@link ColumnText#showTextAligned(PdfContentByte, int, Phrase, float, float, float)} * denotes the baseline while {@link ColumnText#setSimpleColumn(Rectangle)} surrounds * the text to come. * </p> */ @Test public void testShowTextAlignedVsSimpleColumnTopAlignment() throws DocumentException, IOException { Document document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "ColumnTextTopAligned.pdf"))); document.open(); Font fontQouteItems = new Font(BaseFont.createFont(), 12); PdfContentByte canvas = writer.getDirectContent(); // Item Number ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, new Phrase("36222-0", fontQouteItems), 60, 450, 0); // Estimated Qty ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, new Phrase("47", fontQouteItems), 143, 450, 0); // Item Description ColumnText ct = new ColumnText(canvas); // Uses a simple column box to provide proper text wrapping ct.setSimpleColumn(new Rectangle(193, 070, 390, 450)); ct.setText(new Phrase("In-Situ : Poly Cable - 100'\nPoly vented rugged black gable 100ft\nThis is an additional description. It can wrap an extra line if it needs to so this text is long.", fontQouteItems)); ct.go(); document.close(); }
private static void drawSexyTriangle(PdfWriter writer, boolean rotated) { PdfContentByte canvas = writer.getDirectContent(); float x = 36; float y = 400; float side = 70; PdfShading axial = rotated ? PdfShading.simpleAxial(writer, PageSize.A4.getRight() - y, x, PageSize.A4.getRight() - y, x + side, BaseColor.PINK, BaseColor.BLUE) : PdfShading.simpleAxial(writer, x, y, x + side, y, BaseColor.PINK, BaseColor.BLUE); PdfShadingPattern shading = new PdfShadingPattern(axial); canvas.setShadingFill(shading); canvas.moveTo(x,y); canvas.lineTo(x + side, y); canvas.lineTo(x + (side / 2), (float)(y + (side * Math.sin(Math.PI / 3)))); canvas.closePathFillStroke(); }
private static void createRectangle(PdfWriter writer, float x, float y, float width, float height, BaseColor color) { float posX = Utilities.millimetersToPoints(x); float posY = Utilities.millimetersToPoints(y); float widthX = Utilities.millimetersToPoints(width + x); float heightY = Utilities.millimetersToPoints(height + y); Rectangle rectangle = new Rectangle(posX, posY, widthX, heightY); PdfContentByte canvas = writer.getDirectContent(); rectangle.setBorder(Rectangle.BOX); rectangle.setBorderWidth(1); rectangle.setBorderColor(color); canvas.rectangle(rectangle); }
/** * <a href="http://stackoverflow.com/questions/43870545/filling-a-pdf-with-itextsharp-and-then-hiding-the-base-layer"> * Filling a PDF with iTextsharp and then hiding the base layer * </a> * <p> * This test shows how to cover all content using a white rectangle. * </p> */ @Test public void testHideContenUnderRectangle() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("document.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "document-hiddenContent.pdf"))) { PdfReader pdfReader = new PdfReader(resource); PdfStamper pdfStamper = new PdfStamper(pdfReader, result); for (int page = 1; page <= pdfReader.getNumberOfPages(); page++) { Rectangle pageSize = pdfReader.getPageSize(page); PdfContentByte canvas = pdfStamper.getOverContent(page); canvas.setColorFill(BaseColor.WHITE); canvas.rectangle(pageSize.getLeft(), pageSize.getBottom(), pageSize.getWidth(), pageSize.getHeight()); canvas.fill(); } pdfStamper.close(); } }
void addRotatedImage(PdfContentByte contentByte, Image image, float x, float y, float width, float height, float rotation) throws DocumentException { // Draw image at x,y without rotation contentByte.addImage(image, width, 0, 0, height, x, y); // Draw image as if the previous image was rotated around its center // Image starts out being 1x1 with origin in lower left // Move origin to center of image AffineTransform A = AffineTransform.getTranslateInstance(-0.5, -0.5); // Stretch it to its dimensions AffineTransform B = AffineTransform.getScaleInstance(width, height); // Rotate it AffineTransform C = AffineTransform.getRotateInstance(rotation); // Move it to have the same center as above AffineTransform D = AffineTransform.getTranslateInstance(x + width/2, y + height/2); // Concatenate AffineTransform M = (AffineTransform) A.clone(); M.preConcatenate(B); M.preConcatenate(C); M.preConcatenate(D); //Draw contentByte.addImage(image, M); }
static byte[] createRotatedImagePdf() throws DocumentException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); PdfContentByte directContent = writer.getDirectContent(); BufferedImage bim = new BufferedImage(1000, 250, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = bim.createGraphics(); g2d.setColor(Color.BLUE); g2d.fillRect(0, 0, 500, 500); g2d.dispose(); Image image = Image.getInstance(bim, null); directContent.addImage(image, 0, 500, -500, 0, 550, 50); document.close(); return baos.toByteArray(); }
public static byte[] stampLayer(InputStream _pdfFile, Image iImage, int x, int y, String layername, boolean readLayers) throws IOException, DocumentException { PdfReader reader = new PdfReader(_pdfFile); try ( ByteArrayOutputStream ms = new ByteArrayOutputStream() ) { PdfStamper stamper = new PdfStamper(reader, ms); //Don't delete otherwise the stamper flattens the layers if (readLayers) stamper.getPdfLayers(); PdfLayer logoLayer = new PdfLayer(layername, stamper.getWriter()); PdfContentByte cb = stamper.getUnderContent(1); cb.beginLayer(logoLayer); //300dpi iImage.scalePercent(24f); iImage.setAbsolutePosition(x, y); cb.addImage(iImage); cb.endLayer(); stamper.close(); return (ms.toByteArray()); } }
/** * @see com.itextpdf.text.pdf.PdfPageEventHelper#onStartPage(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document) */ public void onStartPage(PdfWriter writer, Document document) { if (writer.getPageNumber() < 3) { PdfContentByte cb = writer.getDirectContentUnder(); cb.saveState(); cb.setColorFill(BaseColor.PINK); cb.beginText(); cb.setFontAndSize(helv, 48); cb.showTextAligned(Element.ALIGN_CENTER, "My Watermark Under " + writer.getPageNumber(), document.getPageSize().getWidth() / 2, document.getPageSize().getHeight() / 2, 45); cb.endText(); cb.restoreState(); } }
/** * Create a series bar code for this series * * @return Image */ private static Image getBarCode(PdfContentByte cb, TridasSample s) { UUID uuid = UUID.fromString(s.getIdentifier().getValue()); LabBarcode barcode = new LabBarcode(LabBarcode.Type.SAMPLE, uuid); barcode.setX(1.0f); //barcode.setN(0.5f); //barcode.setSize(6f); barcode.setFont(null); //barcode.setBaseline(8f); barcode.setBarHeight(20f); Image image = barcode.createImageWithBarcode(cb, null, null); return image; }
/** * Writes commands to stroke and / or fill the last geometry. */ private void writeFillStroke(VectorSymbol symbol, boolean close, PdfContentByte cb) { if (symbol == null) { return; } final boolean fill = symbol.isFilled(); final boolean stroke = symbol.isStroked(); if (fill && stroke) { cb.fillStroke(); } else if (fill) { cb.fill(); } else if (stroke) { cb.stroke(); } else // nothing: invisible element ; }
public void writePdfDataToOutputStream(OutputStream toWrite, final int treeCount, final String text, final String name, final String number, String imagePath) throws Exception { // create pdf final Document doc = new Document(); final PdfWriter pdfWriter = PdfWriter.getInstance(doc, toWrite); pdfWriter.setEncryption(null, null, PdfWriter.ALLOW_DEGRADED_PRINTING | PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128); final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+2"), Locale.GERMAN); cal.setTimeInMillis(System.currentTimeMillis()); final String date = cal.get(Calendar.DAY_OF_MONTH) + "." + (cal.get(Calendar.MONTH) + 1) + "." + cal.get(Calendar.YEAR); _imagePath = imagePath; doc.open(); PdfContentByte cb = pdfWriter.getDirectContent(); PdfHelper.createHeaderBlock(cb,1,1); PdfHelper.createCircleAndText(cb, "Zertifikat", 298f, 665f, 75f, textFontForCircle, 0x9E, 0x3C, 0x59); createTreeCountAndCustomTextBlock(cb, text, treeCount); createLawTextDateAndSignatureBlock(cb, number, date); pdfHelper.addLogo(cb, imagePath, 262f, 20f); doc.close(); }
public void writePdfDataToOutputStream(OutputStream toWrite, final int treeCount, final String text, final String name, final String number, String imagePath) throws Exception { // create pdf final Document doc = new Document(); final PdfWriter pdfWriter = PdfWriter.getInstance(doc, toWrite); pdfWriter.setEncryption(null, null, PdfWriter.ALLOW_DEGRADED_PRINTING | PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128); final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+2"), Locale.GERMAN); cal.setTimeInMillis(System.currentTimeMillis()); final String date = cal.get(Calendar.DAY_OF_MONTH) + "." + (cal.get(Calendar.MONTH) + 1) + "." + cal.get(Calendar.YEAR); _imagePath = imagePath; doc.open(); PdfContentByte cb = pdfWriter.getDirectContent(); PdfHelper.createHeaderBlock(cb,1,1); PdfHelper.createCircleAndText(cb, "Zertifikat", 298f, 665f, 75f, textFontForCircle, 0x9E, 0x3C, 0x59); createTreeCountAndCustomTextBlock(cb, text, treeCount); createLawTextDateAndSignatureBlock(cb, number, date); pdfHelper.addLogo(cb, _imagePath, 262f, 20f); doc.close(); }
private void createReceiptHeaderAndTextBelow(PdfContentByte cb) throws DocumentException { PdfPTable headerTable = new PdfPTable(1); float[] rows = { 450f }; headerTable.setTotalWidth(rows); headerTable.getDefaultCell() .setBorder(Rectangle.NO_BORDER); headerTable.addCell(new Phrase(new Chunk("Bestätigung über Geldzuwendungen", textFontForReceiptHeader))); headerTable.writeSelectedRows(0, 1, 75f, 625, cb); PdfPTable table = new PdfPTable(1); table.setTotalWidth(rows); table.getDefaultCell() .setBorder(Rectangle.NO_BORDER); table.getDefaultCell() .setLeading(8f, 0); table.addCell(new Phrase(new Chunk("im Sinne des §10b des Einkommensteuergesetzes", textFont))); table.addCell(new Phrase(new Chunk("an eine der in §5 Abs. 1 Nr. 9 des Körperschaftsteuergesetzes bezeichneten", textFont))); table.addCell(new Phrase(new Chunk("Körperschaften, Personenvereinigungen oder Vermögensmassen", textFont))); table.writeSelectedRows(0, 3, 75f, 590, cb); }
private PdfPTable createPriceTable(PdfContentByte cb, Receipt receipt) throws DocumentException { PdfPTable tableForPrices = new PdfPTable(1); float[] rowForTotalPrice = { 250f }; tableForPrices.setTotalWidth(rowForTotalPrice); tableForPrices.getDefaultCell() .setBorder(Rectangle.NO_BORDER); tableForPrices.addCell(new Phrase(new Chunk("Betrag der Zuwendung in Ziffern:", textFont))); tableForPrices.addCell(new Phrase(new Chunk(" ", textFont))); Double totalPrice = 0.0; for (final Cart cart : receipt.getCarts()) { tableForPrices.addCell(new Phrase(new Chunk(cart.getTotalPrice() .toString() + " €", textFontUserData))); totalPrice += cart.getTotalPrice() .doubleValue(); } String formattedPrice = priceFormat.format(totalPrice) .toString(); tableForPrices.addCell(new Phrase(new Chunk("Gesamt: " + formattedPrice + " €", textFontUserData))); return tableForPrices; }
private PdfPTable createDateTable(PdfContentByte cb, Receipt receipt) throws DocumentException { PdfPTable tableForDate = new PdfPTable(1); float[] rowForDate = { 110f }; tableForDate.setTotalWidth(rowForDate); tableForDate.getDefaultCell() .setBorder(Rectangle.NO_BORDER); tableForDate.addCell(new Phrase(new Chunk("Datum der Zuwendung:", textFont))); tableForDate.addCell(new Phrase(new Chunk(" ", textFont))); final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+2"), Locale.GERMAN); for (final Cart cart : receipt.getCarts()) { cal.setTimeInMillis(cart.getTimeStamp()); final String date = cal.get(Calendar.DAY_OF_MONTH) + "." + (cal.get(Calendar.MONTH) + 1) + "." + cal.get(Calendar.YEAR); PdfPCell cell = new PdfPCell(new Phrase(new Chunk(date, textFontUserData))); cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT); cell.setBorder(PdfPCell.NO_BORDER); tableForDate.addCell(cell); } return tableForDate; }
private PdfPTable createLawTable(PdfContentByte cb) throws DocumentException { PdfPTable table = new PdfPTable(1); float[] rows = { 445f }; table.setTotalWidth(rows); table.getDefaultCell() .setBorder(Rectangle.NO_BORDER); table.getDefaultCell() .setLeading(8f, 0); table.addCell(new Phrase(new Chunk("Es handelt sich nicht um den Verzicht auf Erstattung von Aufwendungen.", textFontLawText))); table.addCell(new Phrase(new Chunk("Die Gesellschaft ist wegen Förderung (begünstigter Zweck: Umweltschutz (§52 (2) S. 1 Nr.(n) 8 AO)) durch", textFontLawText))); table.addCell(new Phrase(new Chunk("Bescheinigung des Finanzamt Halle (Saale)-Nord, StNr. 110/108/91169, vom 19.11.2008 ab 01.01.2009", textFontLawText))); table.addCell(new Phrase(new Chunk("als gemeinnützig anerkannt. Letzter Freistellungsbescheid datiert auf den 20.06.2013.", textFontLawText))); table.addCell(new Phrase(new Chunk("Es wird bestätigt, dass die Zuwendung nur zur Förderung des Umweltschutzes verwendet wird.", textFontLawText))); PdfPCell emptyCell = new PdfPCell(); emptyCell.setBorder(Rectangle.BOTTOM); emptyCell.setFixedHeight(15f); table.addCell(emptyCell); return table; }
public static void createCircleAndText(PdfContentByte cb, String text, float xCoord, float yCoord, float radius, Font textFont, int circleColorRed, int circleColorGreen, int circleColorBlue) throws DocumentException, IOException { cb.saveState(); cb.setRGBColorFill(circleColorRed, circleColorGreen, circleColorBlue); cb.circle(xCoord, yCoord, radius); cb.fill(); cb.stroke(); cb.restoreState(); PdfPTable table = new PdfPTable(1); float[] rows = { 595f }; table.setTotalWidth(rows); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE); table.getDefaultCell().setFixedHeight(radius * 2); table.addCell(new Phrase(new Chunk(text, textFont))); table.writeSelectedRows(0, 1, 0, yCoord + radius, cb); }
/** * Create the multipage PDF report from the internal list of JPanels. * @throws DocumentException */ public void createMultipagePDF() throws DocumentException { // Document defaults to A4, so specify the current dimensions Document doc= new Document(new Rectangle(pageWidth, pageHeight)); PdfWriter writer= PdfWriter.getInstance(doc, os); doc.open(); PdfContentByte cb= writer.getDirectContent(); // Iterate over tabs for (int i= 0; i != tabs.getTabCount(); ++i) { JPanel jp= (JPanel) tabs.getComponent(i); // Iterate over pages for (int currentPage= 0; currentPage < getNumPages(jp); ++currentPage) { doc.newPage(); // not needed for page 1, needed for >1 PdfTemplate template= cb.createTemplate(pageWidth, pageHeight); Graphics2D g2d= new PdfGraphics2D(template, pageWidth, pageHeight * (currentPage + 1)); jp.printAll(g2d); g2d.dispose(); cb.addTemplate(template, 0, 0); } } doc.close(); }
public static void addImage(byte[] input, OutputStream output, Image image, String placeholder) throws IOException, DocumentException { try (PdfReaderAutoclosable pdfReader = new PdfReaderAutoclosable(input); PdfStamperAutoclosable pdfStamper = new PdfStamperAutoclosable(pdfReader, output)) { AcroFields form = pdfStamper.getAcroFields(); List<AcroFields.FieldPosition> positions = form.getFieldPositions(placeholder); positions.forEach(p -> { image.scaleToFit(p.position.getWidth(), p.position.getHeight()); image.setAbsolutePosition(p.position.getLeft() + (p.position.getWidth() - image.getScaledWidth()) / 2, p.position.getBottom() + (p.position.getHeight() - image.getScaledHeight()) / 2); PdfContentByte cb = pdfStamper.getOverContent(p.page); try { cb.addImage(image); } catch(DocumentException e) { throw Throwables.propagate(e); } }); } }
@Override public void cellLayout(PdfPCell cell, Rectangle rect, PdfContentByte[] canvas) { BaseColor color = colorProviders.apply(percent); if (color != null) { PdfContentByte cb = canvas[PdfPTable.BACKGROUNDCANVAS]; cb.saveState(); cb.setColorFill(color); cb.rectangle( rect.getLeft() + margin.marginLeft, rect.getBottom() + margin.marginBottom, rect.getWidth() * percent - (margin.marginLeft + margin.marginRight), rect.getHeight() - (margin.marginTop + margin.marginBottom)); cb.fill(); cb.restoreState(); } }
public void tableLayout(PdfPTable table, float[][] width, float[] height, int headerRows, int rowStart, PdfContentByte[] canvas) { // because table is only one cell length, one can focus on using the first width float xmin = width[0][0]; float xmax = width[0][1]; float ymin = height[height.length - 1]; float ymax = height[0]; float d = 3; PdfContentByte background = canvas[PdfPTable.BASECANVAS]; background.saveState(); background.setColorFill(backgroundColor); background.roundRectangle( xmin - d, ymin - d, (xmax + d) - (xmin - d), (ymax + d) - (ymin - d), d + d); background.fill(); background.restoreState(); }
public void drawFooter(PdfContentByte canvas, PageInfos pageInfos) { if (pageInfos.getRawPageNumber() == 1 && !footerOnFirstPage) return; if (drawLine) { BaseColor lineColor = styles.getColorOrDefault(HEADER_LINE_COLOR); canvas.saveState(); canvas.setColorStroke(lineColor); canvas.setLineWidth(1.2f); canvas.moveTo(rect.getLeft(), rect.getBottom() - 6); canvas.lineTo(rect.getRight(), rect.getBottom() - 6); canvas.stroke(); canvas.restoreState(); } float bottom = rect.getBottom() - 20; Phrase footer = footerText(pageInfos); if (footer != null) { showTextAligned(canvas, Element.ALIGN_LEFT, footer, rect.getLeft(), bottom, 0); } Font footerFont = styles.getFontOrDefault(FOOTER_FONT); Phrase page = new Phrase(pageInfos.getFormattedPageNumber(), footerFont); showTextAligned(canvas, Element.ALIGN_RIGHT, page, rect.getRight(), bottom, 0); }
private PdfPTable createBarcodeTable(PdfContentByte cb, String caption, String detail, String code) { // Barcode Generation Barcode39 codeEAN = new Barcode39(); codeEAN.setCode(code); Image imageEAN = codeEAN.createImageWithBarcode(cb, null, null); // Table PdfPTable table = new PdfPTable(1); table.setSpacingBefore(10); table.setSpacingAfter(10); table.setTotalWidth(80); table.setLockedWidth(true); PdfPCell cell1 = new PdfPCell(imageEAN); PdfPCell cell2 = new PdfPCell(new Paragraph(caption)); PdfPCell cell3 = new PdfPCell(new Paragraph(detail)); cell1.setBorder(Rectangle.NO_BORDER); cell2.setBorder(Rectangle.NO_BORDER); cell3.setBorder(Rectangle.NO_BORDER); table.addCell(cell1); table.addCell(cell2); table.addCell(cell3); return table; }
public static void writeToFile(File f, Component m) throws Exception { Graphics2D g2; Document document = new Document(new Rectangle( m.getBounds().x, m.getBounds().y, m.getBounds().width, m.getBounds().height )); PdfWriter writer; writer = PdfWriter.getInstance(document, new FileOutputStream(f)); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(m.getSize().width, m.getSize().height); g2 = tp.createGraphicsShapes(m.getSize().width, m.getSize().height); m.paint(g2); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); }
public void drawFooter(PdfContentByte canvas, PageInfos pageInfos) { if (lineColor != null) { canvas.saveState(); canvas.setColorStroke(lineColor); canvas.setLineWidth(1.2f); canvas.moveTo(rect.getLeft(), rect.getBottom() - 6); canvas.lineTo(rect.getRight(), rect.getBottom() - 6); canvas.stroke(); canvas.restoreState(); } float bottom = rect.getBottom() - 20; Phrase footer = footerText(); if (footer != null) { showTextAligned(canvas, Element.ALIGN_LEFT, footer, rect.getLeft(), bottom, 0); } Phrase page = new Phrase(pageInfos.getFormattedPageNumber(), footerFont); showTextAligned(canvas, Element.ALIGN_RIGHT, page, rect.getRight(), bottom, 0); }
private List<Element> renderGral(String raw) throws BadElementException, IOException { ChartDescriptor descriptor = new ChartDescriptorParser().parse(raw); PdfContentByte cb = writer.get().getDirectContent(); float width = (float) descriptor.getWidth(); float height = (float) descriptor.getHeight(); PdfTemplate template = cb.createTemplate(width, height); Graphics2D g2 = new PdfGraphics2D(template, width, height); GralRenderer renderer = new GralRenderer(); renderer.render(g2, descriptor); ArrayList<Element> elements = new ArrayList<Element>(1); elements.add(new ImgTemplate(template)); return elements; }