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); } }
/** * Draws a horizontal line. * @param canvas the canvas to draw on * @param leftX the left x coordinate * @param rightX the right x coordindate * @param y the y coordinate */ public void drawLine(PdfContentByte canvas, float leftX, float rightX, float y) { float w; if (getPercentage() < 0) w = -getPercentage(); else w = (rightX - leftX) * getPercentage() / 100.0f; float s; switch (getAlignment()) { case Element.ALIGN_LEFT: s = 0; break; case Element.ALIGN_RIGHT: s = rightX - leftX - w; break; default: s = (rightX - leftX - w) / 2; break; } canvas.setLineWidth(getLineWidth()); if (getLineColor() != null) canvas.setColorStroke(getLineColor()); canvas.moveTo(s + leftX, y + offset); canvas.lineTo(s + w + leftX, y + offset); canvas.stroke(); }
/** * Print footer string on each page * @param writer * @param document */ public void onEndPage(PdfWriter writer, Document document) { if(getDateTime() == null) { setDateTime(new Date()); } PdfContentByte cb = writer.getDirectContent(); cb.beginText(); cb.setFontAndSize(getBaseFont(), getFontSize()); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, getDateFormat().format(getDateTime()), document.left(), 20, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, String.valueOf(document.getPageNumber()), document.right(), 20, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, MESSAGES.pdfCopyright(Constants.getVersion()), (document.left() + document.right()) / 2, 20, 0); cb.endText(); return; }
/** * 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); }
/** * Draws arabic text using java.awt.Graphics2D. */ @Test public void main() throws Exception { // step 1 Document document = new Document(PageSize.A4, 50, 50, 50, 50); try { // step 2 PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream( "arabictext.pdf")); // step 3 document.open(); // step 4 String text1 = "This text has \u0634\u0627\u062f\u062c\u0645\u0647\u0648\u0631 123,456 \u0645\u0646 (Arabic)"; java.awt.Font font = new java.awt.Font("arial", 0, 18); PdfContentByte cb = writer.getDirectContent(); java.awt.Graphics2D g2 = cb.createGraphicsShapes(PageSize.A4.getWidth(), PageSize.A4.getHeight()); g2.setFont(font); g2.drawString(text1, 100, 100); g2.dispose(); cb.sanityCheck(); // step 5 document.close(); } catch (Exception de) { de.printStackTrace(); } }
private void setPageNumbers() throws DocumentException, IOException { int pages = getReader().getNumberOfPages(); int i = 0; PdfContentByte overContent; Rectangle pageSize = null; BaseFont font = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); while (i < pages) { i++; overContent = getStamper().getOverContent(i); pageSize = overContent.getPdfDocument().getPageSize(); overContent.beginText(); overContent.setFontAndSize(font, 9); overContent.setTextMatrix(pageSize.getWidth() - 50, pageSize.getHeight() - 70); overContent.showText("Page " + i + " of " + pages); overContent.endText(); } }
public void footer() { PdfContentByte cb = writer.getDirectContent(); cb.saveState(); Date now = new Date(); String promoTxt = OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT"); if( promoTxt == null ) { promoTxt = new String(); } String strFooter = promoTxt + " " + formatter.format(now); float textBase = document.bottom(); cb.beginText(); cb.setFontAndSize(font.getBaseFont(),FONTSIZE); Rectangle page = document.getPageSize(); float width = page.getWidth(); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, strFooter, (width/2.0f), textBase - 20, 0); strFooter = "-" + writer.getPageNumber() + "-"; cb.showTextAligned(PdfContentByte.ALIGN_CENTER, strFooter, (width/2.0f), textBase-10, 0); cb.endText(); cb.restoreState(); }
@Test public void main() throws Exception { Document document = new Document(PageSize.A4, 50, 50, 50, 50); PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream( "shading.pdf")); document.open(); PdfFunction function1 = PdfFunction.type2(writer, new float[] { 0, 1 }, null, new float[] { .929f, .357f, 1, .298f }, new float[] { .631f, .278f, 1, .027f }, 1.048f); PdfFunction function2 = PdfFunction.type2(writer, new float[] { 0, 1 }, null, new float[] { .929f, .357f, 1, .298f }, new float[] { .941f, .4f, 1, .102f }, 1.374f); PdfFunction function3 = PdfFunction.type3(writer, new float[] { 0, 1 }, null, new PdfFunction[] { function1, function2 }, new float[] { .708f }, new float[] { 1, 0, 0, 1 }); PdfShading shading = PdfShading.type3(writer, new CMYKColor(0, 0, 0, 0), new float[] { 0, 0, .096f, 0, 0, 1 }, null, function3, new boolean[] { true, true }); PdfContentByte cb = writer.getDirectContent(); cb.moveTo(316.789f, 140.311f); cb.curveTo(303.222f, 146.388f, 282.966f, 136.518f, 279.122f, 121.983f); cb.lineTo(277.322f, 120.182f); cb.curveTo(285.125f, 122.688f, 291.441f, 121.716f, 298.156f, 119.386f); cb.lineTo(336.448f, 119.386f); cb.curveTo(331.072f, 128.643f, 323.346f, 137.376f, 316.789f, 140.311f); cb.clip(); cb.newPath(); cb.saveState(); cb.concatCTM(27.7843f, 0, 0, -27.7843f, 310.2461f, 121.1521f); cb.paintShading(shading); cb.restoreState(); cb.sanityCheck(); document.close(); }
/** * Generates an Acroform with a Combobox */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(PageSize.A4); // step 2: PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("combo.pdf")); // step 3: we open the document document.open(); // step 4: PdfContentByte cb = writer.getDirectContent(); cb.moveTo(0, 0); String options[] = { "Red", "Green", "Blue" }; PdfFormField field = PdfFormField.createCombo(writer, true, options, 0); field.setWidget(new Rectangle(100, 700, 180, 720), PdfAnnotation.HIGHLIGHT_INVERT); field.setFieldName("ACombo"); field.setValueAsString("Red"); writer.addAnnotation(field); // step 5: we close the document document.close(); }
/** * * @param cb * @param foreground * @param moduleSide */ public void placeBarcode(PdfContentByte cb, Color foreground, float moduleSide) { int width = bm.getWidth(); int height = bm.getHeight(); byte[][] mt = bm.getArray(); cb.setColorFill(foreground); for (int y = 0; y < height; ++y) { byte[] line = mt[y]; for (int x = 0; x < width; ++x) { if (line[x] == 0) { cb.rectangle(x * moduleSide, (height - y - 1) * moduleSide, moduleSide, moduleSide); } } } cb.fill(); }
/** * Break a large table up into several smaller tables for memory management * purposes. * */ @Test public void main() throws Exception { // step1 Document document = new Document(PageSize.A4, 10, 10, 10, 10); // step2 PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("SplitTable.pdf")); // step3 document.open(); // step4 PdfContentByte cb = writer.getDirectContent(); PdfPTable table = new PdfPTable(10); for (int k = 1; k <= 100; ++k) { table.addCell("The number " + k); } table.setTotalWidth(800); table.writeSelectedRows(0, 5, 0, -1, 50, 650, cb); document.newPage(); table.writeSelectedRows(5, -1, 0, -1, 50, 650, cb); document.close(); // step5 document.close(); }
private void setCheckboxAppearance( PdfFormField checkboxfield, PdfContentByte canvas, float width ) { PdfAppearance[] onOff = new PdfAppearance[2]; onOff[0] = canvas.createAppearance( width + 2, width + 2 ); onOff[0].rectangle( 1, 1, width, width ); onOff[0].stroke(); onOff[1] = canvas.createAppearance( width + 2, width + 2 ); onOff[1].setRGBColorFill( 255, 128, 128 ); onOff[1].rectangle( 1, 1, width, width ); onOff[1].fillStroke(); onOff[1].moveTo( 1, 1 ); onOff[1].lineTo( width + 1, width + 1 ); onOff[1].moveTo( 1, width + 1 ); onOff[1].lineTo( width + 1, 1 ); onOff[1].stroke(); checkboxfield.setAppearance( PdfAnnotation.APPEARANCE_NORMAL, "Off", onOff[0] ); checkboxfield.setAppearance( PdfAnnotation.APPEARANCE_NORMAL, "On", onOff[1] ); }
public void footer() { PdfContentByte cb = writer.getDirectContent(); cb.saveState(); Date now = new Date(); String promoTxt = OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT"); if (promoTxt == null) { promoTxt = new String(); } String strFooter = promoTxt + " " + formatter.format(now); float textBase = document.bottom(); cb.beginText(); cb.setFontAndSize(font.getBaseFont(), FONTSIZE); Rectangle page = document.getPageSize(); float width = page.getWidth(); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, strFooter, (width / 2.0f), textBase - 20, 0); strFooter = "-" + writer.getPageNumber() + "-"; cb.showTextAligned(PdfContentByte.ALIGN_CENTER, strFooter, (width / 2.0f), textBase - 10, 0); cb.endText(); cb.restoreState(); }
public void onEndPage( PdfWriter writer, Document document ) { //Footer contains page numbers and date printed on all pages PdfContentByte cb = writer.getDirectContent(); cb.saveState(); String strFooter = promoTxt + " " + formatter.format(now); float textBase = document.bottom(); cb.beginText(); cb.setFontAndSize(font.getBaseFont(),FONTSIZE); Rectangle page = document.getPageSize(); float width = page.getWidth(); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, strFooter, (width/2.0f), textBase - 20, 0); strFooter = "-" + writer.getPageNumber() + "-"; cb.showTextAligned(PdfContentByte.ALIGN_CENTER, strFooter, (width/2.0f), textBase-10, 0); cb.endText(); cb.restoreState(); }
/** * Adds promo text, date and current page number to each page * * @param writer * @param document */ public void onEndPage(PdfWriter writer, Document document) { PdfContentByte cb = writer.getDirectContent(); cb.saveState(); float textBase = document.bottom() - getBaseOffset(); float width = document.getPageSize().getWidth(); float center = width / 2.0f; cb.beginText(); cb.setFontAndSize(getFont(), getFontSize()); cb.setTextMatrix(document.left(), textBase); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, text, center, textBase, 0); cb.endText(); cb.restoreState(); }
/** * Any work to start off printing a page of the document * m_currentPage will contain the page being printed, and * m_currentTemplatePage will contain the template page number to base this * new page on. * @throws FormPrintException Thrown if there is any form processing problems */ protected void startPage() throws FormPrintException { log.debug("startPage: Page=" + getCurrentPage()); Rectangle r = m_templateReader.getPageSize(getCurrentTemplatePage()); log.debug( "Page Size : t="+r.getTop()+",l="+r.getLeft()+",b="+r.getBottom()+",r="+r.getRight()+", rot="+r.getRotation() ); r = m_templateReader.getPageSizeWithRotation(getCurrentTemplatePage()); log.debug( "Page Size w/Rot: t="+r.getTop()+",l="+r.getLeft()+",b="+r.getBottom()+",r="+r.getRight()+", rot="+r.getRotation() ); // Get rotation quadrent 0..3 int q = (m_templateReader.getPageSizeWithRotation(getCurrentTemplatePage()).getRotation() % 360)/90; float tX = (q==2?r.getTop():0)+(q==3?r.getRight():0); float tY = (q==1?r.getTop():0)+(q==2?r.getRight():0); float sX=1f, sY=1f; double angle = -r.getRotation()*(Math.PI/180f); double transformA = sX * Math.cos(angle); double transformB = sY * Math.sin(angle); double transformC = -sX * Math.sin(angle); double transformD = sY * Math.cos(angle); double transformE = tX; double transformF = tY; m_generatedDoc.setPageSize(m_templateReader.getPageSizeWithRotation(getCurrentTemplatePage()) ); //m_generatedDoc.setPageSize(m_templateReader.getPageSize(getCurrentTemplatePage()) ); /** * try { * m_generatedDoc.newPage(); * } catch (DocumentException e) { * log.error("Error Creating New Page - " + e.getMessage() ,e); * throw new EngineProcessingException("Error Creating New Page - " + e.getMessage()); * } **/ m_generatedDoc.newPage(); PdfImportedPage page = m_writer.getImportedPage(m_templateReader, getCurrentTemplatePage() ); PdfContentByte cb = m_writer.getDirectContent(); //cb.addTemplate(page, 1f, 0, 0, 1f, 0, 0); cb.addTemplate(page, (float)transformA, (float)transformB, (float)transformC, (float)transformD, (float)transformE, (float)transformF); log.debug("Matrix = [A=" + transformA +", B=" + transformB +", C=" + transformC + ", D=" + transformD +", E=" + transformE +", F=" + transformF +" ]"); }
/** Print a java image */ private void printImage(java.awt.Image image, PdfContentByte cb, float x1, float y1, float x2, float y2, int alignment, int fitMethod, float rotate) throws BadElementException, IOException, DocumentException { if(image!=null) { // Convert to an iText Image Image img = Image.getInstance(image, null); printImage(img,cb,x1,y1,x2,y2,alignment,fitMethod,rotate); } }
/** Print an iText image */ private void printImage(Image image, PdfContentByte cb, float x1, float y1, float x2, float y2, int alignment, int fitMethod, float rotate) throws DocumentException { if(image!=null) { float boxWidth = Math.abs(x2-x1)+1; float boxHeight = Math.abs(y2-y1)+1; log.debug("Print Image (Size w="+image.getPlainWidth()+",h="+image.getPlainHeight()+") wthin BOX (w="+boxWidth+",h="+boxHeight+") FitMethod = "+fitMethod); // Clip the image based on the bounding box if(fitMethod==FIT_METHOD_CLIP) { if( (boxWidth < image.getPlainWidth()) || (boxHeight < image.getPlainHeight()) ) { // @TODO - Clip image log.warn("IMAGE CLIPPING REQUIRED, but not implemented - default to 'SCALE'..."); fitMethod=FIT_METHOD_SCALE; } } // Stretch/shrink both the X/Y to fit the bounding box if(fitMethod==FIT_METHOD_FILL) { log.debug("Scale image to fill box"); image.scaleToFit(x2-x1, y2-y1); } // Stretch/shrink preserving the aspect ratio to fit the bounding box if(fitMethod==FIT_METHOD_SCALE) { float multipler = Math.min(boxWidth / image.getPlainWidth(), boxHeight /image.getPlainHeight()); log.debug("Need to scale image by " + (Math.floor(multipler*10000)/100) + "%"); image.scalePercent(multipler*100); } log.debug("Print image at (" + x1 + "," + y1 +")"); image.setAbsolutePosition(x1,y1); image.setRotationDegrees(rotate); cb.addImage(image); //Phrase text = new Phrase(new Chunk(image, 0, 0)); //ColumnText ct = new ColumnText(cb); //ct.setSimpleColumn(text, x1, y1, x2, y2, 10, alignment); //ct.go(); } }
private void insertImage(Image img, PdfContentByte canvas, float[] imgPosition) throws Exception { com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(img.getBytes()); float fieldLx = imgPosition[1]; float fieldLy = imgPosition[2]; float fieldUx = imgPosition[3]; float fieldUy = imgPosition[4]; Rectangle rect = new Rectangle(fieldLx, fieldLy, fieldUx, fieldUy); float absPosWidth = fieldLx; float absPosHeight = fieldLy; image.scaleToFit(rect.getWidth(), rect.getHeight()); image.setAbsolutePosition(absPosWidth, absPosHeight); canvas.addImage(image, rect.getWidth(), 0, 0, rect.getHeight(), absPosWidth, absPosHeight); }
/** * @see com.lowagie.text.pdf.PdfPTableEvent#tableLayout(com.lowagie.text.pdf.PdfPTable, float[][], float[], int, int, com.lowagie.text.pdf.PdfContentByte[]) */ public void tableLayout(PdfPTable table, float[][] widths, float[] heights, int headerRows, int rowStart, PdfContentByte[] canvases) { float[] width = widths[0]; Rectangle rect = new Rectangle(width[0], heights[heights.length - 1], width[width.length - 1], heights[0]); rect.cloneNonPositionParameters(this); int bd = rect.getBorder(); rect.setBorder(Rectangle.NO_BORDER); canvases[PdfPTable.BACKGROUNDCANVAS].rectangle(rect); rect.setBorder(bd); rect.setBackgroundColor(null); canvases[PdfPTable.LINECANVAS].rectangle(rect); }
/** * @see com.lowagie.text.pdf.draw.DrawInterface#draw(com.lowagie.text.pdf.PdfContentByte, float, float, float, float, float) */ public void draw(PdfContentByte canvas, float llx, float lly, float urx, float ury, float y) { canvas.saveState(); canvas.setLineWidth(lineWidth); canvas.setLineCap(PdfContentByte.LINE_CAP_ROUND); canvas.setLineDash(0, gap, gap / 2); drawLine(canvas, llx, urx, y); canvas.restoreState(); }
public void restoreState(int index, PdfContentByte cb) { int pops; if (index < 0) pops = Math.min(-index, savedStates.size()); else pops = Math.max(savedStates.size() - index, 0); if (pops == 0) return; MetaState state = null; while (pops-- != 0) { cb.restoreState(); state = (MetaState)savedStates.pop(); } setMetaState(state); }
private void nextPage(EctConsultationFormRequestUtil reqForm) { PdfImportedPage page2 = writer.getImportedPage(reader, 2); document.newPage(); cb.addTemplate(page2, 1, 0, 0, 1, 0, 0); printClinicData(reqForm); cb.beginText(); cb.setFontAndSize(bf, FONTSIZE); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, reqForm.patientName, 110, height - 82, 0); cb.endText(); }
/** * 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(); }
/** * Draws some shapes. */ @Test public void main() throws Exception { // step 1: creation of a document-object Document document = new Document(); try { // 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( "shapes.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(); // an example of a rectangle with a diagonal in very thick lines 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(); // an example of some circles cb.setLineDash(3, 3, 0); cb.setRGBColorStrokeF(0f, 255f, 0f); cb.circle(150f, 500f, 100f); cb.stroke(); cb.setLineWidth(5f); cb.resetRGBColorStroke(); cb.circle(150f, 500f, 50f); cb.stroke(); // example with colorfill cb.setRGBColorFillF(0f, 255f, 0f); cb.moveTo(100f, 200f); cb.lineTo(200f, 250f); cb.lineTo(400f, 150f); // because we change the fill color BEFORE we stroke the triangle // the color of the triangle will be red instead of green cb.setRGBColorFillF(255f, 0f, 0f); cb.closePathFillStroke(); 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(); }
/** * Add an image using different transformation matrices. */ @Test public void main() throws Exception { Document.compress = false; // 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( "transformimage.pdf")); // step 3: we open the document document.open(); // step 4: PdfContentByte cb = writer.getDirectContent(); Image img = Image.getInstance(PdfTestBase.RESOURCES_DIR + "hitchcock.png"); cb.addImage(img, 271, -50, -30, 550, 100, 100); 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(); }
/** * Generate barcode in the form * * @param pdfStamper * @throws DocumentException */ private void generateBarcode(PdfStamper pdfStamper, String userId) throws DocumentException { // add barcode on the first page PdfContentByte cb = pdfStamper.getOverContent(BARCODE_PAGE); // barcode format 128C Barcode128 code128 = new Barcode128(); // barcode format e.g. *1502A1234567890 // asterisk - * [constant] // WebPOS Transaction - 1502 [constant] // Form Version - A [constant for MyPost 1.5] // 10-digit APCN code128.setCode(ASTERISK + WEBPOS_TRANSACTIION + MYPOST_FORM_VERSION + userId); code128.setCodeType(Barcode128.CODE128); // convert barcode into image Image code128Image = code128.createImageWithBarcode(cb, null, null); // set barcode position x pixel, y pixel code128Image.setAbsolutePosition(BARCODE_POSITION_X, BARCODE_POSITION_Y); code128Image.scalePercent(BARCODE_SCALE_PERCENTAGE); // add barcode image into PDF template cb.addImage(code128Image); }
/** * Adds an outline for every new Paragraph * * @param writer * @param document * @param position */ public void onParagraph(PdfWriter writer, Document document, float position) { n++; PdfContentByte cb = writer.getDirectContent(); PdfDestination destination = new PdfDestination(PdfDestination.FITH, position); new PdfOutline(cb.getRootOutline(), destination, "paragraph " + n); }
public void onEndPage(PdfWriter writer, Document document){ try { Rectangle page = document.getPageSize(); PdfContentByte cb = writer.getDirectContent(); BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); int pageNum = document.getPageNumber(); float width = page.getWidth(); float height = page.getHeight(); //add patient name header for every page but the first. if (pageNum > 1){ cb.beginText(); cb.setFontAndSize(bf, 8); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, handler.getPatientName(), 575, height - 30, 0); cb.endText(); } //add footer for every page cb.beginText(); cb.setFontAndSize(bf, 8); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "-"+pageNum+"-", width/2, 30, 0); cb.endText(); // add promotext as footer if it is enabled if ( OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT") != null){ cb.beginText(); cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA,BaseFont.CP1252,BaseFont.NOT_EMBEDDED), 6); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT"), width/2, 19, 0); cb.endText(); } // throw any exceptions } catch (Exception e) { throw new ExceptionConverter(e); } }
/** * Shading example. */ @Test public void main() throws Exception { Document document = new Document(PageSize.A4, 50, 50, 50, 50); PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("shading_pattern.pdf")); document.open(); PdfShading shading = PdfShading.simpleAxial(writer, 100, 100, 400, 100, Color.red, Color.cyan); PdfShadingPattern shadingPattern = new PdfShadingPattern(shading); PdfContentByte cb = writer.getDirectContent(); BaseFont bf = BaseFont.createFont(BaseFont.TIMES_BOLD, BaseFont.WINANSI, false); cb.setShadingFill(shadingPattern); cb.beginText(); cb.setTextMatrix(100, 100); cb.setFontAndSize(bf, 40); cb.showText("Look at this text!"); cb.endText(); PdfShading shadingR = PdfShading.simpleRadial(writer, 200, 500, 50, 300, 500, 100, new Color(255, 247, 148), new Color(247, 138, 107), false, false); cb.paintShading(shadingR); cb.sanityCheck(); document.close(); }
/** * Prints a square and fills half of it with a gray rectangle. * @param x * @param y * @param cb * @throws Exception */ public static void pictureBackdrop(float x, float y, PdfContentByte cb) throws Exception { cb.setColorStroke(Color.black); cb.setColorFill(Color.red); cb.rectangle(x, y, 100, 200); cb.fill(); cb.setLineWidth(2); cb.rectangle(x, y, 200, 200); cb.stroke(); }
/** * Prints 3 circles in different colors that intersect with eachother. * @param x * @param y * @param cb * @throws Exception */ public static void pictureCircles(float x, float y, PdfContentByte cb) throws Exception { PdfGState gs = new PdfGState(); gs.setBlendMode(PdfGState.BM_SOFTLIGHT); gs.setFillOpacity(0.7f); cb.setGState(gs); cb.setColorFill(Color.gray); cb.circle(x + 70, y + 70, 50); cb.fill(); cb.circle(x + 100, y + 130, 50); cb.fill(); cb.circle(x + 130, y + 70, 50); cb.fill(); }
/** * Demonstrates the Transparency functionality. */ @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 a writer PdfWriter writer = PdfWriter.getInstance(document,PdfTestBase.getOutputStream("softmask.pdf")); // step 3: we open the document document.open(); // step 4: content PdfContentByte cb = writer.getDirectContent(); String text = "text "; text += text; text += text; text += text; text += text; text += text; text += text; text += text; text += text; document.add(new Paragraph(text)); Image img = Image.getInstance(PdfTestBase.RESOURCES_DIR + "otsoe.jpg"); img.setAbsolutePosition(100, 550); byte gradient[] = new byte[256]; for (int k = 0; k < 256; ++k) { gradient[k] = (byte) k; } Image smask = Image.getInstance(256, 1, 1, 8, gradient); smask.makeMask(); img.setImageMask(smask); cb.addImage(img); cb.sanityCheck(); // step 5: we close the document document.close(); }
/** * Generate a QR code including URL on the page * * @param pdfStamper * @throws DocumentException */ private void generateQRCode(PdfStamper pdfStamper) throws DocumentException { // add barcode on the first page PdfContentByte pdfContentByte = pdfStamper.getOverContent(APPENDED_PAGE); BarcodeQRCode qrcode = new BarcodeQRCode("http://www.vendian.org/mncharity/dir3/paper_rulers/", 200, 200, null); Image qrcodeImage = qrcode.getImage(); qrcodeImage.setAbsolutePosition(360,500); qrcodeImage.scalePercent(100); pdfContentByte.addImage(qrcodeImage); }
/** * Prints 3 circles in different colors that intersect with eachother. * * @param x * @param y * @param cb * @throws Exception */ private static void pictureCircles(float x, float y, PdfContentByte cb) throws Exception { cb.setColorFill(Color.red); cb.circle(x + 70, y + 70, 50); cb.fill(); cb.setColorFill(Color.yellow); cb.circle(x + 100, y + 130, 50); cb.fill(); cb.setColorFill(Color.blue); cb.circle(x + 130, y + 70, 50); cb.fill(); }
/** * Writing vertical text. */ @Test public void main() throws Exception { Document document = new Document(PageSize.A4, 50, 50, 50, 50); texts[3] = convertCid(texts[0]); texts[4] = convertCid(texts[1]); texts[5] = convertCid(texts[2]); PdfWriter writer = PdfWriter.getInstance(document,PdfTestBase.getOutputStream("vertical.pdf")); int idx = 0; document.open(); PdfContentByte cb = writer.getDirectContent(); for (int j = 0; j < 2; ++j) { BaseFont bf = BaseFont.createFont("KozMinPro-Regular", encs[j], false); cb.setRGBColorStroke(255, 0, 0); cb.setLineWidth(0); float x = 400; float y = 700; float height = 400; float leading = 30; int maxLines = 6; for (int k = 0; k < maxLines; ++k) { cb.moveTo(x - k * leading, y); cb.lineTo(x - k * leading, y - height); } cb.rectangle(x, y, -leading * (maxLines - 1), -height); cb.stroke(); VerticalText vt = new VerticalText(cb); vt.setVerticalLayout(x, y, height, maxLines, leading); vt.addText(new Chunk(texts[idx++], new Font(bf, 20))); vt.addText(new Chunk(texts[idx++], new Font(bf, 20, 0, Color.blue))); vt.go(); vt.setAlignment(Element.ALIGN_RIGHT); vt.addText(new Chunk(texts[idx++], new Font(bf, 20, 0, Color.orange))); vt.go(); document.newPage(); } document.close(); }
/** * Generates an Acroform with a PushButton */ @Test public void main() throws Exception { Document.compress = false; // step 1: creation of a document-object Document document = new Document(PageSize.A4); // step 2: PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("pushbutton.pdf")); // step 3: we open the document document.open(); // step 4: PdfFormField pushbutton = PdfFormField.createPushButton(writer); PdfContentByte cb = writer.getDirectContent(); cb.moveTo(0, 0); PdfAppearance normal = cb.createAppearance(100, 50); normal.setColorFill(Color.GRAY); normal.rectangle(5, 5, 90, 40); normal.fill(); PdfAppearance rollover = cb.createAppearance(100, 50); rollover.setColorFill(Color.RED); rollover.rectangle(5, 5, 90, 40); rollover.fill(); PdfAppearance down = cb.createAppearance(100, 50); down.setColorFill(Color.BLUE); down.rectangle(5, 5, 90, 40); down.fill(); pushbutton.setFieldName("PushMe"); pushbutton.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, normal); pushbutton.setAppearance(PdfAnnotation.APPEARANCE_ROLLOVER, rollover); pushbutton.setAppearance(PdfAnnotation.APPEARANCE_DOWN, down); pushbutton.setWidget(new Rectangle(100, 700, 200, 750), PdfAnnotation.HIGHLIGHT_PUSH); writer.addAnnotation(pushbutton); // step 5: we close the document document.close(); }
private void printClinicData(EctConsultationFormRequestUtil reqForm){ cb.beginText(); if(IsPropertiesOn.isMultisitesEnable()) { Provider letterheadNameProvider = (reqForm.letterheadName != null ? new RxProviderData().getProvider(reqForm.letterheadName) : null); String letterheadNameParam = (letterheadNameProvider == null ? reqForm.letterheadName : letterheadNameProvider.getFirstName()+" "+letterheadNameProvider.getSurname()); cb.setFontAndSize(bf, 16); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, letterheadNameParam, 90, height - 70, 0); cb.setFontAndSize(bf, FONTSIZE); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, reqForm.letterheadAddress, 533, height - 70, 0); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, reqForm.letterheadPhone, 360, height - 82, 0); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, reqForm.letterheadFax, 471, height - 82, 0); } else { ClinicData clinic = new ClinicData(); clinic.refreshClinicData(); cb.beginText(); cb.setFontAndSize(bf, 16); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, clinic.getClinicName(), 90, height - 70, 0); cb.setFontAndSize(bf, FONTSIZE); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, clinic.getClinicAddress()+", "+clinic.getClinicCity()+", "+clinic.getClinicProvince()+", "+clinic.getClinicPostal(), 533, height - 70, 0); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, clinic.getClinicPhone(), 360, height - 82, 0); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, clinic.getClinicFax(), 471, height - 82, 0); } cb.endText(); }
/** * Demonstrates some Layer functionality. * */ @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("Layers.pdf")); writer.setPdfVersion(PdfWriter.VERSION_1_5); // step 3: writer.setViewerPreferences(PdfWriter.PageModeUseOC); document.open(); // step 4: PdfContentByte cb = writer.getDirectContent(); Phrase explanation = new Phrase("Layer grouping", new Font(Font.HELVETICA, 20, 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); 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, 0); 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(); PdfOCProperties p = writer.getOCProperties(); PdfArray order = new PdfArray(); order.add(l1.getRef()); PdfArray group = new PdfArray(); group.add(new PdfString("A group of two", PdfObject.TEXT_UNICODE)); group.add(l2.getRef()); group.add(l3.getRef()); order.add(group); PdfDictionary d = new PdfDictionary(); d.put(PdfName.ORDER, order); p.put(PdfName.D, d); // step 5: we close the document document.close(); }