List of usage examples for com.lowagie.text.pdf PdfStamper close
public void close() throws DocumentException, IOException
From source file:com.orange.atk.atkUI.corecli.utils.PdfUtilities.java
License:Apache License
/** * Adds a logo to the given pdf file.//from www . ja v a 2 s . c o m * @param pdfFileName * @param imageFileName * @param x position for image * @param y position for image * @throws Exception */ public void addWatermark(String pdfFileName, String imageFileName, int x, int y) throws Exception { // 1. copy File tmpPDFFile = new File(tmpDir, "tmpPDF.pdf"); copyFile(new File(pdfFileName), tmpPDFFile); // 2. add watermark // we create a reader for a certain document PdfReader reader = new PdfReader(tmpPDFFile.getAbsolutePath()); int n = reader.getNumberOfPages(); // we create a stamper that will copy the document to a new file PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(pdfFileName)); // adding content to each page int i = 0; PdfContentByte under; Image img = Image.getInstance(imageFileName); img.setAbsolutePosition(x, y); while (i < n) { i++; // watermark under the existing page under = stamp.getUnderContent(i); under.addImage(img); } // closing PdfStamper will generate the new PDF file stamp.close(); }
From source file:com.orange.atk.atkUI.corecli.utils.PdfUtilities.java
License:Apache License
/** * Adds a text in the given pdf file./*from w w w .j a v a2 s .c o m*/ * @param pdfFileName * @param text * @param x * @param y * @param rotation * @param page * @throws Exception */ public void addText(String pdfFileName, String text, int x, int y, int rotation, int page) throws Exception { // see example on http://itextdocs.lowagie.com/examples/com/lowagie/examples/general/copystamp/AddWatermarkPageNumbers.java // 1. copy File tmpPDFFile = new File(tmpDir, "tmpPDF.pdf"); copyFile(new File(pdfFileName), tmpPDFFile); // 2. add text // we create a reader for a certain document PdfReader reader = new PdfReader(tmpPDFFile.getAbsolutePath()); // we create a stamper that will copy the document to a new file PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(pdfFileName)); // adding content to each page PdfContentByte over; BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); over = stamp.getOverContent(page); over.beginText(); over.setFontAndSize(bf, 32); over.setTextMatrix(30, 30); over.setColorFill(java.awt.Color.RED); over.showTextAligned(Element.ALIGN_LEFT, text, x, y, rotation); over.endText(); // closing PdfStamper will generate the new PDF file stamp.close(); }
From source file:com.orange.atk.atkUI.corecli.utils.PdfUtilities.java
License:Apache License
public void addTemplate(String pdfFileName, String templatePDFFileName) throws Exception { // see example on http://itextdocs.lowagie.com/examples/com/lowagie/examples/general/copystamp/AddWatermarkPageNumbers.java // 1. copy/*from w ww . ja va 2 s . co m*/ File tmpPDFFile = new File(tmpDir, "tmpPDF.pdf"); copyFile(new File(pdfFileName), tmpPDFFile); // 2. add template on all pages // we create a reader for a certain document PdfReader reader = new PdfReader(tmpPDFFile.getAbsolutePath()); // we create a stamper that will copy the document to a new file PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(pdfFileName)); // adding content to each page int n = reader.getNumberOfPages(); int i = 0; // a reader for the template document PdfReader reader2 = new PdfReader(templatePDFFileName); PdfContentByte under; while (i < n) { i++; // template under the existing page under = stamp.getUnderContent(i); //under.addTemplate(stamp.getImportedPage(reader2, 1), 1, 0, 0, 1, 0, 0); under.addTemplate(stamp.getImportedPage(reader2, 1), -10, -50); } // closing PdfStamper will generate the new PDF file stamp.close(); }
From source file:com.servoy.extensions.plugins.pdf_output.PDFProvider.java
License:Open Source License
/** * Convert a protected PDF form to a PDF document. * * @sample/*from ww w. j a va 2 s .c om*/ * var pdfform = plugins.file.readFile('c:/temp/1040a-form.pdf'); * //var field_values = plugins.file.readFile('c:/temp/1040a-data.fdf');//read adobe fdf values or * var field_values = new Array()//construct field values * field_values[0] = 'f1-1=John C.J.' * field_values[1] = 'f1-2=Longlasting' * var result_pdf_doc = plugins.pdf_output.convertProtectedPDFFormToPDFDocument(pdfform, 'pdf_password', field_values) * if (result_pdf_doc != null) * { * plugins.file.writeFile('c:/temp/1040a-flatten.pdf', result_pdf_doc) * } * * @param pdf_form the PDF Form to convert * @param pdf_password the password to use * @param field_values the field values to use */ public byte[] js_convertProtectedPDFFormToPDFDocument(byte[] pdf_form, String pdf_password, Object field_values) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfReader reader = new PdfReader(pdf_form, pdf_password != null ? pdf_password.getBytes() : null); PdfStamper stamp = new PdfStamper(reader, baos); if (field_values != null) { AcroFields form = stamp.getAcroFields(); if (field_values instanceof String) { FdfReader fdf = new FdfReader((String) field_values); form.setFields(fdf); } else if (field_values instanceof byte[]) { FdfReader fdf = new FdfReader((byte[]) field_values); form.setFields(fdf); } else if (field_values instanceof Object[]) { for (int i = 0; i < ((Object[]) field_values).length; i++) { Object obj = ((Object[]) field_values)[i]; if (obj instanceof Object[]) { Object[] row = (Object[]) obj; if (row.length >= 2) { Object field = row[0]; Object value = row[1]; if (field != null && value != null) { form.setField(field.toString(), value.toString()); } } // else if (row.length >= 3) // { // form.setField(field, value); // } } else if (obj instanceof String) { String s = (String) obj; int idx = s.indexOf('='); form.setField(s.substring(0, idx), s.substring(idx + 1)); } } } } stamp.setFormFlattening(true); stamp.close(); return baos.toByteArray(); } catch (Exception e) { Debug.error(e); throw new RuntimeException("Error converting pdf form to pdf document", e); //$NON-NLS-1$ } }
From source file:com.square.adherent.noyau.service.implementations.RelevePrestationServiceImpl.java
License:Open Source License
@Override public FichierDto getRelevePrestationByteArray(Long idRelevePrestation, Long idPersonne, boolean duplicata) { logger.debug(messageSourceUtil.get(MessageKeyUtil.LOGGER_DEBUG_CONVERSION_RELEVE_PRESTATION, new String[] { String.valueOf(idRelevePrestation) })); final CritereSelectionRelevePrestationDto critereSelectionRelevePrestationDto = new CritereSelectionRelevePrestationDto(); critereSelectionRelevePrestationDto.setRelevePrestationId(idRelevePrestation); if (idPersonne != null) { critereSelectionRelevePrestationDto.setIdPersonne(idPersonne); }// w w w . j av a 2 s .co m final List<RelevePrestation> lstReleves = relevePrestationDao .getListeReleveParCriteres(critereSelectionRelevePrestationDto, null); if (lstReleves.size() == 1) { final RelevePrestation releve = lstReleves.get(0); final String error = messageSourceUtil.get(MessageKeyUtil.ERROR_RECUPERATION_FICHIER); FichierDto fichier; final String cheminFichier = serveurEmcRepReleve + File.separator + releve.getNomFichier(); try { fichier = new FichierDto(); fichier.setNomFichier(releve.getNomFichierCommercial()); if (duplicata) { // On appose la mention "DUPLICATA" sur toutes les pages du relev. try { final PdfReader reader = new PdfReader(cheminFichier); final int nombrePages = reader.getNumberOfPages(); final BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLDOBLIQUE, BaseFont.WINANSI, BaseFont.EMBEDDED); final PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FICHIER_DUPLICATA_TEMP)); final int taillePolice = 56; final int positionX = ((int) PageSize.A4.getWidth()) / 2; final int positionY = ((int) PageSize.A4.getHeight()) / 2; final int rotation = 30; for (int i = 1; i <= nombrePages; i++) { final PdfContentByte over = stamp.getOverContent(i); over.beginText(); over.setColorFill(Color.GRAY); final PdfGState gs1 = new PdfGState(); gs1.setFillOpacity(NIVEAU_TRANSPARENCE); over.setGState(gs1); over.setFontAndSize(bf, taillePolice); over.showTextAligned(PdfContentByte.ALIGN_CENTER, "DUPLICATA", positionX, positionY, rotation); over.endText(); } stamp.close(); reader.close(); fichier.setContenu(IOUtils.toByteArray(new FileInputStream(FICHIER_DUPLICATA_TEMP))); final File file = new File(FICHIER_DUPLICATA_TEMP); file.delete(); } catch (DocumentException e) { throw new TechnicalException( messageSourceUtil.get(MessageKeyUtil.ERROR_IMPOSSIBLE_AJOUTER_MENTION_DUPLICATA, new String[] { releve.getNomFichier() })); } } else { fichier.setContenu(IOUtils.toByteArray(new FileInputStream(cheminFichier))); } fichier.setTypeMime(Magic.getMagicMatch(fichier.getContenu()).getMimeType()); } catch (FileNotFoundException e) { logger.error(error + releve.getNomFichier(), e); throw new TechnicalException(error + cheminFichier); } catch (IOException e) { logger.error(error + releve.getNomFichier(), e); throw new TechnicalException(error + cheminFichier); } catch (MagicParseException e) { logger.error(error + releve.getNomFichier(), e); throw new TechnicalException(error + cheminFichier); } catch (MagicMatchNotFoundException e) { logger.error(error + releve.getNomFichier(), e); throw new TechnicalException(error + cheminFichier); } catch (MagicException e) { logger.error(error + releve.getNomFichier(), e); throw new TechnicalException(error + cheminFichier); } return fichier; } else { throw new TechnicalException( messageSourceUtil.get(MessageKeyUtil.ERROR_ABSCENCE_RELEVE_PRESTATION_PERSONNE)); } }
From source file:com.urservices.urerp.ecole.views.PdfReportView.java
@Override protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter pdfWriter, HttpServletRequest request, HttpServletResponse response) throws Exception { try {/*from w w w . j ava 2 s . c om*/ PdfReader pdfTemplate = new PdfReader((InputStream) model.get("template")); PdfStamper stamper = new PdfStamper(pdfTemplate, response.getOutputStream()); stamper.setFormFlattening(true); stamper.getAcroFields().setField("txtNom", "Kamdoum"); stamper.getAcroFields().setField("txtPrenom", "Samuel"); stamper.close(); pdfTemplate.close(); System.out.println("This PDF has " + pdfTemplate.getNumberOfPages() + " pages."); } catch (Exception e) { System.out.println("PdfReportView.buildPdfDocument() " + e.getMessage()); } }
From source file:com.userweave.batch.CreatePDF.java
License:Open Source License
public static void main(String[] args) { if (args.length == 0) { args = new String[] { "one.pdf", "two.pdf", "out.pdf" }; }/*from w ww. j ava 2s. com*/ if (args.length == 3) { try { // the document we're watermarking PdfReader document = new PdfReader(args[0]); int num_pages = document.getNumberOfPages(); // the watermark (or letterhead, etc.) PdfReader mark = new PdfReader(args[1]); Rectangle mark_page_size = mark.getPageSize(1); // the output document PdfStamper writer = new PdfStamper(document, new FileOutputStream(args[2])); // create a PdfTemplate from the first page of mark // (PdfImportedPage is derived from PdfTemplate) PdfImportedPage mark_page = writer.getImportedPage(mark, 1); for (int ii = 0; ii < num_pages;) { // iterate over document's pages, adding mark_page as // a layer 'underneath' the page content; scale mark_page // and move it so it fits within the document's page; // if document's page is cropped, then this scale might // not be small enough ++ii; Rectangle doc_page_size = document.getPageSize(ii); float h_scale = doc_page_size.getWidth() / mark_page_size.getWidth(); float v_scale = doc_page_size.getHeight() / mark_page_size.getHeight(); float mark_scale = (h_scale < v_scale) ? h_scale : v_scale; float h_trans = (float) ((doc_page_size.getWidth() - mark_page_size.getWidth() * mark_scale) / 2.0); float v_trans = (float) ((doc_page_size.getHeight() - mark_page_size.getHeight() * mark_scale) / 2.0); PdfContentByte contentByte = writer.getUnderContent(ii); contentByte.addTemplate(mark_page, mark_scale, 0, 0, mark_scale, h_trans, v_trans); } writer.close(); } catch (Exception ee) { ee.printStackTrace(); } } else { // input error System.err.println("arguments: in_document in_watermark out_pdf_fn"); } }
From source file:com.userweave.domain.service.pdf.ItextUtils.java
License:Open Source License
public OutputStream createPDF(InputStream generatedPDF, InputStream stampPDF, OutputStream out) throws IOException, DocumentException { // the document we're watermarking PdfReader document = new PdfReader(generatedPDF); int num_pages = document.getNumberOfPages(); // the watermark (or letterhead, etc.) PdfReader mark = new PdfReader(stampPDF); Rectangle mark_page_size = mark.getPageSize(1); // the output document PdfStamper writer = new PdfStamper(document, out); // create a PdfTemplate from the first page of mark // (PdfImportedPage is derived from PdfTemplate) PdfImportedPage mark_page = writer.getImportedPage(mark, 1); for (int ii = 0; ii < num_pages;) { // iterate over document's pages, adding mark_page as // a layer 'underneath' the page content; scale mark_page // and move it so it fits within the document's page; // if document's page is cropped, then this scale might // not be small enough ++ii;/* w ww . jav a 2 s .c o m*/ Rectangle doc_page_size = document.getPageSize(ii); float h_scale = doc_page_size.getWidth() / mark_page_size.getWidth(); float v_scale = doc_page_size.getHeight() / mark_page_size.getHeight(); float mark_scale = (h_scale < v_scale) ? h_scale : v_scale; float h_trans = (float) ((doc_page_size.getWidth() - mark_page_size.getWidth() * mark_scale) / 2.0); float v_trans = (float) ((doc_page_size.getHeight() - mark_page_size.getHeight() * mark_scale) / 2.0); PdfContentByte contentByte = writer.getUnderContent(ii); contentByte.addTemplate(mark_page, mark_scale, 0, 0, mark_scale, h_trans, v_trans); } writer.close(); return out; /* PdfReader reader = new PdfReader(origPDF); int n = reader.getNumberOfPages(); Document document = new Document(reader.getPageSizeWithRotation(1)); PdfWriter writer = PdfWriter.getInstance(document, outfile); writer.setEncryption(PdfWriter.STRENGTH40BITS, "pdf", null, PdfWriter.AllowCopy); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfImportedPage page; int rotation; int i = 0; while (i < n) { i++; document.setPageSize(reader.getPageSizeWithRotation(i)); document.newPage(); page = writer.getImportedPage(reader, i); rotation = reader.getPageRotation(i); if (rotation == 90 || rotation == 270) { cb.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).height()); } else { cb.addTemplate(page, 1f, 0, 0, 1f, 0, 0); } System.out.println("Processed page " + i); } document.close(); } catch( Exception e) { e.printStackTrace(); } */ }
From source file:de.jdufner.sudoku.generator.service.PdfGeneratorService.java
License:Open Source License
public void packPdf(String filePathName, String packageFileBaseName, String frontpageFileBaseName, String questsFileBaseName, String resultsFileBaseName, String htmlFileName) throws FileNotFoundException, DocumentException, IOException { PdfStamper pdfStamper = new PdfStamper(new PdfReader(filePathName + frontpageFileBaseName), new FileOutputStream(filePathName + packageFileBaseName)); pdfStamper.addFileAttachment("Quests", null, filePathName + questsFileBaseName, questsFileBaseName); pdfStamper.addFileAttachment("Results", null, filePathName + resultsFileBaseName, resultsFileBaseName); pdfStamper.addFileAttachment("HTML", null, filePathName + htmlFileName, htmlFileName); pdfStamper.makePackage(PdfName.T);//from ww w . j a v a2s .c o m pdfStamper.close(); }
From source file:dev.ztgnrw.htmlconverter.HtmlConverter.java
/** * Method for attachment. Adds a File to a PDF as attachment * //w w w . j a va 2 s . com * @param reader * @param output * @param attachment_uri * @throws IOException * @throws DocumentException */ private static void addFile(PdfReader reader, String output, String attachment_uri) throws IOException, DocumentException { File attachment = new File(attachment_uri); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(output + ".pdf")); // PdfFileSpecification fs = PdfFileSpecification.fileEmbedded( // stamper.getWriter(), null, "test.txt", "Some test".getBytes()); PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(stamper.getWriter(), null, attachment.getName(), Files.readAllBytes(attachment.toPath())); stamper.addFileAttachment("Attachment File", fs); stamper.close(); }