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:org.lucee.extension.pdf.tag.PDF.java
License:Open Source License
private void doActionAddHeaderFooter(boolean isHeader) throws PageException, IOException, DocumentException { required("pdf", "write", "source", source); // required("pdf", "write", "destination", destination); /*//from www . j a v a2 s .c o m * optinal - pages */ /* * isBase64 = "yes|no" showonprint = "yes|no"> opacity = "header opacity" image = "image file name to be used as the header" * */ PDFStruct doc = toPDFDocument(source, password, null); PdfReader reader = doc.getPdfReader(); BIF bif = null; if (NUMBERFORMAT_NUMERIC != numberformat) { ClassUtil classUtil = engine.getClassUtil(); try { bif = classUtil.loadBIF(pageContext, "lucee.runtime.functions.displayFormatting.NumberFormat"); } catch (Exception e) { e.printStackTrace(); throw engine.getCastUtil().toPageException(e); } } // output stream boolean destIsSource = destination != null && doc.getResource() != null && destination.equals(doc.getResource()); OutputStream os = null; if (!Util.isEmpty(name) || destIsSource) { os = new ByteArrayOutputStream(); } else if (destination != null) { os = destination.getOutputStream(); } PdfStamper stamper = null; try { if (destination != null && destination.exists() && !overwrite) throw engine.getExceptionUtil() .createApplicationException("destination file [" + destination + "] already exists"); int len = reader.getNumberOfPages(); Set<Integer> pageSet = PDFUtil.parsePageDefinition(pages, len); stamper = new PdfStamper(reader, destination.getOutputStream()); if (font == null) font = getDefaultFont(); // , new Font(FontFamily.HELVETICA, 14) for (int p = 1; p <= len; p++) { if (pageSet != null && !pageSet.contains(p)) continue; Phrase header = text(text, p, len, numberformat, bif, font); // vertical orientation float y; if (isHeader) { y = reader.getPageSize(p).getTop(header.getFont().getCalculatedSize() + (topmargin - 3)); } else { y = reader.getPageSize(p).getBottom((bottommargin + 2)); /* * System.out.println("y:"+y); System.out.println("bottom:"+reader.getPageSize(p).getBottom()); System.out.println("margin:"+bottommargin); * System.out.println("font:"+header.getFont().getSize()); System.out.println("CalculatedStyle:"+header.getFont().getCalculatedStyle()); * System.out.println("CalculatedSize:"+header.getFont().getCalculatedSize()); */ } // float yh = reader.getPageSize(p).getTop(topmargin); // float yf = reader.getPageSize(p).getBottom(bottommargin); System.out.println("++++++++++++"); System.out.println(y); System.out.println(reader.getPageSize(p).getTop()); // horizontal orientation float x = reader.getPageSize(p).getWidth() / 2; if (Element.ALIGN_LEFT == align) { x = leftmargin; } else if (Element.ALIGN_RIGHT == align) { x = reader.getPageSize(p).getWidth() - rightmargin; } else { x = reader.getPageSize(p).getWidth() / 2; } ColumnText.showTextAligned(stamper.getOverContent(p), align, header, x, y, 0); } } finally { try { if (stamper != null) stamper.close(); } catch (IOException ioe) { } ; Util.closeEL(os); if (os instanceof ByteArrayOutputStream) { if (destination != null) engine.getIOUtil().copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()), destination, true);// MUST overwrite if (!Util.isEmpty(name)) { pageContext.setVariable(name, new PDFStruct(((ByteArrayOutputStream) os).toByteArray(), password)); } } } // PdfReader pr = doc.getPdfReader(); // output /* * boolean destIsSource = doc.getResource()!=null && destination.equals(doc.getResource()); * * OutputStream os=null; if(destIsSource){ os=new ByteArrayOutputStream(); } else if(destination!=null) { os=destination.getOutputStream(); } * * try { PDFUtil.concat(new PDFStruct[]{doc}, os, true, true, true,version); } finally { Util.closeEL(os); if(os instanceof ByteArrayOutputStream) { * if(destination!=null)engine.getIOUtil().copy(new ByteArrayInputStream(((ByteArrayOutputStream)os).toByteArray()), destination,true);// MUST overwrite * } } */ }
From source file:org.lucee.extension.pdf.tag.PDF.java
License:Open Source License
private void doActionAddWatermark() throws PageException, IOException, DocumentException { required("pdf", "addWatermark", "source", source); if (copyFrom == null && image == null) throw engine.getExceptionUtil().createApplicationException( "at least one of the following attributes must be defined " + "[copyFrom,image]"); if (destination != null && destination.exists() && !overwrite) throw engine.getExceptionUtil() .createApplicationException("destination file [" + destination + "] already exists"); // image//from www .j av a2s .co m Image img = null; if (image != null) { // TODO lucee.runtime.img.Image ri = lucee.runtime.img.Image.createImage(pageContext,image,false,false,true,null); // TODO img=Image.getInstance(ri.getBufferedImage(),null,false); } // copy From else { byte[] barr; try { Resource res = copyFrom instanceof String ? engine.getResourceUtil().toResourceExisting(pageContext, (String) copyFrom) : engine.getCastUtil().toResource(copyFrom); barr = PDFUtil.toBytes(res); } catch (PageException ee) { barr = engine.getCastUtil().toBinary(copyFrom); } img = Image.getInstance(PDFUtil.toImage(barr, 1), null, false); } // position float x = UNDEFINED, y = UNDEFINED; if (!Util.isEmpty(position)) { int index = position.indexOf(','); if (index == -1) throw engine.getExceptionUtil() .createApplicationException("attribute [position] has an invalid value [" + position + "]," + "value should follow one of the following pattern [40,50], [40,] or [,50]"); String strX = position.substring(0, index).trim(); String strY = position.substring(index + 1).trim(); if (!Util.isEmpty(strX)) x = engine.getCastUtil().toIntValue(strX); if (!Util.isEmpty(strY)) y = engine.getCastUtil().toIntValue(strY); } PDFStruct doc = toPDFDocument(source, password, null); doc.setPages(pages); PdfReader reader = doc.getPdfReader(); reader.consolidateNamedDestinations(); java.util.List bookmarks = SimpleBookmark.getBookmark(reader); ArrayList master = new ArrayList(); if (bookmarks != null) master.addAll(bookmarks); // output boolean destIsSource = destination != null && doc.getResource() != null && destination.equals(doc.getResource()); OutputStream os = null; if (!Util.isEmpty(name) || destIsSource) { os = new ByteArrayOutputStream(); } else if (destination != null) { os = destination.getOutputStream(); } try { int len = reader.getNumberOfPages(); PdfStamper stamp = new PdfStamper(reader, os); if (len > 0) { if (x == UNDEFINED || y == UNDEFINED) { PdfImportedPage first = stamp.getImportedPage(reader, 1); if (y == UNDEFINED) y = (first.getHeight() - img.getHeight()) / 2; if (x == UNDEFINED) x = (first.getWidth() - img.getWidth()) / 2; } img.setAbsolutePosition(x, y); // img.setAlignment(Image.ALIGN_JUSTIFIED); ration geht nicht anhand mitte } // rotation if (rotation != 0) { img.setRotationDegrees(rotation); } Set _pages = doc.getPages(); for (int i = 1; i <= len; i++) { if (_pages != null && !_pages.contains(Integer.valueOf(i))) continue; PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i); PdfGState gs1 = new PdfGState(); // print.out("op:"+opacity); gs1.setFillOpacity(opacity); // gs1.setStrokeOpacity(opacity); cb.setGState(gs1); cb.addImage(img); } if (bookmarks != null) stamp.setOutlines(master); stamp.close(); } finally { Util.closeEL(os); if (os instanceof ByteArrayOutputStream) { if (destination != null) engine.getIOUtil().copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()), destination, true);// MUST overwrite if (!Util.isEmpty(name)) { pageContext.setVariable(name, new PDFStruct(((ByteArrayOutputStream) os).toByteArray(), password)); } } } }
From source file:org.lucee.extension.pdf.tag.PDF.java
License:Open Source License
private void doActionRemoveWatermark() throws PageException, IOException, DocumentException { required("pdf", "removeWatermark", "source", source); if (destination != null && destination.exists() && !overwrite) throw engine.getExceptionUtil() .createApplicationException("destination file [" + destination + "] already exists"); BufferedImage bi = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); g.setBackground(Color.BLACK); g.clearRect(0, 0, 1, 1);// www .j a v a2 s .c o m Image img = Image.getInstance(bi, null, false); img.setAbsolutePosition(1, 1); PDFStruct doc = toPDFDocument(source, password, null); doc.setPages(pages); PdfReader reader = doc.getPdfReader(); boolean destIsSource = destination != null && doc.getResource() != null && destination.equals(doc.getResource()); java.util.List bookmarks = SimpleBookmark.getBookmark(reader); ArrayList master = new ArrayList(); if (bookmarks != null) master.addAll(bookmarks); // output OutputStream os = null; if (!Util.isEmpty(name) || destIsSource) { os = new ByteArrayOutputStream(); } else if (destination != null) { os = destination.getOutputStream(); } try { int len = reader.getNumberOfPages(); PdfStamper stamp = new PdfStamper(reader, os); Set _pages = doc.getPages(); for (int i = 1; i <= len; i++) { if (_pages != null && !_pages.contains(Integer.valueOf(i))) continue; PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i); PdfGState gs1 = new PdfGState(); gs1.setFillOpacity(0); cb.setGState(gs1); cb.addImage(img); } if (bookmarks != null) stamp.setOutlines(master); stamp.close(); } finally { Util.closeEL(os); if (os instanceof ByteArrayOutputStream) { if (destination != null) engine.getIOUtil().copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()), destination, true);// MUST overwrite if (!Util.isEmpty(name)) { pageContext.setVariable(name, new PDFStruct(((ByteArrayOutputStream) os).toByteArray(), password)); } } } }
From source file:org.meveo.admin.action.billing.BillingAccountBean.java
License:Open Source License
public void generatePDF(long invoiceId) { Invoice invoice = invoiceService.findById(invoiceId); byte[] invoicePdf = invoice.getPdf(); FacesContext context = FacesContext.getCurrentInstance(); String invoiceFilename = null; BillingRun billingRun = invoice.getBillingRun(); invoiceFilename = invoice.getInvoiceNumber() + ".pdf"; if (billingRun != null && billingRun.getStatus() != BillingRunStatusEnum.VALIDATED) { invoiceFilename = "unvalidated-invoice.pdf"; }//ww w . j a v a2 s . c om HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse(); response.setContentType("application/pdf"); // fill in response.setHeader("Content-disposition", "attachment; filename=" + invoiceFilename); try { OutputStream os = response.getOutputStream(); Document document = new Document(PageSize.A4); if (billingRun != null && invoice.getBillingRun().getStatus() != BillingRunStatusEnum.VALIDATED) { // Add watemark image PdfReader reader = new PdfReader(invoicePdf); int n = reader.getNumberOfPages(); PdfStamper stamp = new PdfStamper(reader, os); PdfContentByte over = null; BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); PdfGState gs = new PdfGState(); gs.setFillOpacity(0.5f); int i = 1; while (i <= n) { over = stamp.getOverContent(i); over.setGState(gs); over.beginText(); System.out.println("top=" + document.top() + ",bottom=" + document.bottom()); over.setTextMatrix(document.top(), document.bottom()); over.setFontAndSize(bf, 150); over.setColorFill(Color.GRAY); over.showTextAligned(Element.ALIGN_CENTER, "TEST", document.getPageSize().getWidth() / 2, document.getPageSize().getHeight() / 2, 45); over.endText(); i++; } stamp.close(); } else { os.write(invoicePdf); // fill in PDF with bytes } // contentType os.flush(); os.close(); context.responseComplete(); } catch (IOException e) { log.error("failed to generate PDF ", e); } catch (DocumentException e) { log.error("error in generation PDF ", e); } }
From source file:org.openconcerto.erp.core.finance.accounting.report.PDFImageInsertor.java
License:Open Source License
public void insert(File pdf, Image img, int page, boolean under) throws Exception { PdfReader reader;/*from ww w . ja va2 s. c o m*/ reader = new PdfReader(new FileInputStream(pdf)); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(pdf)); // img.setAbsolutePosition(20, 40); // int total = reader.getNumberOfPages() + 1; PdfContentByte content; if (under) { content = stamper.getUnderContent(page); } else { content = stamper.getOverContent(page); } content.addImage(img); stamper.close(); }
From source file:org.orbeon.oxf.processor.pdf.PDFTemplateProcessor.java
License:Open Source License
protected void readInput(PipelineContext pipelineContext, ProcessorInput input, Config config, OutputStream outputStream) { final org.dom4j.Document configDocument = readCacheInputAsDOM4J(pipelineContext, "model");// TODO: after all, should we use "config"? final org.dom4j.Document instanceDocument = readInputAsDOM4J(pipelineContext, input); final Configuration configuration = XPathCache.getGlobalConfiguration(); final DocumentInfo configDocumentInfo = new DocumentWrapper(configDocument, null, configuration); final DocumentInfo instanceDocumentInfo = new DocumentWrapper(instanceDocument, null, configuration); try {// w w w .j av a 2s .c o m // Get reader final String templateHref = XPathCache.evaluateAsString(configDocumentInfo, "/*/template/@href", null, null, functionLibrary, null, null, null);//TODO: LocationData // Create PDF reader final PdfReader reader; { final String inputName = ProcessorImpl.getProcessorInputSchemeInputName(templateHref); if (inputName != null) { // Read the input final ByteArrayOutputStream os = new ByteArrayOutputStream(); readInputAsSAX(pipelineContext, inputName, new BinaryTextXMLReceiver(null, os, true, false, null, false, false, null, false)); // Create the reader reader = new PdfReader(os.toByteArray()); } else { // Read and create the reader reader = new PdfReader(URLFactory.createURL(templateHref)); } } // Get total number of pages final int pageCount = reader.getNumberOfPages(); // Get size of first page final Rectangle pageSize = reader.getPageSize(1); final float width = pageSize.getWidth(); final float height = pageSize.getHeight(); final String showGrid = XPathCache.evaluateAsString(configDocumentInfo, "/*/template/@show-grid", null, null, functionLibrary, null, null, null);//TODO: LocationData final PdfStamper stamper = new PdfStamper(reader, outputStream); stamper.setFormFlattening(true); for (int currentPage = 1; currentPage <= pageCount; currentPage++) { final PdfContentByte contentByte = stamper.getOverContent(currentPage); // Handle root group final GroupContext initialGroupContext = new GroupContext(contentByte, stamper.getAcroFields(), height, currentPage, Collections.singletonList((Item) instanceDocumentInfo), 1, 0, 0, "Courier", 14, 15.9f); handleGroup(pipelineContext, initialGroupContext, Dom4jUtils.elements(configDocument.getRootElement()), functionLibrary, reader); // Handle preview grid (NOTE: This can be heavy in memory.) if ("true".equalsIgnoreCase(showGrid)) { final float topPosition = 10f; final BaseFont baseFont2 = BaseFont.createFont("Courier", BaseFont.CP1252, BaseFont.NOT_EMBEDDED); contentByte.beginText(); { // 20-pixel lines and side legends contentByte.setFontAndSize(baseFont2, (float) 7); for (int w = 0; w <= width; w += 20) { for (int h = 0; h <= height; h += 2) contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h, 0); } for (int h = 0; h <= height; h += 20) { for (int w = 0; w <= width; w += 2) contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h, 0); } for (int w = 0; w <= width; w += 20) { contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + w, (float) w, height - topPosition, 0); contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + w, (float) w, topPosition, 0); } for (int h = 0; h <= height; h += 20) { contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + h, (float) 5, height - h, 0); contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + h, width - (float) 5, height - h, 0); } // 10-pixel lines contentByte.setFontAndSize(baseFont2, (float) 3); for (int w = 10; w <= width; w += 10) { for (int h = 0; h <= height; h += 2) contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h, 0); } for (int h = 10; h <= height; h += 10) { for (int w = 0; w <= width; w += 2) contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h, 0); } } contentByte.endText(); } } // Close the document // document.close(); stamper.close(); } catch (Exception e) { throw new OXFException(e); } }
From source file:org.oscarehr.common.printing.HtmlToPdfServlet.java
License:Open Source License
public static byte[] stamp(byte[] content) throws Exception { PdfReader reader = null;//from www. j a v a 2 s. c om ByteArrayOutputStream os = null; PdfStamper stamper = null; try { reader = new PdfReader(content); os = new ByteArrayOutputStream(content.length); stamper = new PdfStamper(reader, os); for (int i = 1; i <= reader.getNumberOfPages(); i++) { PdfContentByte over = stamper.getOverContent(i); BaseFont font = FontSettings.HELVETICA_6PT.createFont(); over.setFontAndSize(font, 10); float center = reader.getPageSize(i).getWidth() / 2.0f; // TODO Consider refactoring this into is own class printText(over, "Page " + i + " of " + reader.getNumberOfPages(), center, 35); printText(over, OscarProperties.getConfidentialityStatement(), center, 25); } // this is ugly, but there is no flush method for readers in itext.... stamper.close(); reader.close(); os.flush(); return os.toByteArray(); } finally { if (os != null) IOUtils.closeQuietly(os); } }
From source file:org.saiku.web.rest.resources.ExporterResource.java
License:Apache License
/** * Export chart to a file.//w w w. ja va2s. co m * @summary Export Chart. * @param type The export type (png, svg, jpeg) * @param svg The SVG * @param size The size * @param name The name * @return A reponse containing the chart export. */ @POST @Produces({ "image/*" }) @Path("/saiku/chart") public Response exportChart(@FormParam("type") @DefaultValue("png") String type, @FormParam("svg") String svg, @FormParam("size") Integer size, @FormParam("name") String name) { try { final String imageType = type.toUpperCase(); Converter converter = Converter.byType("PDF"); if (converter == null) { throw new Exception("Image convert is null"); } // resp.setContentType(converter.getContentType()); // resp.setHeader("Content-disposition", "attachment; filename=chart." + converter.getExtension()); // final Integer size = req.getParameter("size") != null? Integer.parseInt(req.getParameter("size")) : null; // final String svgDocument = req.getParameter("svg"); // if (svgDocument == null) // { // resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing 'svg' parameter"); // return; // } if (StringUtils.isBlank(svg)) { throw new Exception("Missing 'svg' parameter"); } final InputStream in = new ByteArrayInputStream(svg.getBytes("UTF-8")); final ByteArrayOutputStream out = new ByteArrayOutputStream(); converter.convert(in, out, size); out.flush(); byte[] doc = out.toByteArray(); byte[] b = null; if (getVersion() != null && !getVersion().contains("EE")) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfReader reader = new PdfReader(doc); PdfStamper pdfStamper = new PdfStamper(reader, baos); URL dir_url = ExporterResource.class.getResource("/org/saiku/web/svg/watermark.png"); Image image = Image.getInstance(dir_url); for (int i = 1; i <= reader.getNumberOfPages(); i++) { PdfContentByte content = pdfStamper.getOverContent(i); image.setAbsolutePosition(450f, 280f); /*image.setAbsolutePosition(reader.getPageSize(1).getWidth() - image.getScaledWidth(), reader.getPageSize (1).getHeight() - image.getScaledHeight());*/ //image.setAlignment(Image.MIDDLE); content.addImage(image); } pdfStamper.close(); b = baos.toByteArray(); } else { b = doc; } if (!type.equals("pdf")) { PDDocument document = PDDocument.load(new ByteArrayInputStream(b), null); PDPageTree pdPages = document.getDocumentCatalog().getPages(); PDPage page = pdPages.get(0); BufferedImage o = new PDFRenderer(document).renderImage(0); ByteArrayOutputStream imgb = new ByteArrayOutputStream(); String ct = ""; String ext = ""; if (type.equals("png")) { ct = "image/png"; ext = "png"; } else if (type.equals("jpg")) { ct = "image/jpg"; ext = "jpg"; } ImageIO.write(o, type, imgb); byte[] outfile = imgb.toByteArray(); if (name == null || name.equals("")) { name = "chart"; } return Response.ok(outfile).type(ct) .header("content-disposition", "attachment; filename = " + name + "." + ext) .header("content-length", outfile.length).build(); } else { if (name == null || name.equals("")) { name = "chart"; } return Response.ok(b).type(converter.getContentType()) .header("content-disposition", "attachment; filename = " + name + "." + converter.getExtension()) .header("content-length", b.length).build(); } } catch (Exception e) { log.error("Error exporting Chart to " + type, e); return Response.serverError().entity(e.getMessage()).status(Status.INTERNAL_SERVER_ERROR).build(); } }
From source file:org.silverpeas.core.util.PdfUtil.java
License:Open Source License
/** * Add a image under or over content on each page of a PDF file. * @param pdfSource the source pdf file, this content is not modified by this method * @param imageToAdd the image file/*from w ww . j a va 2 s.co m*/ * @param pdfDestination the destination pdf file, with the image under or over content * @param isBackground indicates if image is addes under or over the content of the pdf source * file */ private static void addImageOnEachPage(InputStream pdfSource, File imageToAdd, OutputStream pdfDestination, final boolean isBackground) { // Verify given arguments if (imageToAdd == null || !imageToAdd.isFile()) { throw new SilverpeasRuntimeException("The image file doesn't exist"); } else if (!FileUtil.isImage(imageToAdd.getPath())) { throw new SilverpeasRuntimeException("The picture to add is not an image file"); } PdfReader reader = null; try { // Get a reader of PDF content reader = new PdfReader(pdfSource); // Obtain the total number of pages int pdfNbPages = reader.getNumberOfPages(); PdfStamper stamper = new PdfStamper(reader, pdfDestination); // Load the image Image image = Image.getInstance(imageToAdd.getPath()); float imageWidth = image.getWidth(); float imageHeigth = image.getHeight(); // Adding the image on each page of the PDF for (int i = 1; i <= pdfNbPages; i++) { // Page sizes Rectangle rectangle = reader.getPageSize(i); // Compute the scale of the image float scale = Math.min(100, (rectangle.getWidth() / imageWidth * 100)); image.scalePercent(Math.min(scale, (rectangle.getHeight() / imageHeigth * 100))); // Setting the image position for the current page image.setAbsolutePosition(computeImageCenterPosition(rectangle.getWidth(), image.getScaledWidth()), computeImageCenterPosition(rectangle.getHeight(), image.getScaledHeight())); // Adding image PdfContentByte imageContainer = isBackground ? stamper.getUnderContent(i) : stamper.getOverContent(i); imageContainer.addImage(image); } // End of the treatment : closing the stamper stamper.close(); } catch (Exception e) { SilverLogger.getLogger(PdfUtil.class).error(e); throw new SilverpeasRuntimeException( "A problem has occurred during the adding of an image into a pdf file", e); } finally { if (reader != null) { reader.close(); } } }
From source file:org.silverpeas.util.PdfUtil.java
License:Open Source License
/** * Add a image under or over content on each page of a PDF file. * @param pdfSource the source pdf file, this content is not modified by this method * @param imageToAdd the image file/* w w w.j a va2 s .c om*/ * @param pdfDestination the destination pdf file, with the image under or over content * @param isBackground indicates if image is addes under or over the content of the pdf source * file */ private static void addImageOnEachPage(InputStream pdfSource, File imageToAdd, OutputStream pdfDestination, final boolean isBackground) { // Verify given arguments if (imageToAdd == null || !imageToAdd.isFile()) { throw new RuntimeException("The image file doesn't exist"); } else if (!FileUtil.isImage(imageToAdd.getPath())) { throw new RuntimeException("The picture to add is not an image file"); } PdfReader reader = null; try { // Get a reader of PDF content reader = new PdfReader(pdfSource); // Obtain the total number of pages int pdfNbPages = reader.getNumberOfPages(); PdfStamper stamper = new PdfStamper(reader, pdfDestination); // Load the image Image image = Image.getInstance(imageToAdd.getPath()); float imageWidth = image.getWidth(); float imageHeigth = image.getHeight(); // Adding the image on each page of the PDF for (int i = 1; i <= pdfNbPages; i++) { // Page sizes Rectangle rectangle = reader.getPageSize(i); // Compute the scale of the image float scale = Math.min(100, (rectangle.getWidth() / imageWidth * 100)); image.scalePercent(Math.min(scale, (rectangle.getHeight() / imageHeigth * 100))); // Setting the image position for the current page image.setAbsolutePosition(computeImageCenterPosition(rectangle.getWidth(), image.getScaledWidth()), computeImageCenterPosition(rectangle.getHeight(), image.getScaledHeight())); // Adding image PdfContentByte imageContainer = isBackground ? stamper.getUnderContent(i) : stamper.getOverContent(i); imageContainer.addImage(image); } // End of the treatment : closing the stamper stamper.close(); } catch (Exception e) { SilverTrace.error("util", "PdfUtil.stamp", "EX_ERROR_PDF_ADD_WATERWARK", e); throw new RuntimeException("A problem has occured during the adding of an image into a pdf file", e); } finally { if (reader != null) { reader.close(); } } }