List of usage examples for com.itextpdf.text.pdf PdfContentByte addImage
public void addImage(final Image image) throws DocumentException
Image
to the page. From source file:EplanPrinter.PDFPrint.java
License:Open Source License
public String insertComment(String sx, String sy, String id, String deptValue, String userInit, String comment, int pageNum, int masterHeight, int masterWidth, int pinned, int customFontSize) throws DocumentException, IOException { float ratio = getRatio(masterHeight, masterWidth, pageNum); float x = Float.parseFloat(sx); float y = Float.parseFloat(sy); float[] f = commentTrans(x, y, masterHeight, masterWidth, pageNum); PdfGState gs1 = new PdfGState(); gs1.setFillOpacity(1);// ww w . java 2 s.c om if (customFontSize > 0) fontSize = customFontSize; PdfContentByte fg = pds.getOverContent(pageNum); fg.setGState(gs1); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED); float[] trans = translate(x, y, r[pageNum - 1].getHeight(), r[pageNum - 1].getWidth(), masterHeight, masterWidth, pageNum); // comment tag image (width=35pts, height=8pts) float[] scalar = scale(trans[0], trans[1], 35, 8, masterHeight, masterWidth, pageNum); /* Addition. ftorres - 7/21/2015 - Added to account for rotated pages * with the origin (0,0) not set to the bottom-left of the page. [1400] */ float coords[] = translateRotation(trans[0], trans[1], pageNum); coords = checkBounds(coords[0], coords[1], pageNum); /* Addition. ftorres - 10/20/2015 - If the comment was pinned in EPC, then * render the comment inside a comment box. */ if (pinned == 1) { insertPinnedComment(coords[0], coords[1], id + " - " + deptValue + " (" + userInit + ")", comment, pageNum, masterHeight, masterWidth); // Add the pinned comment text to page annotation -Jon Changkachith 11/24/2015 Rectangle rect = new Rectangle(0, 0, 0, 0); PdfAnnotation annotation = PdfAnnotation.createText(pds.getWriter(), rect, id + " - " + deptValue + " (" + userInit + ")", cleanupComment(comment), true, id); pds.addAnnotation(annotation, pds.getWriter().getCurrentPageNumber()); } else { Image image = Image.getInstance(commentIMGPath); image.setAbsolutePosition(coords[0] + (scalar[0] * (id.length() / 5f)), coords[1]); /* * Commented out by Jon Changkachith 12/09/2015 because it was throwing * DocumentException with the message "The image must have absolute positioning." image.scaleAbsoluteHeight(1); image.scaleAbsoluteWidth(1); */ image.scalePercent(ratio); //Added to fix DocumentException "The image must have absolute positioning." Jon Changkachith 12/09/2015 image.setAnnotation(new Annotation(id + " - " + deptValue + " (" + userInit + ")", cleanupComment(comment), 0, 0, 0, 0)); fg.addImage(image); } fg.setLineWidth(.5f * ratio); fg.setColorStroke(new BaseColor(Color.decode("0x6E2405").getRGB())); fg.setColorFill(new BaseColor(Color.decode("0x6E2405").getRGB())); float tHeight = scalar[1]; float tWidth = 0; if (id.length() > 3) { tWidth = (scalar[0] * (id.length() / 5f)); } else { tWidth = (scalar[0]); } fg.moveTo(coords[0], coords[1]); fg.lineTo(coords[0] + (10f * ratio), coords[1] - (tHeight / 2)); fg.lineTo(coords[0] + tWidth, coords[1] - (tHeight / 2)); fg.lineTo(coords[0] + tWidth, coords[1] + (tHeight / 2)); fg.lineTo(coords[0] + (10f * ratio), coords[1] + (tHeight / 2)); fg.lineTo(coords[0], coords[1]); fg.closePathFillStroke(); fg.fill(); // Comment number that goes on the comment tag image Phrase p = new Phrase(id); p.getFont().setColor(BaseColor.WHITE); p.getFont().setSize(8f * ratio); //comment number font size = 8f //p.getChunks().get(0).setAnnotation(PdfAnnotation.createText(pds.getWriter(), new Rectangle(trans[0],trans[1], trans[0]+5f, trans[1]+5f), id, comment, true, id)); float fs[] = translateRotation(f[0], f[1], pageNum); fs = checkBounds(fs[0], fs[1], pageNum); ColumnText.showTextAligned(fg, Element.ALIGN_LEFT, p, (float) (fs[0] + (9 * ratio)), (float) (fs[1] - (3 * ratio)), 0); return ""; }
From source file:es.sm2.openppm.front.utils.DocumentUtils.java
License:Open Source License
/** * /* w w w . j a va 2 s . co m*/ * @param pagActual * @param pagTotal * @param headerImg * @param footerImg * @param reader * @param stamper * @param idioma * @throws DocumentException * @throws IOException */ private static void setHeaderFooter(int pagActual, int pagTotal, Image headerImg, Image footerImg, PdfReader reader, PdfStamper stamper, ResourceBundle idioma) throws DocumentException, IOException { PdfContentByte content = stamper.getUnderContent(pagActual); content.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false), 8); headerImg.setAbsolutePosition(74f, 745f); content.addImage(headerImg); footerImg.setAbsolutePosition(75f, 20f); content.addImage(footerImg); content.beginText(); content.showTextAligned(Element.ALIGN_BOTTOM, "_____________________________________________________________________________________________________", 75f, 55f, 0f); content.showTextAligned(Element.ALIGN_BOTTOM, "2010 OPEN PPM - Projet Portfolio Management. (Open PPM)", 75f, 45f, 0f); content.showTextAligned(Element.ALIGN_BOTTOM, "www.sourceforce.net/openppm", 75f, 35f, 0f); content.showTextAligned(Element.ALIGN_BOTTOM, new ParamResourceBundle("pdf.pagination", pagActual, pagTotal).toString(idioma), 475f, 45f, 0f); content.endText(); content.stroke(); }
From source file:eyeofthetiger.utils.PDFDossardGenerator.java
public void createPdf(List<Participant> participants, OutputStream out) throws IOException, DocumentException { sortParticipants(participants);//from w ww . ja v a 2 s . c o m Document document = new Document(PageSize.A4.rotate()); float margin = CentimeterToUserSpace(marginCm); document.setMargins(margin, margin, margin, margin); PdfWriter writer = PdfWriter.getInstance(document, out); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfReader pdfBackgroundReader = null; PdfImportedPage backgroundPage = null; if (pdfBackground != null && (new File(pdfBackground)).exists() && (new File(pdfBackground)).isFile()) { pdfBackgroundReader = new PdfReader(pdfBackground); backgroundPage = writer.getImportedPage(pdfBackgroundReader, 1); } float documentTop = document.top(); float documentBottom = document.bottom(); float documentHeight = documentTop - documentBottom; float left = document.left(); float right = document.right(); float width = right - left; float height = documentTop - documentBottom; //cb.rectangle(left, documentBottom, width, documentHeight); //cb.stroke(); boolean logoLeftExist = (new File(logoLeft)).exists() && (new File(logoLeft)).isFile(); boolean logoRightExist = (new File(logoRight)).exists() && (new File(logoRight)).isFile(); float imgLeftRight = left; float imgLeftBottom = documentTop; float imgRightLeft = right; float imgRighBottom = documentTop; Image imgLeft = null; Image imgRight = null; if (exportLogos) { if (logoLeftExist) { imgLeft = Image.getInstance(logoLeft); float h = imgLeft.getHeight(); float w = imgLeft.getWidth(); float nw = width * logoLeftWidth; float nh = (h / w) * nw; imgLeft.scaleAbsolute(nw, nh); //img.scaleAbsoluteHeight(img.getScaledWidth() / xyRatio); imgLeft.setAbsolutePosition(left, documentTop - imgLeft.getScaledHeight()); //cb.addImage(img); imgLeftRight = imgLeft.getAbsoluteX() + imgLeft.getScaledWidth(); imgLeftBottom = imgLeft.getAbsoluteY(); } if (logoRightExist) { imgRight = Image.getInstance(logoRight); float h = imgRight.getHeight(); float w = imgRight.getWidth(); float nw = width * logoRightWidth; float nh = (h / w) * nw; imgRight.scaleAbsolute(nw, nh); imgRight.setAbsolutePosition(right - imgRight.getScaledWidth(), documentTop - imgRight.getScaledHeight()); //cb.addImage(imgRight); imgRightLeft = imgRight.getAbsoluteX(); imgRighBottom = imgRight.getAbsoluteY(); } } float nameHeightPercent = 0.35f; float groupHeightPercent = 0.25f; float nameTop = documentTop; float nameBottom = nameTop; if (exportName) { nameBottom = nameTop - (documentHeight * nameHeightPercent); } float groupeTop = nameBottom; float groupeBottom = nameBottom; if (exportGroup) { groupeBottom = groupeTop - (documentHeight * groupHeightPercent); } float barcodeTop = groupeBottom; float barcodeBottom = documentBottom; ColumnText columnText; for (Participant participant : participants) { if (backgroundPage != null) { //cb.addTemplate(backgroundPage, 1f, 0, 0, 1, 0, 0); //TODO cb.addTemplate(backgroundPage, 0, 0); } float nameFontSize = 65f; float groupFontSize = 45f; float renseignementFontSize = 35f; if (imgLeft != null) { cb.addImage(imgLeft); } if (imgRight != null) { cb.addImage(imgRight); } if (exportName) { columnText = new ColumnText(cb); columnText.setAlignment(Rectangle.ALIGN_CENTER); if (imgLeftRight != -1 && imgLeftBottom != -1) { float[] leftBorder = null; if (imgLeftBottom < nameBottom) { leftBorder = new float[] { imgLeftRight, nameTop, imgLeftRight, nameBottom, left, nameBottom }; } else { leftBorder = new float[] { imgLeftRight, nameTop, imgLeftRight, imgLeftBottom, left, imgLeftBottom, left, nameBottom }; } float[] rightBorder = null; if (imgRighBottom < nameBottom) { rightBorder = new float[] { imgRightLeft, nameTop, imgRightLeft, nameBottom, right, nameBottom }; } else { rightBorder = new float[] { imgRightLeft, nameTop, imgRightLeft, imgRighBottom, right, imgRighBottom, right, nameBottom }; } columnText.setColumns(leftBorder, rightBorder); } else { columnText.setSimpleColumn(left, nameTop, right, nameBottom); } //cb.rectangle(left, nameBottom, width, (nameTop - nameBottom)); //cb.stroke(); columnText.setExtraParagraphSpace(0f); columnText.setAdjustFirstLine(false); columnText.setIndent(0); String txt = participant.getNom().toUpperCase() + " " + participant.getPrenom(); float previousPos = columnText.getYLine(); columnText.setLeading(nameFontSize); columnText.setText(createCleanPhrase(txt, nameFontSize, true)); while (nameFontSize > 1 && ColumnText.hasMoreText(columnText.go(true))) { nameFontSize = nameFontSize - 0.5f; columnText.setLeading(nameFontSize); columnText.setText(createCleanPhrase(txt, nameFontSize, true)); columnText.setYLine(previousPos); } columnText.setLeading(nameFontSize); columnText.setText(createCleanPhrase(txt, nameFontSize, true)); columnText.setYLine(previousPos); columnText.go(false); } if (exportGroup) { columnText = new ColumnText(cb); columnText.setAlignment(Rectangle.ALIGN_CENTER); columnText.setSimpleColumn(document.left(), groupeTop, document.right(), groupeBottom); float groupeHeight = groupeTop - groupeBottom; //cb.rectangle(document.left(), groupeTop - groupeHeight, document.right() - document.left(), groupeHeight); //cb.stroke(); columnText.setExtraParagraphSpace(0f); columnText.setAdjustFirstLine(false); columnText.setIndent(0); columnText.setFollowingIndent(0); String txt1 = participant.getGroupe(); String txt2 = exportRenseignement ? "\n" + participant.getRenseignements() : null; float previousPos = columnText.getYLine(); columnText.setText(null); columnText.setLeading(groupFontSize); columnText.addText(createCleanPhrase(txt1, groupFontSize, true)); columnText.addText(createCleanPhrase(txt2, renseignementFontSize, false)); while (groupFontSize > 1 && ColumnText.hasMoreText(columnText.go(true))) { groupFontSize = groupFontSize - 0.5f; renseignementFontSize = renseignementFontSize - 0.5f; columnText.setText(null); columnText.setLeading(groupFontSize); columnText.addText(createCleanPhrase(txt1, groupFontSize, true)); columnText.addText(createCleanPhrase(txt2, renseignementFontSize, false)); columnText.setYLine(previousPos); } columnText.setText(null); columnText.setLeading(groupFontSize); columnText.addText(createCleanPhrase(txt1, groupFontSize, true)); columnText.addText(createCleanPhrase(txt2, renseignementFontSize, false)); columnText.setYLine(previousPos); columnText.go(false); } { columnText = new ColumnText(cb); float topMargin = 12f; columnText.setSimpleColumn(left, barcodeTop - topMargin, right, barcodeBottom); float barcodeHeight = (barcodeTop - topMargin) - barcodeBottom; //cb.rectangle(left, barcodeTop - barcodeHeight, width, barcodeHeight); //cb.stroke(); columnText.setExtraParagraphSpace(0f); columnText.setAdjustFirstLine(false); columnText.setIndent(0); float previousPos = columnText.getYLine(); columnText.setText(null); columnText.addElement(createCleanBarcode(cb, participant.getNumero(), width, barcodeHeight)); columnText.go(false); } document.newPage(); } document.close(); if (pdfBackgroundReader != null) { pdfBackgroundReader.close(); } }
From source file:gov.utah.dts.det.ccl.actions.facility.information.license.reports.LicenseCertificate.java
private static void writePdf(License license, ByteArrayOutputStream ba, HttpServletRequest request) throws DocumentException, BadElementException { SimpleDateFormat df = new SimpleDateFormat("MMMM d, yyyy"); StringBuilder sb;/*ww w.j av a 2s. c o m*/ // Retrieve the certificate template to use as watermark ServletContext context = request.getSession().getServletContext(); String templatefile = context.getRealPath("/resources") + "/LicenseCertificateTemplate.pdf"; PdfReader reader = getTemplateReader(templatefile); if (reader != null && reader.getNumberOfPages() > 0) { Phrase phrase; // Create new document using the page size of the certificate template document Document document = new Document(reader.getPageSizeWithRotation(1), 0, 0, 0, 0); PdfWriter writer = PdfWriter.getInstance(document, ba); document.open(); // Get the writer under content byte for placing of watermark PdfContentByte under = writer.getDirectContentUnder(); PdfContentByte over = writer.getDirectContent(); // Retrieve the first page of the template document and wrap as an Image to use as new document watermark PdfImportedPage page = writer.getImportedPage(reader, 1); Image img = Image.getInstance(page); // Make sure the image has an absolute page position if (!img.hasAbsoluteX() || !img.hasAbsoluteY()) { img.setAbsolutePosition(0, 0); } under.addImage(img); /* * THE FOLLOWING TWO FUNCTION CALLS DISPLAY THE PAGE MARGINS AND TEXT COLUMN BORDERS FOR DEBUGGING TEXT PLACEMENT. * UNCOMMENT EACH FUNCTION CALL TO HAVE BORDERS DISPLAYED ON THE OUTPUT DOCUMENT. THIS WILL HELP WHEN YOU NEED * TO SEE WHERE TEXT WILL BE PLACED ON THE CERTIFICATE FORM. */ // Show the page margins //showPageMarginBorders(over); // Show the text column borders //showColumnBorders(over); ColumnText ct = new ColumnText(over); ct.setLeading(fixedLeading); // Add Facility Name to column String text = license.getFacility().getName(); if (text != null) { phrase = new Phrase(text.toUpperCase(), mediumfontB); phrase.setLeading(noLeading); ct.addText(phrase); ct.addText(Chunk.NEWLINE); } // Add Facility Site to column text = license.getFacility().getSiteName(); if (text != null) { phrase = new Phrase(text.toUpperCase(), mediumfontB); phrase.setLeading(noLeading); ct.addText(phrase); ct.addText(Chunk.NEWLINE); } // Add Facility Address to column text = license.getFacility().getLocationAddress().getAddressOne(); if (text != null) { phrase = new Phrase(text.toUpperCase(), mediumfontB); phrase.setLeading(noLeading); ct.addText(phrase); ct.addText(Chunk.NEWLINE); } text = license.getFacility().getLocationAddress().getCityStateZip(); if (text != null) { phrase = new Phrase(text.toUpperCase(), mediumfontB); phrase.setLeading(noLeading); ct.addText(phrase); ct.addText(Chunk.NEWLINE); } // Write column to document ct.setAlignment(Element.ALIGN_CENTER); ct.setSimpleColumn(COLUMNS[0][0], COLUMNS[0][1], COLUMNS[0][2], COLUMNS[0][3]); ct.go(); // Add Certification Service Code to column ct = new ColumnText(over); ct.setLeading(fixedLeading); String service = ""; if (license.getSpecificServiceCode() != null && StringUtils.isNotBlank(license.getSpecificServiceCode().getValue()) && DV_TREATMENT.equalsIgnoreCase(license.getSpecificServiceCode().getValue())) { service += DOMESTIC_VIOLENCE; } if (!license.getProgramCodeIds().isEmpty()) { // redmine 25410 mentalHealthLoop: for (PickListValue pkv : license.getProgramCodeIds()) { String program = pkv.getValue(); int idx = program.indexOf(" -"); if (idx >= 0) { String code = program.substring(0, idx); if (MENTAL_HEALTH_CODES.indexOf(code + ":") >= 0) { if (service.length() > 0) { service += " / "; } service += MENTAL_HEALTH; break mentalHealthLoop; } } } substanceAbuseLoop: for (PickListValue pkv : license.getProgramCodeIds()) { String program = pkv.getValue(); int idx = program.indexOf(" -"); if (idx >= 0) { String code = program.substring(0, idx); if (SUBSTANCE_ABUSE_CODES.indexOf(code + ":") >= 0) { if (service.length() > 0) { service += " / "; } service += SUBSTANCE_ABUSE; break substanceAbuseLoop; } } } } if (StringUtils.isNotBlank(license.getServiceCodeDesc())) { if (service.length() > 0) { service += " / "; } service += license.getServiceCodeDesc(); } if (StringUtils.isNotEmpty(service)) { phrase = new Phrase(service.toUpperCase(), mediumfont); phrase.setLeading(noLeading); ct.addText(phrase); ct.addText(Chunk.NEWLINE); } // Add CLIENTS Info to column sb = new StringBuilder("FOR "); if (license.getAgeGroup() == null || license.getAgeGroup().getValue().equalsIgnoreCase("Adult & Youth")) { // Adult & Youth if (license.getAdultTotalSlots() != null) { sb.append(license.getAdultTotalSlots().toString()); } sb.append(" ADULT AND YOUTH CLIENTS"); } else if (license.getAgeGroup().getValue().equalsIgnoreCase("Adult")) { // Adult if (license.getAdultTotalSlots() != null) { // Are male or female counts specified? sb.append(license.getAdultTotalSlots().toString()); sb.append(" ADULT"); if (license.getAdultFemaleCount() != null || license.getAdultMaleCount() != null) { // Does either the male or female count equal the total slot count? if ((license.getAdultFemaleCount() != null && license.getAdultFemaleCount().equals(license.getAdultTotalSlots()))) { sb.append(" FEMALE CLIENTS"); } else if (license.getAdultMaleCount() != null && license.getAdultMaleCount().equals(license.getAdultTotalSlots())) { sb.append(" MALE CLIENTS"); } else { sb.append(" CLIENTS, "); if (license.getAdultMaleCount() != null) { sb.append(license.getAdultMaleCount().toString() + " MALE"); } if (license.getAdultFemaleCount() != null) { if (license.getAdultMaleCount() != null) { sb.append(" AND "); } sb.append(license.getAdultFemaleCount().toString() + " FEMALE"); } if (license.getFromAge() != null || license.getToAge() != null) { sb.append(","); } } } else { sb.append(" CLIENTS"); } } else { sb.append(" ADULT CLIENTS"); } } else { // Youth if (license.getYouthTotalSlots() != null) { // Are male or female counts specified? sb.append(license.getYouthTotalSlots().toString()); sb.append(" YOUTH"); if (license.getYouthFemaleCount() != null || license.getYouthMaleCount() != null) { // Does either the male or female count equal the total slot count? if ((license.getYouthFemaleCount() != null && license.getYouthFemaleCount().equals(license.getYouthTotalSlots()))) { sb.append(" FEMALE CLIENTS"); } else if (license.getYouthMaleCount() != null && license.getYouthMaleCount().equals(license.getYouthTotalSlots())) { sb.append(" MALE CLIENTS"); } else { sb.append(" CLIENTS, "); if (license.getYouthMaleCount() != null) { sb.append(license.getYouthMaleCount().toString() + " MALE"); } if (license.getYouthFemaleCount() != null) { if (license.getYouthMaleCount() != null) { sb.append(" AND "); } sb.append(license.getYouthFemaleCount().toString() + " FEMALE"); } if (license.getFromAge() != null || license.getToAge() != null) { sb.append(","); } } } else { sb.append(" CLIENTS"); } } else { sb.append(" YOUTH CLIENTS"); } } if (license.getFromAge() != null || license.getToAge() != null) { sb.append(" AGES "); if (license.getFromAge() != null) { sb.append(license.getFromAge().toString()); if (license.getToAge() != null) { sb.append(" TO " + license.getToAge().toString()); } else { sb.append(" AND OLDER"); } } else { sb.append("TO " + license.getToAge().toString()); } } phrase = new Phrase(sb.toString(), mediumfont); phrase.setLeading(noLeading); ct.addText(phrase); ct.addText(Chunk.NEWLINE); // Add Certificate Comments if (StringUtils.isNotBlank(license.getCertificateComment())) { phrase = new Phrase(license.getCertificateComment().toUpperCase(), mediumfont); phrase.setLeading(noLeading); ct.addText(phrase); } // Write column to document ct.setAlignment(Element.ALIGN_CENTER); ct.setSimpleColumn(COLUMNS[1][0], COLUMNS[1][1], COLUMNS[1][2], COLUMNS[1][3]); ct.go(); // Add Certificate Start Date if (license.getStartDate() != null) { phrase = new Phrase(df.format(license.getStartDate()), mediumfont); phrase.setLeading(noLeading); ct = new ColumnText(over); ct.setSimpleColumn(phrase, COLUMNS[2][0], COLUMNS[2][1], COLUMNS[2][2], COLUMNS[2][3], fixedLeading, Element.ALIGN_RIGHT); ct.go(); } // Add Certificate End Date if (license.getEndDate() != null) { phrase = new Phrase(df.format(license.getEndDate()), mediumfont); phrase.setLeading(noLeading); ct = new ColumnText(over); ct.setSimpleColumn(phrase, COLUMNS[3][0], COLUMNS[3][1], COLUMNS[3][2], COLUMNS[3][3], fixedLeading, Element.ALIGN_LEFT); ct.go(); } // Add License Number if (license.getLicenseNumber() != null) { phrase = new Phrase(license.getLicenseNumber().toString(), largefontB); phrase.setLeading(noLeading); ct = new ColumnText(over); ct.setSimpleColumn(phrase, COLUMNS[4][0], COLUMNS[4][1], COLUMNS[4][2], COLUMNS[4][3], numberLeading, Element.ALIGN_CENTER); ct.go(); } document.close(); } }
From source file:itext_result.Main.java
private int developScreeningSheet() { new SwingWorker<Object, Object>() { String filename;/* w ww .j a v a 2s. c om*/ @Override protected void done() { // ConsoleMsg("Printing PROFILE SHEET IN PROGRESS.. "); } public PdfPCell createBarcode(PdfWriter writer, String code) throws DocumentException, IOException { BarcodeEAN barcode = new BarcodeEAN(); barcode.setCodeType(Barcode.EAN8); barcode.setCode(code); PdfPCell cell = new PdfPCell( barcode.createImageWithBarcode(writer.getDirectContent(), BaseColor.BLACK, BaseColor.GRAY), true); cell.setPadding(10); return cell; } class ImageContent implements PdfPTableEvent { protected com.itextpdf.text.Image content; public ImageContent(com.itextpdf.text.Image content) { this.content = content; } public void tableLayout(PdfPTable table, float[][] widths, float[] heights, int headerRows, int rowStart, PdfContentByte[] canvases) { try { PdfContentByte canvas = canvases[PdfPTable.TEXTCANVAS]; float x = widths[3][1] + 10; float y = heights[3] - 10 - content.getScaledHeight(); content.setAbsolutePosition(x, y); canvas.addImage(content); } catch (DocumentException e) { throw new ExceptionConverter(e); } } } @Override protected Object doInBackground() throws Exception { // System.err.println(" Roll No Received ....." + rollno); Document doc = new Document(); try { PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream("12345" + ".pdf")); doc.open(); doc.addTitle("Recruitment PET Sheett - " + "Created By SOS : "); doc.addSubject("Confidential Report Eyes Only"); doc.addKeywords(""); doc.addAuthor("SOS"); doc.addCreator("SOS"); // A4 = 210mm x 297mm ~ 605points x 855points doc.setPageSize(PageSize.A5); doc.setMargins(15f, 15f, 15f, 15f); ///////////////////////////////////////////////////////////// int pageno = 1; for (int i = 0; i == pageno; i++) { // doc.add(imageRight); } PdfContentByte cb = writer.getDirectContent(); //DONE BarcodeEAN codeEAN = new BarcodeEAN(); codeEAN.setCodeType(Barcode.EAN8); Barcode128 code128 = new Barcode128(); code128.setCode(String.valueOf("123456")); Barcode128 code128_jacket = new Barcode128(); code128_jacket.setCode(String.valueOf("10345")); codeEAN.setCode(String.valueOf("123456")); com.itextpdf.text.Image imageEAN = code128.createImageWithBarcode(cb, null, null); // imageEAN.scalePercent(10f); //464f, 725f // imageEAN.setAbsolutePosition(474f, 662f); int i = 1; while (i <= pageno) { doc.newPage(); // cb.addImage(imageRight); // cb.addImage(imageEAN); i++; } com.itextpdf.text.Image carcode = code128_jacket.createImageWithBarcode(cb, null, null); carcode.scaleAbsolute(100f, 35f); carcode.setAbsolutePosition(500f, 600f); writer.addDirectImageSimple(carcode); // cb.addImage(carcode); com.itextpdf.text.Image carcode2 = code128.createImageWithBarcode(cb, null, null); carcode2.scaleAbsolute(100f, 35f); carcode2.setAbsolutePosition(450f, 760f); writer.addDirectImageSimple(carcode2); // cb.addImage(carcode2); Image image1 = Image.getInstance("jklogo.gif"); PdfPTable table = new PdfPTable(1); table.setWidthPercentage(99); table.addCell(image1); doc.add(table); table = new PdfPTable(4); table.setWidthPercentage(99); float[] columnWidths = { 6, 2 }; PdfPTable CandidateTable = new PdfPTable(columnWidths); Font f = new Font(Font.FontFamily.HELVETICA, 7, Font.NORMAL, GrayColor.BLACK); Font fsmall = new Font(Font.FontFamily.HELVETICA, 7, Font.NORMAL, GrayColor.BLACK); PdfPCell rollno = new PdfPCell(new Phrase("Roll No# " + String.valueOf("123456"), fsmall)); PdfPCell cname = new PdfPCell(new Phrase("Name #" + String.valueOf("John Doe"), fsmall)); // DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); // String today = formatter.format(cInfo.getDob()); PdfPCell dob = new PdfPCell(new Phrase("DOB#" + String.valueOf("12-03-1989"), fsmall)); PdfPCell fname = new PdfPCell(new Phrase("F/H Name #" + String.valueOf("Big John"), fsmall)); PdfPCell type = new PdfPCell(new Phrase("Total Time #" + String.valueOf("350.00"), fsmall)); // String scrtoday = formatter.format(cInfo.getScreeningdate()); // System.out.println("Today : " + today); PdfPCell scrdate = new PdfPCell(new Phrase("Laps #" + String.valueOf("4"), fsmall)); PdfPCell cell = new PdfPCell(new Phrase(" ", fsmall)); rollno.setBorder(com.itextpdf.text.Rectangle.NO_BORDER); cname.setBorder(com.itextpdf.text.Rectangle.NO_BORDER); rollno.setBorder(com.itextpdf.text.Rectangle.NO_BORDER); dob.setBorder(com.itextpdf.text.Rectangle.NO_BORDER); fname.setBorder(com.itextpdf.text.Rectangle.NO_BORDER); type.setBorder(com.itextpdf.text.Rectangle.NO_BORDER); scrdate.setBorder(com.itextpdf.text.Rectangle.NO_BORDER); cell.setBorder(com.itextpdf.text.Rectangle.NO_BORDER); CandidateTable.addCell(rollno); CandidateTable.addCell(cell); CandidateTable.addCell(cname); CandidateTable.addCell(cell); CandidateTable.addCell(dob); CandidateTable.addCell(cell); PdfPTable CandidateOtherTable = new PdfPTable(columnWidths); CandidateOtherTable.addCell(fname); CandidateOtherTable.addCell(cell); CandidateOtherTable.addCell(scrdate); CandidateOtherTable.addCell(cell); CandidateOtherTable.addCell(type); CandidateOtherTable.addCell(cell); PdfPCell race_start_time = new PdfPCell(new Phrase("Start Time :XX-XX-XX ", fsmall)); PdfPCell race_end_time = new PdfPCell(new Phrase("End Time :XX-XX-XX", fsmall)); PdfPCell race_total_time = new PdfPCell(new Phrase("Total Time : 350.00 ", fsmall)); race_start_time.setBorder(com.itextpdf.text.Rectangle.NO_BORDER); race_end_time.setBorder(com.itextpdf.text.Rectangle.NO_BORDER); race_total_time.setBorder(com.itextpdf.text.Rectangle.NO_BORDER); PdfPTable CandidateRaceDetails = new PdfPTable(columnWidths); CandidateRaceDetails.addCell(race_start_time); CandidateRaceDetails.addCell(cell); CandidateRaceDetails.addCell(race_end_time); CandidateRaceDetails.addCell(cell); CandidateRaceDetails.addCell(race_total_time); CandidateRaceDetails.addCell(cell); PdfPTable tablewith3cells = new PdfPTable(3); //1 St Col for Roll No Name and DOB tablewith3cells.addCell(CandidateTable); //2 nd Col for Father Name sCREEning Date Gurkha tablewith3cells.addCell(CandidateOtherTable); //3rd Col for Barcode to be Printed tablewith3cells.addCell(CandidateRaceDetails); // Setting the Width here to 101 tablewith3cells.setWidthPercentage(99); doc.add(tablewith3cells); PdfPTable userArea = new PdfPTable(1); userArea.setWidthPercentage(99); userArea.addCell(" \n \n Congratulations \n \n "); doc.add(userArea); PdfPTable footerCSBC = new PdfPTable(2); footerCSBC.setWidthPercentage(99); PdfPCell height_box = new PdfPCell(new Phrase("Height \n\n\n", f)); height_box.setBorder(com.itextpdf.text.Rectangle.BOX); PdfPCell chest_box = new PdfPCell(new Phrase("Chest \n\n\n", f)); chest_box.setBorder(com.itextpdf.text.Rectangle.BOX); PdfPCell chest_exp_box = new PdfPCell(new Phrase("Chest Exp \n\n\n", f)); chest_exp_box.setBorder(com.itextpdf.text.Rectangle.BOX); PdfPCell pushup_box = new PdfPCell(new Phrase("Pushup \n\n\n", f)); pushup_box.setBorder(com.itextpdf.text.Rectangle.BOX); //CSignatureBox.setBorder(com.itextpdf.text.Rectangle.BOX); // ASignatureBox.setBorder(com.itextpdf.text.Rectangle.BOX); footerCSBC.addCell(height_box); footerCSBC.addCell(chest_box); footerCSBC.addCell(chest_exp_box); footerCSBC.addCell(pushup_box); doc.add(footerCSBC); float[] columnWidths_ForBarcode = { 6, 3 }; PdfPTable terminalinfo = new PdfPTable(columnWidths_ForBarcode); // terminalinfo.setWidthPercentage(99); String computername = InetAddress.getLocalHost().getHostName(); System.out.println(computername); PdfPCell pcname = new PdfPCell(new Phrase("\t Jacket \n\n ", f)); String UserMatchScore = "\t Barcode\n\n"; PdfPCell score = new PdfPCell(new Phrase(UserMatchScore, f)); PdfPCell barcode = new PdfPCell(carcode2); PdfPCell jacketnumber = new PdfPCell(carcode); pcname.setBorder(com.itextpdf.text.Rectangle.NO_BORDER); score.setBorder(com.itextpdf.text.Rectangle.NO_BORDER); barcode.setBorder(com.itextpdf.text.Rectangle.NO_BORDER); jacketnumber.setBorder(com.itextpdf.text.Rectangle.NO_BORDER); terminalinfo.addCell(score); terminalinfo.addCell(pcname); terminalinfo.addCell(barcode); terminalinfo.addCell(jacketnumber); doc.add(terminalinfo); PdfPCell eula_notice = new PdfPCell(new Phrase(" ", f)); eula_notice.setBorder(com.itextpdf.text.Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_CENTER); PdfPTable eula_notice_table = new PdfPTable(1); eula_notice_table.setWidthPercentage(25); eula_notice_table.addCell(eula_notice); doc.add(eula_notice_table); } catch (Exception e) { System.err.println(e.getMessage()); // ConsoleMsg(e.getMessage()); } finally { doc.close(); doc.close(); doc.close(); } //ConsoleMsg("PDF... GENERATED"); return null; // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }.execute(); return 0; }
From source file:learn.PdfRendererBasicFragment.java
License:Apache License
public void merge(int pageNum) { try {//w w w .ja va 2 s. co m Image image = Image.getInstance(signatureByte); pdfReader = new PdfReader(path); //fix y Matrix matrix = mSignatureImage.getImageMatrix(); // Get the values of the matrix float[] values = new float[9]; matrix.getValues(values); float relativeX = (mSignatureImage.getX() - values[2]) / values[0]; float relativeY = (mSignatureImage.getY() - values[5]) / values[4]; x = relativeX; y = relativeY; if (pageNum != -1) { y = pdfReader.getCropBox(pageNum).getHeight() - y; y -= mSign.getHeight(); } PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(newP)); if (pageNum == -1) { y = pdfReader.getCropBox(1).getHeight() - y; y -= mSign.getHeight(); for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) { //put content under PdfContentByte content;// = pdfStamper.getUnderContent(i); // image.setAbsolutePosition(x, y); // content.addImage(image); //put content over content = pdfStamper.getOverContent(i); image.setAbsolutePosition(x, y); content.addImage(image); //Text over the existing page /*BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); content.beginText(); content.setFontAndSize(bf, 18); content.showTextAligned(PdfContentByte.ALIGN_LEFT, "Page No: " + i, 430, 15, 0); content.endText();*/ } } else { PdfContentByte content = pdfStamper.getOverContent(pageNum); image.setAbsolutePosition(x, y); content.addImage(image); } pdfStamper.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:managedbeans.descargas.PDFConversionDemo.java
public static void main(String[] args) { try {//from w w w .ja va 2 s. co m //Read file using PdfReader PdfReader pdfReader = new PdfReader("HelloWorld.pdf"); //Modify file using PdfReader PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream("HelloWorld-modified.pdf")); Image image = Image.getInstance("temp.png"); image.scaleAbsolute(100, 50); image.setAbsolutePosition(100f, 700f); for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) { PdfContentByte content = pdfStamper.getUnderContent(i); content.addImage(image); } pdfStamper.close(); } catch (IOException | DocumentException e) { logger.warn("failed to ...." + e); } }
From source file:net.FilterLogic.imaging.ToPDF.java
License:Apache License
private void writeMultiPagePDF(String fileName) throws Exception { float STD_WIDTH = 620; float STD_HEIGHT = 775; float newWidth = 0; float newHeight = 0; float xPos = 0; float yPos = 0; boolean scaleImage = true; boolean pdfAutoOrientation = true; boolean autoCenter = false; boolean portrait = true; BufferedImage img = null;/*from w ww.ja v a 2 s .c o m*/ Document pdf; PdfWriter writer; try { // scale image String si = this.documentProperties.getProperty(KEY_SCALE_TO_FIT, KEY_SCALE_TO_FIT_DEFAULT); scaleImage = Boolean.parseBoolean(si); // auto-orientation String ao = this.documentProperties.getProperty(KEY_AUTO_ORIENTATION, KEY_AUTO_ORIENTATION_DEFAULT); pdfAutoOrientation = Boolean.parseBoolean(ao); // auto-center String ac = this.documentProperties.getProperty(KEY_AUTO_CENTER, KEY_AUTO_CENTER_DEFAULT); autoCenter = Boolean.parseBoolean(ac); if (document.size() > 0) img = document.get(0); if (img != null) { // if dpi set, calculate new width/height if (horizontalDPI > 0 && verticalDPI > 0) { float xd = (float) horizontalDPI / 100; float yd = (float) verticalDPI / 100; newWidth = img.getWidth() / xd; newHeight = img.getHeight() / yd; } else { newWidth = img.getWidth(); newHeight = img.getHeight(); } // if image width or height changed, scale if (newWidth != img.getWidth() || newHeight != img.getHeight()) scaleImage = true; // if auto orientation, set portrait or landscape if (pdfAutoOrientation) { if (newWidth >= newHeight) { pdf = new Document(PageSize.LETTER.rotate()); portrait = false; } else { pdf = new Document(PageSize.LETTER); portrait = true; } } else { // else, always portrait pdf = new Document(PageSize.LETTER); portrait = true; } writer = PdfWriter.getInstance(pdf, new FileOutputStream(fileName)); writer.setFullCompression(); pdf.open(); // set document props setDocumentProperties(pdf); int t = 0; float pdfPageWidth = pdf.getPageSize().getWidth(); float pdfPageHeight = pdf.getPageSize().getHeight(); // if new image larger than standard size, override and enable image scaling if (newWidth > pdfPageWidth || newHeight > pdfPageHeight) { scaleImage = true; if (newWidth > pdfPageWidth) newWidth = pdfPageWidth; if (newHeight > pdfPageHeight) newHeight = pdfPageHeight; } // break out each page to single file while (t < totalPages) { PdfContentByte cb = writer.getDirectContent(); com.itextpdf.text.Image pdfImage; if (img != null) { pdfImage = com.itextpdf.text.Image.getInstance(img, null); // calculate center if (autoCenter) { if (portrait) { xPos = (pdfPageWidth - newWidth) / 2; yPos = (pdfPageHeight - newHeight) / 2; } else { //xPos = ((pdfPageHeight * (float)1.60) - newWidth) / 2; xPos = (pdfPageHeight - newWidth) / 2; yPos = (pdfPageWidth - newHeight) / 2; } } else { // if not scaling, set image to top left if (!scaleImage) { xPos = 0; // calculate top left corner yPos = pdfPageWidth - newHeight; } else { xPos = 0; yPos = 0; } } // check if x and y pos >=0 if (xPos < 0) xPos = 0; if (yPos < 0) yPos = 0; if (scaleImage) { if (!portrait) { pdfImage.scaleToFit(newHeight, newWidth); } else { pdfImage.scaleToFit(newWidth, newHeight); } // check is scaled height/width match new width/height // if not, recalculate center if autcenter enabled. if (newWidth != pdfImage.getScaledWidth() || newHeight != pdfImage.getScaledHeight()) { newWidth = pdfImage.getScaledWidth(); newHeight = pdfImage.getScaledHeight(); // calculate center if (autoCenter) { xPos = (pdfPageWidth - newWidth) / 2; yPos = (pdfPageHeight - newHeight) / 2; // check if x and y pos >=0 if (xPos < 0) xPos = 0; if (yPos < 0) yPos = 0; } } pdfImage.setAbsolutePosition(xPos, yPos); } else { pdfImage.setAbsolutePosition(xPos, yPos); } cb.addImage(pdfImage); // inc counter ++t; if (t < totalPages) { img = document.get(t); // if dpi set, calculate new width/height if (horizontalDPI > 0 && verticalDPI > 0) { float xd = (float) horizontalDPI / 100; float yd = (float) verticalDPI / 100; newWidth = img.getWidth() / xd; newHeight = img.getHeight() / yd; } else { newWidth = img.getWidth(); newHeight = img.getHeight(); } // if auto orientation, set portrait or landscape if (pdfAutoOrientation) { if (newWidth >= newHeight) { pdf.setPageSize(PageSize.LETTER.rotate()); portrait = false; } else { pdf.setPageSize(PageSize.LETTER); portrait = true; } } else { // else, always portrait pdf.setPageSize(PageSize.LETTER); portrait = true; } // create new page. must happen after setting page orientation pdf.newPage(); writer.newPage(); // get new pages width/height pdfPageWidth = pdf.getPageSize().getWidth(); pdfPageHeight = pdf.getPageSize().getHeight(); // set width/height to something normal if (newWidth > pdfPageWidth) newWidth = pdfPageWidth; if (newHeight > pdfPageHeight) newHeight = pdfPageHeight; } } } pdf.close(); // add file name to list fileNames = new ArrayList<String>(); fileNames.add(fileName); } } catch (Exception e) { throw new Exception(e); } }
From source file:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFWatermarkActionExecuter.java
License:Apache License
/** * Applies an image watermark/* w w w .j a v a2 s. c om*/ * * @param reader * @param writer * @param options * @throws Exception */ private void imageAction(Action ruleAction, NodeRef actionedUponNodeRef, NodeRef watermarkNodeRef, ContentReader actionedUponContentReader, ContentReader watermarkContentReader, Map<String, Object> options) { PdfStamper stamp = null; File tempDir = null; ContentWriter writer = null; try { // get a temp file to stash the watermarked PDF in before moving to // repo File alfTempDir = TempFileProvider.getTempDir(); tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId()); tempDir.mkdir(); File file = new File(tempDir, serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName()); // get the PDF input stream and create a reader for iText PdfReader reader = new PdfReader(actionedUponContentReader.getContentInputStream()); stamp = new PdfStamper(reader, new FileOutputStream(file)); PdfContentByte pcb; // get a com.itextpdf.text.Image object via java.imageio.ImageIO Image img = Image.getInstance(ImageIO.read(watermarkContentReader.getContentInputStream()), null); // get the PDF pages and position String pages = (String) options.get(PARAM_PAGE); String position = (String) options.get(PARAM_POSITION); String depth = (String) options.get(PARAM_WATERMARK_DEPTH); // image requires absolute positioning or an exception will be // thrown // set image position according to parameter. Use // PdfReader.getPageSizeWithRotation // to get the canvas size for alignment. img.setAbsolutePosition(100f, 100f); // stamp each page int numpages = reader.getNumberOfPages(); for (int i = 1; i <= numpages; i++) { Rectangle r = reader.getPageSizeWithRotation(i); // set stamp position if (position.equals(POSITION_BOTTOMLEFT)) { img.setAbsolutePosition(0, 0); } else if (position.equals(POSITION_BOTTOMRIGHT)) { img.setAbsolutePosition(r.getWidth() - img.getWidth(), 0); } else if (position.equals(POSITION_TOPLEFT)) { img.setAbsolutePosition(0, r.getHeight() - img.getHeight()); } else if (position.equals(POSITION_TOPRIGHT)) { img.setAbsolutePosition(r.getWidth() - img.getWidth(), r.getHeight() - img.getHeight()); } else if (position.equals(POSITION_CENTER)) { img.setAbsolutePosition(getCenterX(r, img), getCenterY(r, img)); } // if this is an under-text stamp, use getUnderContent. // if this is an over-text stamp, usse getOverContent. if (depth.equals(DEPTH_OVER)) { pcb = stamp.getOverContent(i); } else { pcb = stamp.getUnderContent(i); } // only apply stamp to requested pages if (checkPage(pages, i, numpages)) { pcb.addImage(img); } } stamp.close(); // Get a writer and prep it for putting it back into the repo //can't use BasePDFActionExecuter.getWriter here need the nodeRef of the destination NodeRef destinationNode = createDestinationNode(file.getName(), (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER), actionedUponNodeRef); writer = serviceRegistry.getContentService().getWriter(destinationNode, ContentModel.PROP_CONTENT, true); writer.setEncoding(actionedUponContentReader.getEncoding()); writer.setMimetype(FILE_MIMETYPE); // Put it in the repo writer.putContent(file); // delete the temp file file.delete(); } catch (IOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (DocumentException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } finally { if (tempDir != null) { try { tempDir.delete(); } catch (Exception ex) { throw new AlfrescoRuntimeException(ex.getMessage(), ex); } } if (stamp != null) { try { stamp.close(); } catch (Exception ex) { throw new AlfrescoRuntimeException(ex.getMessage(), ex); } } } }
From source file:org.durel.mydooble.ImageItem.java
License:Open Source License
@Override public void toPDF(PDF out, int i) { super.toPDF(out, i); try {/*from w w w . j ava 2 s .com*/ Image img = Image.getInstance(image); img.setDpi(288, 288); img.setInterpolation(true); float ih = (float) (img.getHeight()); float iw = (float) (img.getWidth()); if (ih > h || iw > w) { float xratio = iw / w; float yratio = ih / h; float ratio = Math.max(xratio, yratio); log.info("ih: " + ih + " - iw: " + iw + " - xratio: " + xratio + " - yratio: " + yratio + " - ratio: " + ratio + " --> " + (int) (iw / ratio) + "x" + (int) (ih / ratio)); img.scalePercent(100 / ratio); } PdfContentByte cb = out.writer.getDirectContent(); float x = bx + (c * (w + m)) + m; float y = by + (r * (h + m)) + m; img.setAbsolutePosition(x, y); cb.addImage(img); } catch (DocumentException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }