List of usage examples for com.lowagie.text.pdf PdfStamper getOverContent
public PdfContentByte getOverContent(int pageNum)
PdfContentByte
to write over the page of the original document. From source file:net.sourceforge.fenixedu.util.report.ReportsUtils.java
License:Open Source License
static public byte[] stampPdfAt(byte[] originalPdf, byte[] toStampPdf, int positionX, int positionY) { try {/*from w w w.ja va 2 s . c o m*/ PdfReader originalPdfReader = new PdfReader(originalPdf); PdfReader toStampPdfReader = new PdfReader(toStampPdf); ByteArrayOutputStream stream = new ByteArrayOutputStream(); PdfStamper stamper = new PdfStamper(originalPdfReader, stream); PdfImportedPage importedPage = stamper.getImportedPage(toStampPdfReader, 1); PdfContentByte overContent = stamper.getOverContent(1); Rectangle pageSizeWithRotation = originalPdfReader.getPageSizeWithRotation(1); Rectangle pageSizeWithRotationStamper = toStampPdfReader.getPageSizeWithRotation(1); logger.info( String.format("[ %s, %s]", pageSizeWithRotation.getWidth(), pageSizeWithRotation.getHeight())); logger.info(String.format("[ %s, %s]", pageSizeWithRotationStamper.getWidth(), pageSizeWithRotationStamper.getHeight())); Image image = Image.getInstance(importedPage); overContent.addImage(image, image.getWidth(), 0f, 0f, image.getHeight(), positionX, positionY); stamper.close(); originalPdfReader.close(); toStampPdfReader.close(); return stream.toByteArray(); } catch (Exception e) { logger.error(e.getMessage(), e); throw new RuntimeException(e); } }
From source file:org.allcolor.yahp.cl.converter.CDocumentReconstructor.java
License:Open Source License
/** * construct a pdf document from pdf parts. * // w w w .j a va2 s .c o m * @param files * list containing the pdf to assemble * @param properties * converter properties * @param fout * outputstream to write the new pdf * @param base_url * base url of the document * @param producer * producer of the pdf * * @throws CConvertException * if an error occured while reconstruct. */ public static void reconstruct(final List files, final Map properties, final OutputStream fout, final String base_url, final String producer, final PageSize[] size, final List hf) throws CConvertException { OutputStream out = fout; OutputStream out2 = fout; boolean signed = false; OutputStream oldOut = null; File tmp = null; File tmp2 = null; try { tmp = File.createTempFile("yahp", "pdf"); tmp2 = File.createTempFile("yahp", "pdf"); oldOut = out; if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SIGNING))) { signed = true; out2 = new FileOutputStream(tmp2); } // end if else { out2 = oldOut; } out = new FileOutputStream(tmp); com.lowagie.text.Document document = null; PdfCopy writer = null; boolean first = true; Map mapSizeDoc = new HashMap(); int totalPage = 0; for (int i = 0; i < files.size(); i++) { final File fPDF = (File) files.get(i); final PdfReader reader = new PdfReader(fPDF.getAbsolutePath()); reader.consolidateNamedDestinations(); final int n = reader.getNumberOfPages(); if (first) { first = false; // step 1: creation of a document-object // set title/creator/author document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document writer = new PdfCopy(document, out); // use pdf version 1.5 writer.setPdfVersion(PdfWriter.VERSION_1_3); // compress the pdf writer.setFullCompression(); // check if encryption is needed if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) { final String password = (String) properties .get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD); final int securityType = CDocumentReconstructor.getSecurityFlags(properties); writer.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null, securityType); } // end if final String title = (String) properties.get(IHtmlToPdfTransformer.PDF_TITLE); if (title != null) { document.addTitle(title); } // end if else if (base_url != null) { document.addTitle(base_url); } // end else if final String creator = (String) properties.get(IHtmlToPdfTransformer.PDF_CREATOR); if (creator != null) { document.addCreator(creator); } // end if else { document.addCreator(IHtmlToPdfTransformer.VERSION); } // end else final String author = (String) properties.get(IHtmlToPdfTransformer.PDF_AUTHOR); if (author != null) { document.addAuthor(author); } // end if final String sproducer = (String) properties.get(IHtmlToPdfTransformer.PDF_PRODUCER); if (sproducer != null) { document.add(new Meta("Producer", sproducer)); } // end if else { document.add(new Meta("Producer", (IHtmlToPdfTransformer.VERSION + " - http://www.allcolor.org/YaHPConverter/ - " + producer))); } // end else // step 3: we open the document document.open(); } // end if PdfImportedPage page; for (int j = 0; j < n;) { ++j; totalPage++; mapSizeDoc.put("" + totalPage, "" + i); page = writer.getImportedPage(reader, j); writer.addPage(page); } // end for } // end for document.close(); out.flush(); out.close(); { final PdfReader reader = new PdfReader(tmp.getAbsolutePath()); ; final int n = reader.getNumberOfPages(); final PdfStamper stp = new PdfStamper(reader, out2); int i = 0; BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); final CHtmlToPdfFlyingSaucerTransformer trans = new CHtmlToPdfFlyingSaucerTransformer(); while (i < n) { i++; int indexSize = Integer.parseInt((String) mapSizeDoc.get("" + i)); final int[] dsize = size[indexSize].getSize(); final int[] dmargin = size[indexSize].getMargin(); for (final Iterator it = hf.iterator(); it.hasNext();) { final CHeaderFooter chf = (CHeaderFooter) it.next(); if (chf.getSfor().equals(CHeaderFooter.ODD_PAGES) && (i % 2 == 0)) { continue; } else if (chf.getSfor().equals(CHeaderFooter.EVEN_PAGES) && (i % 2 != 0)) { continue; } final String text = chf.getContent().replaceAll("<pagenumber>", "" + i) .replaceAll("<pagecount>", "" + n); // text over the existing page final PdfContentByte over = stp.getOverContent(i); final ByteArrayOutputStream bbout = new ByteArrayOutputStream(); if (chf.getType().equals(CHeaderFooter.HEADER)) { trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url, new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[3]), new ArrayList(), properties, bbout); } else if (chf.getType().equals(CHeaderFooter.FOOTER)) { trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url, new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[2]), new ArrayList(), properties, bbout); } final PdfReader readerHF = new PdfReader(bbout.toByteArray()); if (chf.getType().equals(CHeaderFooter.HEADER)) { over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], dsize[1] - dmargin[3]); } else if (chf.getType().equals(CHeaderFooter.FOOTER)) { over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], 0); } readerHF.close(); } } stp.close(); } try { out2.flush(); } catch (Exception ignore) { } finally { try { out2.close(); } catch (Exception ignore) { } } if (signed) { final String keypassword = (String) properties .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_PASSWORD); final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD); final String keyStorepassword = (String) properties .get(IHtmlToPdfTransformer.PDF_SIGNING_KEYSTORE_PASSWORD); final String privateKeyFile = (String) properties .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_FILE); final String reason = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_REASON); final String location = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_LOCATION); final boolean selfSigned = !"false" .equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SELF_SIGNING)); PdfReader reader = null; if (password != null) { reader = new PdfReader(tmp2.getAbsolutePath(), password.getBytes()); } // end if else { reader = new PdfReader(tmp2.getAbsolutePath()); } // end else final KeyStore ks = selfSigned ? KeyStore.getInstance(KeyStore.getDefaultType()) : KeyStore.getInstance("pkcs12"); ks.load(new FileInputStream(privateKeyFile), keyStorepassword.toCharArray()); final String alias = (String) ks.aliases().nextElement(); final PrivateKey key = (PrivateKey) ks.getKey(alias, keypassword.toCharArray()); final Certificate chain[] = ks.getCertificateChain(alias); final PdfStamper stp = PdfStamper.createSignature(reader, oldOut, '\0'); if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) { stp.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null, CDocumentReconstructor.getSecurityFlags(properties)); } // end if final PdfSignatureAppearance sap = stp.getSignatureAppearance(); if (selfSigned) { sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED); } // end if else { sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); } // end else if (reason != null) { sap.setReason(reason); } // end if if (location != null) { sap.setLocation(location); } // end if stp.close(); oldOut.flush(); } // end if } // end try catch (final Exception e) { throw new CConvertException( "ERROR: An Exception occured while reconstructing the pdf document: " + e.getMessage(), e); } // end catch finally { try { tmp.delete(); } // end try catch (final Exception ignore) { } try { tmp2.delete(); } // end try catch (final Exception ignore) { } } // end finally }
From source file:org.jpedal.examples.simpleviewer.utils.ItextFunctions.java
License:Open Source License
public void stampImage(int pageCount, PdfPageData currentPageData, final StampImageToPDFPages stampImage) { File tempFile = null;//w w w . j av a2 s . co m try { tempFile = File.createTempFile("temp", null); ObjectStore.copy(selectedFile, tempFile.getAbsolutePath()); } catch (Exception e) { return; } try { int[] pgsToEdit = stampImage.getPages(); if (pgsToEdit == null) return; File fileToTest = new File(stampImage.getImageLocation()); if (!fileToTest.exists()) { currentGUI.showMessageDialog(Messages.getMessage("PdfViewerError.ImageDoesNotExist")); return; } List pagesToEdit = new ArrayList(); for (int i = 0; i < pgsToEdit.length; i++) pagesToEdit.add(new Integer(pgsToEdit[i])); final PdfReader reader = new PdfReader(tempFile.getAbsolutePath()); int n = reader.getNumberOfPages(); PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(selectedFile)); Image img = Image.getInstance(fileToTest.getAbsolutePath()); int chosenWidthScale = stampImage.getWidthScale(); int chosenHeightScale = stampImage.getHeightScale(); img.scalePercent(chosenWidthScale, chosenHeightScale); String chosenPlacement = stampImage.getPlacement(); int chosenRotation = stampImage.getRotation(); img.setRotationDegrees(chosenRotation); String chosenHorizontalPosition = stampImage.getHorizontalPosition(); String chosenVerticalPosition = stampImage.getVerticalPosition(); float chosenHorizontalOffset = stampImage.getHorizontalOffset(); float chosenVerticalOffset = stampImage.getVerticalOffset(); for (int page = 0; page <= n; page++) { if (pagesToEdit.contains(new Integer(page))) { PdfContentByte cb; if (chosenPlacement.equals("Overlay")) cb = stamp.getOverContent(page); else cb = stamp.getUnderContent(page); int currentRotation = currentPageData.getRotation(page); Rectangle pageSize; if (currentRotation == 90 || currentRotation == 270) pageSize = reader.getPageSize(page).rotate(); else pageSize = reader.getPageSize(page); float startx, starty; if (chosenVerticalPosition.equals("From the top")) { starty = pageSize.height() - ((img.height() * (chosenHeightScale / 100)) / 2); } else if (chosenVerticalPosition.equals("Centered")) { starty = (pageSize.height() / 2) - ((img.height() * (chosenHeightScale / 100)) / 2); } else { starty = 0; } if (chosenHorizontalPosition.equals("From the left")) { startx = 0; } else if (chosenHorizontalPosition.equals("Centered")) { startx = (pageSize.width() / 2) - ((img.width() * (chosenWidthScale / 100)) / 2); } else { startx = pageSize.width() - ((img.width() * (chosenWidthScale / 100)) / 2); } img.setAbsolutePosition(startx + chosenHorizontalOffset, starty + chosenVerticalOffset); cb.addImage(img); } } stamp.close(); } catch (Exception e) { ObjectStore.copy(tempFile.getAbsolutePath(), selectedFile); e.printStackTrace(); } finally { tempFile.delete(); } }
From source file:org.jpedal.examples.simpleviewer.utils.ItextFunctions.java
License:Open Source License
public void stampText(int pageCount, PdfPageData currentPageData, final StampTextToPDFPages stampText) { File tempFile = null;//from ww w . j a v a2 s .co m try { tempFile = File.createTempFile("temp", null); ObjectStore.copy(selectedFile, tempFile.getAbsolutePath()); } catch (Exception e) { return; } try { int[] pgsToEdit = stampText.getPages(); if (pgsToEdit == null) return; List pagesToEdit = new ArrayList(); for (int i = 0; i < pgsToEdit.length; i++) pagesToEdit.add(new Integer(pgsToEdit[i])); final PdfReader reader = new PdfReader(tempFile.getAbsolutePath()); PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(selectedFile)); for (int page = 1; page <= pageCount; page++) { if (pagesToEdit.contains(new Integer(page))) { String chosenText = stampText.getText(); if (!chosenText.equals("")) { String chosenFont = stampText.getFontName(); Color chosenFontColor = stampText.getFontColor(); int chosenFontSize = stampText.getFontSize(); int chosenRotation = stampText.getRotation(); String chosenPlacement = stampText.getPlacement(); String chosenHorizontalPosition = stampText.getHorizontalPosition(); String chosenVerticalPosition = stampText.getVerticalPosition(); float chosenHorizontalOffset = stampText.getHorizontalOffset(); float chosenVerticalOffset = stampText.getVerticalOffset(); BaseFont font = BaseFont.createFont(chosenFont, BaseFont.WINANSI, false); PdfContentByte cb; if (chosenPlacement.equals("Overlay")) cb = stamp.getOverContent(page); else cb = stamp.getUnderContent(page); cb.beginText(); cb.setColorFill(chosenFontColor); cb.setFontAndSize(font, chosenFontSize); int currentRotation = currentPageData.getRotation(page); Rectangle pageSize; if (currentRotation == 90 || currentRotation == 270) pageSize = reader.getPageSize(page).rotate(); else pageSize = reader.getPageSize(page); float startx; float starty; if (chosenVerticalPosition.equals("From the top")) { starty = pageSize.height(); } else if (chosenVerticalPosition.equals("Centered")) { starty = pageSize.height() / 2; } else { starty = 0; } if (chosenHorizontalPosition.equals("From the left")) { startx = 0; } else if (chosenHorizontalPosition.equals("Centered")) { startx = pageSize.width() / 2; } else { startx = pageSize.width(); } cb.showTextAligned(Element.ALIGN_CENTER, chosenText, startx + chosenHorizontalOffset, starty + chosenVerticalOffset, chosenRotation); cb.endText(); } } } stamp.close(); } catch (Exception e) { ObjectStore.copy(tempFile.getAbsolutePath(), selectedFile); e.printStackTrace(); } finally { tempFile.delete(); } }
From source file:org.jpedal.examples.simpleviewer.utils.ItextFunctions.java
License:Open Source License
public void addHeaderFooter(int pageCount, PdfPageData currentPageData, final AddHeaderFooterToPDFPages addHeaderFooter) { File tempFile = null;/*from w ww . ja va 2s . c o m*/ try { tempFile = File.createTempFile("temp", null); ObjectStore.copy(selectedFile, tempFile.getAbsolutePath()); } catch (Exception e) { return; } try { int[] pgsToEdit = addHeaderFooter.getPages(); if (pgsToEdit == null) return; List pagesToEdit = new ArrayList(); for (int i = 0; i < pgsToEdit.length; i++) pagesToEdit.add(new Integer(pgsToEdit[i])); final PdfReader reader = new PdfReader(tempFile.getAbsolutePath()); PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(selectedFile)); String chosenFont = addHeaderFooter.getFontName(); Color chosenFontColor = addHeaderFooter.getFontColor(); int chosenFontSize = addHeaderFooter.getFontSize(); float chosenLeftRightMargin = addHeaderFooter.getLeftRightMargin(); float chosenTopBottomMargin = addHeaderFooter.getTopBottomMargin(); String text[] = new String[6]; text[0] = addHeaderFooter.getLeftHeader(); text[1] = addHeaderFooter.getCenterHeader(); text[2] = addHeaderFooter.getRightHeader(); text[3] = addHeaderFooter.getLeftFooter(); text[4] = addHeaderFooter.getCenterFooter(); text[5] = addHeaderFooter.getRightFooter(); Date date = new Date(); String shortDate = DateFormat.getDateInstance(DateFormat.SHORT).format(date); String longDate = DateFormat.getDateInstance(DateFormat.LONG).format(date); SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss a"); String time12 = formatter.format(date); formatter = new SimpleDateFormat("HH.mm.ss"); String time24 = formatter.format(date); String fileName = new File(selectedFile).getName(); BaseFont font = BaseFont.createFont(chosenFont, BaseFont.WINANSI, false); for (int page = 1; page <= pageCount; page++) { if (pagesToEdit.contains(new Integer(page))) { String[] textCopy = new String[text.length]; System.arraycopy(text, 0, textCopy, 0, text.length); for (int i = 0; i < 6; i++) { textCopy[i] = textCopy[i].replaceAll("<d>", shortDate); textCopy[i] = textCopy[i].replaceAll("<D>", longDate); textCopy[i] = textCopy[i].replaceAll("<t>", time12); textCopy[i] = textCopy[i].replaceAll("<T>", time24); textCopy[i] = textCopy[i].replaceAll("<f>", fileName); textCopy[i] = textCopy[i].replaceAll("<F>", selectedFile); textCopy[i] = textCopy[i].replaceAll("<p>", "" + page); textCopy[i] = textCopy[i].replaceAll("<P>", "" + pageCount); } PdfContentByte cb = stamp.getOverContent(page); cb.beginText(); cb.setColorFill(chosenFontColor); cb.setFontAndSize(font, chosenFontSize); Rectangle pageSize = reader.getPageSizeWithRotation(page); cb.showTextAligned(Element.ALIGN_LEFT, textCopy[0], chosenLeftRightMargin, pageSize.height() - chosenTopBottomMargin, 0); cb.showTextAligned(Element.ALIGN_CENTER, textCopy[1], pageSize.width() / 2, pageSize.height() - chosenTopBottomMargin, 0); cb.showTextAligned(Element.ALIGN_RIGHT, textCopy[2], pageSize.width() - chosenLeftRightMargin, pageSize.height() - chosenTopBottomMargin, 0); cb.showTextAligned(Element.ALIGN_LEFT, textCopy[3], chosenLeftRightMargin, chosenTopBottomMargin, 0); cb.showTextAligned(Element.ALIGN_CENTER, textCopy[4], pageSize.width() / 2, chosenTopBottomMargin, 0); cb.showTextAligned(Element.ALIGN_RIGHT, textCopy[5], pageSize.width() - chosenLeftRightMargin, chosenTopBottomMargin, 0); cb.endText(); } } stamp.close(); } catch (Exception e) { ObjectStore.copy(tempFile.getAbsolutePath(), selectedFile); e.printStackTrace(); } finally { tempFile.delete(); } }
From source file:org.jrimum.bopepo.pdf.PDFs.java
License:Apache License
/** * <p>//from w ww .j a v a 2 s .c o m * Muda um input field para uma imgem com as dimenses e possio do field. * </p> * * @param stamper * @param rect * @param image * @return rectanglePDF * @throws DocumentException * * @since 0.2 */ public static PdfRectangle changeFieldToImage(PdfStamper stamper, PdfRectangle rect, Image image) throws DocumentException { // Ajustando o tamanho da imagem de acordo com o tamanho do campo. // image.scaleToFit(rect.getWidth(), rect.getHeight()); image.scaleAbsolute(rect.getWidth(), rect.getHeight()); // A rotina abaixo tem por objetivo deixar a imagem posicionada no // centro // do field, tanto na perspectiva horizontal como na vertical. // Caso no se queira mais posicionar a imagem no centro do field, basta // efetuar a chamada a seguir: // "image.setAbsolutePosition // (rect.getLowerLeftX(),rect.getLowerLeftY());" image.setAbsolutePosition(rect.getLowerLeftX() + (rect.getWidth() - image.getScaledWidth()) / 2, rect.getLowerLeftY() + (rect.getHeight() - image.getScaledHeight()) / 2); stamper.getOverContent(rect.getPage()).addImage(image); return rect; }
From source file:org.jrimum.bopepo.pdf.PDFUtil.java
License:Apache License
/** * <p>// ww w .j av a2 s . c o m * Muda um input field para uma imgem com as dimenses e possio do field. * </p> * * @param stamper * @param rect * @param image * @return rectanglePDF * @throws DocumentException * * @since 0.2 */ public static RectanglePDF changeFieldToImage(PdfStamper stamper, RectanglePDF rect, Image image) throws DocumentException { // Ajustando o tamanho da imagem de acordo com o tamanho do campo. // image.scaleToFit(rect.getWidth(), rect.getHeight()); image.scaleAbsolute(rect.getWidth(), rect.getHeight()); // A rotina abaixo tem por objetivo deixar a imagem posicionada no // centro // do field, tanto na perspectiva horizontal como na vertical. // Caso no se queira mais posicionar a imagem no centro do field, basta // efetuar a chamada a seguir: // "image.setAbsolutePosition // (rect.getLowerLeftX(),rect.getLowerLeftY());" image.setAbsolutePosition(rect.getLowerLeftX() + (rect.getWidth() - image.getScaledWidth()) / 2, rect.getLowerLeftY() + (rect.getHeight() - image.getScaledHeight()) / 2); // cb = stamper.getUnderContent(rect.getPage()); stamper.getOverContent(rect.getPage()).addImage(image); return rect; }
From source file:org.kuali.coeus.common.impl.print.watermark.WatermarkServiceImpl.java
License:Open Source License
/** * /*from w ww . jav a2 s . c om*/ * This method for Decorating the PDF with watermark. * * @param watermarkPdfStamper - wrapper for pdf content byte and assists in decorating PDF LOg the exception if cannot open/read the file * for decoration */ private void decorateWatermark(PdfStamper watermarkPdfStamper, WatermarkBean watermarkBean) { watermarkPdfStamper.setFormFlattening(true); PdfReader pdfReader = watermarkPdfStamper.getReader(); int pageCount = pdfReader.getNumberOfPages(); int pdfPageNumber = 0; PdfContentByte pdfContents; Rectangle rectangle; while (pdfPageNumber < pageCount) { pdfPageNumber++; pdfContents = watermarkPdfStamper.getOverContent(pdfPageNumber); rectangle = pdfReader.getPageSizeWithRotation(pdfPageNumber); if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_IMAGE)) { decoratePdfWatermarkImage(pdfContents, (int) rectangle.getWidth(), (int) rectangle.getHeight(), watermarkBean); } if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_TEXT)) { decoratePdfWatermarkText(pdfContents, rectangle, watermarkBean); } watermarkPdfStamper.setFormFlattening(true); } try { watermarkPdfStamper.close(); } catch (IOException decorateWatermark) { LOG.error("Exception occured in WatermarkServiceImpl. decorateWatermark Exception: " + decorateWatermark.getMessage()); } catch (DocumentException documentException) { LOG.error("Exception occured in WatermarkServiceImpl. decorateWatermark Exception: " + documentException.getMessage()); } }
From source file:org.kuali.kfs.sys.PdfFormFillerUtil.java
License:Open Source License
/** * This method creates a Final watermark on the input Stream. * * @param templateStream/* w ww. ja va2s .c om*/ * @param finalmarkText * @return * @throws IOException * @throws DocumentException */ public static byte[] createFinalmarkOnFile(byte[] templateStream, String finalmarkText) throws IOException, DocumentException { // Create a PDF reader for the template PdfReader pdfReader = new PdfReader(templateStream); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // Create a PDF writer PdfStamper pdfStamper = new PdfStamper(pdfReader, outputStream); int n = pdfReader.getNumberOfPages(); int i = 1; PdfContentByte over; BaseFont bf; try { bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); PdfGState gstate = new PdfGState(); while (i <= n) { // Watermark under the existing page Rectangle pageSize = pdfReader.getPageSizeWithRotation(i); over = pdfStamper.getOverContent(i); over.beginText(); over.setFontAndSize(bf, 8); over.setGState(gstate); over.setColorFill(Color.BLACK); over.showTextAligned(Element.ALIGN_CENTER, finalmarkText, (pageSize.width() / 2), (pageSize.height() - 10), 0); over.endText(); i++; } pdfStamper.close(); } catch (DocumentException ex) { throw new IOException("iText error creating final watermark on PDF", ex); } catch (IOException ex) { throw new IOException("IO error creating final watermark on PDF", ex); } return outputStream.toByteArray(); }
From source file:org.kuali.kfs.sys.PdfFormFillerUtil.java
License:Open Source License
/** * This Method creates a custom watermark on the File. * * @param templateStream/*from ww w . jav a 2 s. c o m*/ * @param watermarkText * @return * @throws IOException * @throws DocumentException */ public static byte[] createWatermarkOnFile(byte[] templateStream, String watermarkText) throws IOException, DocumentException { // Create a PDF reader for the template PdfReader pdfReader = new PdfReader(templateStream); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // Create a PDF writer PdfStamper pdfStamper = new PdfStamper(pdfReader, outputStream); int n = pdfReader.getNumberOfPages(); int i = 1; PdfContentByte over; BaseFont bf; try { bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED); PdfGState gstate = new PdfGState(); gstate.setFillOpacity(0.5f); while (i <= n) { // Watermark under the existing page Rectangle pageSize = pdfReader.getPageSizeWithRotation(i); over = pdfStamper.getOverContent(i); over.beginText(); over.setFontAndSize(bf, 200); over.setGState(gstate); over.setColorFill(Color.LIGHT_GRAY); over.showTextAligned(Element.ALIGN_CENTER, watermarkText, (pageSize.width() / 2), (pageSize.height() / 2), 45); over.endText(); i++; } pdfStamper.close(); } catch (DocumentException ex) { throw new IOException("iText error creating watermark on PDF", ex); } catch (IOException ex) { throw new IOException("IO error creating watermark on PDF", ex); } return outputStream.toByteArray(); }