List of usage examples for com.lowagie.text.pdf PdfStamper close
public void close() throws DocumentException, IOException
From source file:org.saiku.web.rest.resources.ExporterResource.java
License:Apache License
/** * Export chart to a file./*www.j a va 2 s .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 www .j a va 2s . com * @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//from ww w .ja v a2 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(); } } }
From source file:org.squale.welcom.outils.pdf.advanced.WPdfDecoration.java
License:Open Source License
/** * Met a la decoration du document;//from w w w . j a v a 2 s . c o m * * @param pdfReader le reader * @param out l'outputstream * @throws DocumentException exception pouvant etre levee * @throws IOException exception pouvant etre levee */ public void fill(final PdfReader pdfReader, final OutputStream out) throws DocumentException, IOException { final int n = pdfReader.getNumberOfPages(); final PdfStamper stamp = new PdfStamper(pdfReader, out); for (int i = 1; i <= n; i++) { if (i >= startDecorationPage) { // PdfImportedPage page = stamp.getImportedPage (pdfReader, i); final PdfContentByte over = stamp.getOverContent(i); final Rectangle pageSize = pdfReader.getPageSizeWithRotation(i); if (header != null) { header.fill(over, pageSize, i, n); } if (footer != null) { footer.fill(over, pageSize, i, n); } } } stamp.close(); }
From source file:org.squale.welcom.outils.pdf.advanced.WPdfMerge.java
License:Open Source License
/** * Renomme tous le champs du pdf avoir qu'il soit tous uniques * //from w w w. ja va 2 s. co m * @param pdfReader le reader * @return les champs renommes * @throws DocumentException exception pouvant etre levee * @throws IOException exception pouvant etre levee */ private byte[] renameFieldUnique(final PdfReader pdfReader) throws DocumentException, IOException { final ByteArrayOutputStream pOut = new ByteArrayOutputStream(); final PdfStamper pdfStamper = new PdfStamper(pdfReader, pOut); if (pdfReader.getAcroForm() != null) { for (int i = 0; i < pdfReader.getAcroForm().size(); i++) { final PRAcroForm.FieldInformation p = (PRAcroForm.FieldInformation) pdfReader.getAcroForm() .getFields().get(i); final String newName = WPdfMerge.getUniqueFieldName(); pdfStamper.getAcroFields().renameField(p.getName(), newName); } } pdfStamper.close(); return pOut.toByteArray(); }
From source file:org.squale.welcom.outils.pdf.WPdfUtil.java
License:Open Source License
/** * Ajoute dans les parametres du report les paramtres pour l'ouverture en plein ecran Utilise itext.jar * // ww w . j a v a2 s. c o m * @param report : report * @param out : flux pour ecrire * @throws DocumentException : Probleme a la lecture du document * @throws IOException : Probleme a l'ecriture dans la stream */ public static void fullScreen(final byte report[], final OutputStream out) throws DocumentException, IOException { final PdfStamper stamper = new PdfStamper(new PdfReader(report), out); stamper.setViewerPreferences(PdfWriter.PageLayoutTwoColumnRight | PdfWriter.PageModeFullScreen | PdfWriter.NonFullScreenPageModeUseThumbs); stamper.close(); }
From source file:org.squale.welcom.outils.pdf.WPdfUtil.java
License:Open Source License
/** * Ajoute dans les parametres du report l'impression au chargement du document Utilise itext.jar * //w w w. ja va2 s. c o m * @param report : report * @param out : flux pour ecrire * @throws DocumentException : Probleme a la lecture du document * @throws IOException : Probleme a l'ecriture dans la stream */ public static void autoPrint(final byte report[], final OutputStream out) throws DocumentException, IOException { final PdfStamper stamper = new PdfStamper(new PdfReader(report), out); stamper.addJavaScript("this.print(false);"); stamper.close(); }
From source file:org.squale.welcom.outils.pdf.WPdfUtil.java
License:Open Source License
/** * Ajoute dans les parametres du report l'impression au chargement du document avec choix pour l'imprimante Utilise * itext.jar// w w w . jav a 2 s . c om * * @param report : report * @param out : flux pour ecrire * @throws DocumentException : Probleme a la lecture du document * @throws IOException : Probleme a l'ecriture dans la stream */ public static void autoPrintPopup(final byte report[], final OutputStream out) throws DocumentException, IOException { final PdfStamper stamper = new PdfStamper(new PdfReader(report), out); stamper.addJavaScript("this.print(true);"); stamper.close(); }
From source file:papertoolkit.render.sheets.PDFSheetRenderer.java
License:BSD License
/** * Uses the iText package to render a PDF file. iText is nice because we can write to a * Graphics2D context. Alternatively, we can use PDF-like commands. * // w ww. ja v a2 s .c om * @param destPDFFile */ public void renderToPDF(File destPDFFile) { try { final FileOutputStream fileOutputStream = new FileOutputStream(destPDFFile); final PdfReader reader = pdfSheet.getReader(); DebugUtils.println("NumPages in Existing PDF: " + reader.getNumberOfPages()); // allows us to stamp on top of an existing PDF final PdfStamper stamp = new PdfStamper(reader, fileOutputStream); // change the content on top of page 1 // bottom layer for regions final PdfContentByte topLayer = stamp.getOverContent(1 /* page number */); final PdfContentByte bottomLayer = stamp.getUnderContent(1); renderToPDFContentLayers(destPDFFile, topLayer, bottomLayer); stamp.close(); // save the pattern info to the same directory automatically savePatternInformation(); // do this automatically } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:pdflicense.PdfLicenseManager.java
License:Open Source License
private void writeXmp(PdfReader reader, FileOutputStream fos, byte[] xmpBytes) throws DocumentException, IOException { PdfStamper stamp = new PdfStamper(reader, fos); stamp.setXmpMetadata(xmpBytes);/*from w w w. ja v a 2 s .c o m*/ stamp.close(); }