List of usage examples for com.lowagie.text.pdf PdfStamper close
public void close() throws DocumentException, IOException
From source file:docx4j.TextSubstitution.java
License:Apache License
private String addWaterMark() throws IOException, DocumentException { String result = null;/* w w w . j ava 2 s . c o m*/ String newFileName = this.getFolderPath() + "wm" + this.fileName; try { // try to delete the file if it already exists so that we refresh the watermark // if it fails then at least we have the existing version which can be deleted manually File target = new File(newFileName); if (target.exists()) { if (!target.delete()) { return "existing"; } } // add the watermark PdfReader reader = new PdfReader(this.filePath); PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(newFileName)); Image watermark_image = Image.getInstance(this.getFolderPath() + "doc-watermark.png"); watermark_image.setAbsolutePosition(5, 5); int i = 0; PdfContentByte add_watermark; // loop the pages adding the watermark while (i < reader.getNumberOfPages()) { i++; add_watermark = stamp.getUnderContent(i); add_watermark.addImage(watermark_image); } stamp.close(); reader.close(); } catch (Exception e) { result = e.getMessage(); } return result; }
From source file:ec.gov.informatica.firmadigital.FirmaDigital.java
License:Open Source License
/** * Firma un archivo./*from ww w. j a va 2s . co m*/ * * @param data * @return */ // public void firmar(String claveToken, // String tipoCertificado, String urlCertificado, String path) { public void firmar(String claveToken, String tipoCertificado, String path) { try { KeyStore keyStore = null; Enumeration<String> enumeration = null; String alias = null; PrivateKey privateKey = null; Certificate[] certs = null; CMSSignatureProcessor cms = null; KeyStoreProvider keyStoreProvider = null; try { if (tipoCertificado.equals("1") || tipoCertificado.equals("2") || tipoCertificado.equals("3")) { System.out.println("- Firmando con certificado token." + tipoCertificado); keyStoreProvider = this.getKeyStoreProvider(tipoCertificado); System.out.println(claveToken.toCharArray()); keyStore = keyStoreProvider.getKeystore(claveToken.toCharArray()); enumeration = keyStore.aliases(); alias = enumeration.nextElement(); privateKey = (PrivateKey) keyStore.getKey(alias, null); cms = new BouncyCastleSignatureProcessor(keyStore); } // if (tipoCertificado.equals("4")) { // System.out.println("- Firmando con certificado en archivo."); // keyStore = java.security.KeyStore.getInstance("PKCS12"); // // instancia el ks // keyStore.load(new java.io.FileInputStream(urlCertificado), // claveToken.toCharArray()); // Enumeration en = keyStore.aliases(); // alias = ""; // Vector vectaliases = new Vector(); // while (en.hasMoreElements()) { // vectaliases.add(en.nextElement()); // } // String[] aliases = (String[]) (vectaliases.toArray(new // String[0])); // for (int i = 0; i < aliases.length; i++) { // if (keyStore.isKeyEntry(aliases[i])) { // alias = aliases[i]; // break; // } // } // privateKey = (PrivateKey) keyStore.getKey(alias, // claveToken.toCharArray()); // cms = new BouncyCastleSignatureProcessor(keyStore); // } } catch (Exception e) { System.out.println(" \n Fallo trayendo keystore " + e.getMessage()); } certs = keyStore.getCertificateChain(alias); Certificate[] chain = keyStore.getCertificateChain(alias); PrivateKey key = (PrivateKey) keyStore.getKey(alias, claveToken.toCharArray()); String revocados = ""; // para verificar revocados revocados = verificaRevocados(((X509Certificate) certs[0]).getSerialNumber().toString(), tipoCertificado); if (!revocados.isEmpty()) { System.out.println(" CERTIFICADO REVOCADO " + revocados); return; } System.out.println("- Certificado valido "); PdfReader reader = new PdfReader(path); FileOutputStream fout = new FileOutputStream(path + ".Firmado.pdf"); PdfStamper stp = PdfStamper.createSignature(reader, fout, '?'); PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); sap.setReason("Firma Procesos Legales"); sap.setLocation("RedTools"); // Aade la firma visible. Podemos comentarla para que no sea // visible. sap.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, null); stp.close(); // byte[] datosFirmados = cms.sign(data, privateKey, certs); System.out.println("Firmado Correctamente..!"); // this.datosUsuarioActual = this // .crearDatosUsuario((X509Certificate) certs[0]); // llena la // clase de // tipo // datosUsuario // con el // certificado // actual // return datosFirmados; } catch (GeneralSecurityException e) { throw new RuntimeException(e); // FIXME } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(e); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(e); } }
From source file:erando.controllers.InterfaceRandoController.java
void genererpdf() throws IOException, FileNotFoundException, DocumentException { PdfReader pdfTemplate = new PdfReader("templatefacture.pdf"); RandonneService rando = new RandonneService(); Randonne r = new Randonne(); r = rando.findById(RecupererIdRando.getIdRando()); FileOutputStream fileOutputStream = new FileOutputStream("test.pdf"); ByteArrayOutputStream out = new ByteArrayOutputStream(); PdfStamper stamper = new PdfStamper(pdfTemplate, fileOutputStream); stamper.setFormFlattening(true);/*from w w w . j av a 2 s. com*/ stamper.getAcroFields().setField("name", r.getTitre()); stamper.getAcroFields().setField("montant", String.valueOf(r.getPrix())); stamper.getAcroFields().setField("depart", r.getPointDepart()); stamper.getAcroFields().setField("arrivee", r.getDestination()); stamper.getAcroFields().setField("date", String.valueOf(r.getDate())); stamper.close(); pdfTemplate.close(); }
From source file:erando.controllers.ReservationByuserController.java
void genererpdf() throws IOException, FileNotFoundException, DocumentException { PdfReader pdfTemplate = new PdfReader("templatefacture.pdf"); FileOutputStream fileOutputStream = new FileOutputStream("test.pdf"); ByteArrayOutputStream out = new ByteArrayOutputStream(); PdfStamper stamper = new PdfStamper(pdfTemplate, fileOutputStream); stamper.setFormFlattening(true);//from w w w . ja v a 2s . co m stamper.getAcroFields().setField("name", titre); stamper.getAcroFields().setField("montant", String.valueOf(prix)); stamper.getAcroFields().setField("depart", depart); stamper.getAcroFields().setField("arrivee", destination); stamper.getAcroFields().setField("date", String.valueOf(date)); stamper.close(); pdfTemplate.close(); }
From source file:erando.services.impl.pdfCreation.java
public void genererpdf(String titre, float prix, String imageName, int id, String description) throws IOException, FileNotFoundException, DocumentException { PdfReader pdfTemplate = new PdfReader("template.pdf"); FileOutputStream fileOutputStream = new FileOutputStream(id + ".pdf"); ByteArrayOutputStream out = new ByteArrayOutputStream(); PdfStamper stamper = new PdfStamper(pdfTemplate, fileOutputStream); stamper.setFormFlattening(true);/* w ww. ja v a 2s. com*/ stamper.getAcroFields().setField("titre", titre.toUpperCase()); stamper.getAcroFields().setField("description", description); stamper.getAcroFields().setField("prix", "" + prix); stamper.close(); pdfTemplate.close(); }
From source file:eu.europa.ec.markt.dss.signature.pades.PAdESProfileLTV.java
License:Open Source License
@Override public Document extendSignatures(Document document, Document originalData, SignatureParameters parameters) throws IOException { try {// ww w. j ava 2 s . co m final PdfReader reader = new PdfReader(document.openStream()); final ByteArrayOutputStream output = new ByteArrayOutputStream(); final PdfStamper stamper = new PdfStamper(reader, output, '\0', true); LTVSignatureValidationCallback callback = new LTVSignatureValidationCallback(stamper); pdfSignatureService.validateSignatures(document.openStream(), callback); PdfIndirectReference certsRef = stamper.getWriter().getPdfIndirectReference(); stamper.getWriter().addToBody(callback.getCertsArray(), certsRef, false); PdfDictionary dssDictionary = new PdfDictionary(new PdfName("DSS")); PdfDictionary vriDictionary = new PdfDictionary(new PdfName("VRI")); PdfDictionary sigVriDictionary = new PdfDictionary(); integrateCRL(callback, stamper, dssDictionary, sigVriDictionary, sigVriDictionary); integrateOCSP(callback, stamper, dssDictionary, sigVriDictionary, sigVriDictionary); // Add the signature's VRI dictionary, hashing the signature block from the callback method MessageDigest _md = MessageDigest.getInstance(DigestAlgorithm.SHA1.getName()); String hexHash = Hex.encodeHexString(_md.digest(callback.getSignatureBlock())).toUpperCase(); PdfIndirectReference sigVriRef = stamper.getWriter().getPdfIndirectReference(); stamper.getWriter().addToBody(sigVriDictionary, sigVriRef, false); vriDictionary.put(new PdfName(hexHash), sigVriRef); PdfIndirectReference vriRef = stamper.getWriter().getPdfIndirectReference(); stamper.getWriter().addToBody(vriDictionary, vriRef, false); // Add final objects to DSS dictionary dssDictionary.put(new PdfName("VRI"), vriRef); dssDictionary.put(new PdfName("Certs"), certsRef); PdfIndirectReference dssRef = stamper.getWriter().getPdfIndirectReference(); stamper.getWriter().addToBody(dssDictionary, dssRef, false); reader.getCatalog().put(new PdfName("DSS"), dssRef); // /Extensions<</ADBE<</BaseVersion/1.7/ExtensionLevel 5>>>> PdfDeveloperExtension etsiExtension = new PdfDeveloperExtension(PdfName.ADBE, new PdfName("1.7"), 5); stamper.getWriter().addDeveloperExtension(etsiExtension); stamper.getWriter().addToBody(reader.getCatalog(), reader.getCatalog().getIndRef(), false); stamper.close(); output.close(); Document extendedDocument = new InMemoryDocument(output.toByteArray()); ByteArrayOutputStream ltvDoc = new ByteArrayOutputStream(); ITextPDFDocTimeSampService service = new ITextPDFDocTimeSampService(); byte[] digest = service.digest(extendedDocument.openStream(), parameters); TimeStampResponse tsToken = tspSource.getTimeStampResponse(parameters.getDigestAlgorithm(), digest); service.sign(extendedDocument.openStream(), tsToken.getTimeStampToken().getEncoded(), ltvDoc, parameters); return new InMemoryDocument(ltvDoc.toByteArray()); } catch (DocumentException ex) { throw new RuntimeException(ex); } catch (SignatureException e) { throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
From source file:fr.opensagres.odfdom.converter.pdf.internal.BackgroundImage.java
License:Open Source License
private ByteArrayOutputStream insertImage(ByteArrayOutputStream out, Image image) { try {//from www .j av a 2 s .c om ByteArrayOutputStream os = new ByteArrayOutputStream(out.size()); PdfReader reader = new PdfReader(out.toByteArray()); PdfStamper stamper = new PdfStamper(reader, os); for (int i = 1; i <= reader.getNumberOfPages(); i++) { PdfContentByte canvas = stamper.getUnderContent(i); canvas.addImage(image); } reader.close(); stamper.close(); return os; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:gov.anl.aps.cdb.portal.plugins.support.icmsLink.IcmsWatermarkUtility.java
License:Open Source License
/** * Adds a stamp of some metadata to ICMS documents. * * Function Credit: Thomas Fors/*from w ww. jav a 2 s. c o m*/ * * @return byte array ologgerf the stamped PDF file * @throws DocumentException - Error loading pdfstamper or creating font * @throws IOException - Error performing IO operation * @throws Base64DecodingException - Error converting downloadContent string to byte[] */ private byte[] addWatermarkToPDFFile() throws Base64DecodingException, DocumentException, IOException { byte[] pdfBytes = Base64.decode(downloadContentBase64Encoded); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/yy hh:mm:ss a"); LocalDateTime now = LocalDateTime.now(); String downloadTime = dtf.format(now); UserInfo user = (UserInfo) SessionUtility.getUser(); String username = null; if (user != null) { username = user.getUsername(); } else { username = "unknown user"; } String bottomMessage = "Downloaded via APS CDB by: " + username + " at " + downloadTime; controlledRev = updateOptionalValue(controlledRev); dnsCollectionId = updateOptionalValue(dnsCollectionId); dnsDocNumber = updateOptionalValue(dnsDocNumber); String watermarkContents = "Content ID: " + docName; watermarkContents += " Rev: " + controlledRev; watermarkContents += " Released: " + date; watermarkContents += " DNS Collection ID: " + dnsCollectionId; watermarkContents += " DNS Document ID: " + dnsDocNumber; PdfReader pdfReader = new PdfReader(pdfBytes); int n = pdfReader.getNumberOfPages(); ByteArrayOutputStream out = new ByteArrayOutputStream(); PdfStamper stamp = new PdfStamper(pdfReader, out); PdfContentByte over; BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); for (int i = 0; i < n; i++) { over = stamp.getOverContent(i + 1); over.beginText(); over.setTextMatrix(30, 30); over.setFontAndSize(bf, 10); over.setColorFill(new Color(0x80, 0x80, 0x80)); over.showTextAligned(Element.ALIGN_LEFT, watermarkContents, 25, 25, 90); over.showTextAligned(Element.ALIGN_LEFT, bottomMessage, 50, 10, 0); if (status.equals(ICMS_UNDER_REV_STATUS)) { over.setColorFill(new Color(0xFF, 0x00, 0x00)); } //over.showTextAligned(Element.ALIGN_LEFT, status, 25, 25 + bf.getWidthPoint(watermarkContents + " - ", 10), 90); over.endText(); } stamp.close(); return out.toByteArray(); }
From source file:hornet.framework.export.fdf.FDF.java
License:CeCILL license
/** * Thread-safe utility method for PDF generation, based on a FDF template stream and a data object to * merge. Fields defined in FDF that can't be merged (not corresponding field in data object) are stored * in FDF Result./*from w w w . ja v a 2 s . c o m*/ * * @param in * input stream of PDF/FDF (template) * @param out * output stream of final PDF * @param data * a javabean or a java.util.Map. Nested properties are allowed this field names access pattern * : "propA:propB:propC". * @return FDF result object (not null) */ public static FDFRes export(final InputStream in, final OutputStream out, final Object data) { PdfReader pdfIn = null; PdfStamper stamper = null; final FDFRes res = new FDFRes(); try { pdfIn = new PdfReader(in); stamper = new PdfStamper(pdfIn, out); final AcroFields form = stamper.getAcroFields(); // fusion champs FDF avec le bean for (final Object nomField : form.getFields().keySet()) { fusionChamp(data, stamper, res, form, nomField); } // la ligne suivante supprime le formulaire stamper.setFormFlattening(true); } catch (final IOException ex) { throw new FDFExportException(ex); } catch (final DocumentException ex) { throw new FDFExportException(ex); } finally { try { stamper.close(); } catch (final Exception ex) { LOG.error("Erreur", ex); } } return res; }
From source file:it.flavianopetrocchi.jpdfbookmarks.itextbookmarksconverter.iTextBookmarksConverter.java
License:Open Source License
@Override public void createUnencryptedCopy(File tmpFile) throws IOException { try {/* w w w .jav a 2 s . c o m*/ PdfStamper tmpStamper = new PdfStamper(reader, new FileOutputStream(tmpFile)); tmpStamper.close(); } catch (DocumentException ex) { } }