List of usage examples for com.lowagie.text.pdf PdfReader PdfReader
public PdfReader(PdfReader reader)
From source file:eu.europa.ec.markt.dss.signature.pdf.itext.ITextPDFDocTimeSampService.java
License:Open Source License
@SuppressWarnings({ "unchecked", "rawtypes" }) private PdfStamper prepareStamper(InputStream pdfData, OutputStream output, SignatureParameters parameters) throws IOException { try {//w w w.ja v a 2s . c o m PdfReader reader = new PdfReader(pdfData); PdfStamper stamper = PdfStamper.createSignature(reader, output, '\0', null, true); PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setAcro6Layers(true); appearance.setRender(PdfSignatureAppearance.SignatureRenderDescription); PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("ETSI.RFC3161")); // defined in ETSI TS 102 778-4 A.2 dic.put(PdfName.TYPE, new PdfName("DocTimeStamp")); Calendar cal = Calendar.getInstance(); if (parameters.getSigningDate() != null) { cal.setTime(parameters.getSigningDate()); appearance.setSignDate(cal); } dic.setDate(new PdfDate(cal)); appearance.setCryptoDictionary(dic); int csize = getSignatureSize(); HashMap exc = new HashMap(); exc.put(PdfName.CONTENTS, new Integer(csize * 2 + 2)); appearance.preClose(exc); return stamper; } catch (DocumentException e) { throw new IOException(e); } }
From source file:eu.europa.ec.markt.dss.signature.pdf.itext.ITextPDFDocTimeSampService.java
License:Open Source License
@SuppressWarnings("unchecked") private void validateSignatures(InputStream input, PdfDict outerCatalog, SignatureValidationCallback callback, List<String> alreadyLoadedRevisions) throws IOException, SignatureException { PdfReader reader = new PdfReader(input); AcroFields af = reader.getAcroFields(); /*/*from w w w . j a v a2 s . c om*/ * Search the whole document of a signature */ ArrayList<String> names = af.getSignatureNames(); LOG.info(names.size() + " signature(s)"); // For every signature : for (String name : names) { // Affichage du nom LOG.info("Signature name: " + name); LOG.info("Signature covers whole document: " + af.signatureCoversWholeDocument(name)); // Affichage sur les revision - version LOG.info("Document revision: " + af.getRevision(name) + " of " + af.getTotalRevisions()); /* * We are only interested in the validation of signature that covers the whole document. */ if (af.signatureCoversWholeDocument(name)) { PdfPKCS7 pk = af.verifySignature(name); Calendar cal = pk.getSignDate(); Certificate pkc[] = pk.getCertificates(); PdfDict signatureDictionary = new ITextPdfDict(af.getSignatureDictionary(name)); String revisionName = Integer.toString(af.getRevision(name)); if (!alreadyLoadedRevisions.contains(revisionName)) { callback.validate(new ITextPdfDict(reader.getCatalog()), outerCatalog, pk.getSigningCertificate(), cal != null ? cal.getTime() : null, pkc, signatureDictionary, new ITextPdfSignatureInfo(pk)); alreadyLoadedRevisions.add(revisionName); } } else { PdfDict catalog = new ITextPdfDict(reader.getCatalog()); /* * We open the version of the document that was protected by the signature */ ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream ip = af.extractRevision(name); IOUtils.copy(ip, out); out.close(); ip.close(); /* * You can sign a PDF document with only one signature. So when we want the multiple signatures, the * signatures are appended sequentially to the end of the document. The recursive call helps to get the * signature from the original document. */ validateSignatures(new ByteArrayInputStream(out.toByteArray()), catalog, callback, alreadyLoadedRevisions); } } }
From source file:eu.europa.ec.markt.dss.signature.pdf.itext.ITextPDFSignatureService.java
License:Open Source License
@SuppressWarnings({ "unchecked", "rawtypes" }) private PdfStamper prepareStamper(InputStream pdfData, OutputStream output, SignatureParameters parameters) throws IOException, DocumentException { PdfReader reader = new PdfReader(pdfData); PdfStamper stp = PdfStamper.createSignature(reader, output, '\0', null, true); PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setAcro6Layers(true);//from www. j a v a2s . c o m sap.setRender(PdfSignatureAppearance.SignatureRenderDescription); PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("ETSI.CAdES.detached")); Calendar cal = Calendar.getInstance(); cal.setTime(parameters.getSigningDate()); sap.setSignDate(cal); dic.setDate(new PdfDate(cal)); if (parameters.getReason() != null) { dic.setReason(parameters.getReason()); } if (parameters.getLocation() != null) { dic.setLocation(parameters.getLocation()); } if (parameters.getContactInfo() != null) { dic.setContact(parameters.getContactInfo()); } sap.setCryptoDictionary(dic); int csize = getSignatureSize(); HashMap exc = new HashMap(); exc.put(PdfName.CONTENTS, new Integer(csize * 2 + 2)); sap.preClose(exc); return stp; }
From source file:eu.europa.ec.markt.dss.signature.pdf.itext.ITextPDFSignatureService.java
License:Open Source License
@SuppressWarnings("unchecked") private void validateSignatures(InputStream input, PdfDict outerCatalog, SignatureValidationCallback callback, List<String> alreadyLoadedRevisions) throws IOException, SignatureException { PdfReader reader = new PdfReader(input); AcroFields af = reader.getAcroFields(); /*//www . j a v a2 s.com * Search the whole document of a signature */ ArrayList<String> names = af.getSignatureNames(); LOG.info(names.size() + " signature(s)"); // For every signature : for (String name : names) { // Affichage du nom LOG.info("Signature name: " + name); LOG.info("Signature covers whole document: " + af.signatureCoversWholeDocument(name)); // Affichage sur les revision - version LOG.info("Document revision: " + af.getRevision(name) + " of " + af.getTotalRevisions()); /* * We are only interested in the validation of signature that covers the whole document. */ if (af.signatureCoversWholeDocument(name)) { PdfPKCS7 pk = af.verifySignature(name); Calendar cal = pk.getSignDate(); Certificate pkc[] = pk.getCertificates(); PdfDict signatureDictionary = new ITextPdfDict(af.getSignatureDictionary(name)); String revisionName = Integer.toString(af.getRevision(name)); if (!alreadyLoadedRevisions.contains(revisionName)) { callback.validate(new ITextPdfDict(reader.getCatalog()), outerCatalog, pk.getSigningCertificate(), cal != null ? cal.getTime() : null, pkc, signatureDictionary, new ITextPdfSignatureInfo(pk)); alreadyLoadedRevisions.add(revisionName); } } else { PdfDict catalog = new ITextPdfDict(reader.getCatalog()); /* * We open the version of the document that was protected by the signature */ ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream ip = af.extractRevision(name); IOUtils.copy(ip, out); out.close(); ip.close(); /* * You can sign a PDF document with only one signature. So when we want multiple signature, signatures are * appended sequentially to the end of the document. The recursive call help to get the signature from the * original document. */ validateSignatures(new ByteArrayInputStream(out.toByteArray()), catalog, callback, alreadyLoadedRevisions); } } }
From source file:eu.europa.ec.markt.dss.signature.pdf.ITextPDFDocTimeSampService.java
License:Open Source License
@SuppressWarnings({ "unchecked", "rawtypes" }) private PdfStamper prepareStamper(InputStream pdfData, OutputStream output, SignatureParameters parameters) throws IOException, DocumentException { PdfReader reader = new PdfReader(pdfData); PdfStamper stp = PdfStamper.createSignature(reader, output, '\0', null, true); PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setAcro6Layers(true);//from w ww . jav a 2 s. c om sap.setRender(PdfSignatureAppearance.SignatureRenderDescription); PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("ETSI.RFC3161")); // defined in ETSI TS 102 778-4 A.2 dic.put(PdfName.TYPE, new PdfName("DocTimeStamp")); Calendar cal = Calendar.getInstance(); if (parameters.getSigningDate() != null) { cal.setTime(parameters.getSigningDate()); sap.setSignDate(cal); } dic.setDate(new PdfDate(cal)); sap.setCryptoDictionary(dic); int csize = getSignatureSize(); HashMap exc = new HashMap(); exc.put(PdfName.CONTENTS, new Integer(csize * 2 + 2)); sap.preClose(exc); return stp; }
From source file:eu.europa.ec.markt.dss.signature.pdf.ITextPDFDocTimeSampService.java
License:Open Source License
@SuppressWarnings("unchecked") private void validateSignatures(InputStream input, PdfDictionary outerCatalog, SignatureValidationCallback callback, List<String> alreadyLoadedRevisions) throws IOException, SignatureException { PdfReader reader = new PdfReader(input); AcroFields af = reader.getAcroFields(); /*/*from w w w . jav a2 s .com*/ * Search the whole document of a signature */ ArrayList<String> names = af.getSignatureNames(); LOG.info(names.size() + " signature(s)"); // For every signature : for (String name : names) { // Affichage du nom LOG.info("Signature name: " + name); LOG.info("Signature covers whole document: " + af.signatureCoversWholeDocument(name)); // Affichage sur les revision - version LOG.info("Document revision: " + af.getRevision(name) + " of " + af.getTotalRevisions()); /* * We are only interrested in the validation of signature that covers the whole document. */ if (af.signatureCoversWholeDocument(name)) { PdfPKCS7 pk = af.verifySignature(name); Calendar cal = pk.getSignDate(); Certificate pkc[] = pk.getCertificates(); PdfDictionary signatureDictionary = af.getSignatureDictionary(name); String revisionName = Integer.toString(af.getRevision(name)); if (!alreadyLoadedRevisions.contains(revisionName)) { callback.validate(reader, outerCatalog, pk.getSigningCertificate(), cal != null ? cal.getTime() : null, pkc, signatureDictionary, pk); alreadyLoadedRevisions.add(revisionName); } } else { PdfDictionary catalog = reader.getCatalog(); /* * We open the version of the document that was protected by the signature */ ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream ip = af.extractRevision(name); IOUtils.copy(ip, out); out.close(); ip.close(); /* * You can sign a PDF document with only one signature. So when we want multiple signature, signatures * are appended sequentially to the end of the document. The recursive call help to get the signature * from the original document. */ validateSignatures(new ByteArrayInputStream(out.toByteArray()), catalog, callback, alreadyLoadedRevisions); } } }
From source file:eu.europa.ec.markt.dss.signature.pdf.StatefulITextPDFSignatureService.java
License:Open Source License
@SuppressWarnings({ "unchecked", "rawtypes" }) private PdfStamper prepareStamper(InputStream pdfData, OutputStream output, SignatureParameters parameters) throws IOException, DocumentException { if (stp != null) { return stp; }/* w w w.j a v a2 s.co m*/ PdfReader reader = new PdfReader(pdfData); stp = PdfStamper.createSignature(reader, output, '\0', null, true); PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setAcro6Layers(true); sap.setLayer2Text(""); if (parameters.getSignatureAppearance() != null) { sap.setRender(PdfSignatureAppearance.SignatureRenderGraphic); sap.setImage(null); PdfReader stampReader = new PdfReader(parameters.getSignatureAppearance()); PdfTemplate stamp = stp.getWriter().getImportedPage(stampReader, 1); //stamp.setBoundingBox(new Rectangle(200, 100)); sap.setTemplate(stamp); sap.setSignatureGraphic(Image.getInstance(stamp)); float[] pos = parameters.getSignaturePosition(); Rectangle rect = new Rectangle(pos[0], pos[1], pos[2], pos[3]); sap.setVisibleSignature(rect, 1, parameters.getSignatureName()); } else { sap.setRender(PdfSignatureAppearance.SignatureRenderDescription); } PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("ETSI.CAdES.detached")); Calendar cal = Calendar.getInstance(); cal.setTime(parameters.getSigningDate()); sap.setSignDate(cal); dic.setDate(new PdfDate(cal)); if (parameters.getReason() != null) { dic.setReason(parameters.getReason()); } if (parameters.getLocation() != null) { dic.setLocation(parameters.getLocation()); } if (parameters.getContactInfo() != null) { dic.setContact(parameters.getContactInfo()); } sap.setCryptoDictionary(dic); int csize = getSignatureSize(); HashMap exc = new HashMap(); exc.put(PdfName.CONTENTS, new Integer(csize * 2 + 2)); sap.preClose(exc); return stp; }
From source file:Faculty.Scans_Upload_Processor.java
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try {/*from w w w .ja v a 2 s. c o m*/ HttpSession session = request.getSession(); MyDB m = new MyDB(); int total_sheets = (Integer) session.getAttribute("total_sheets"); int p_id = (Integer) session.getAttribute("p_id"); String path = (String) getServletContext().getInitParameter("Directory") + "//"; if (!(new File(path)).exists()) { (new File(path)).mkdir(); // creates the directory if it does not exist } path = path + (Integer) p_id + "//"; System.out.println(); ArrayList err = new ArrayList(); ArrayList rollList = new ArrayList(); ArrayList DocIds = new ArrayList(); if (!(new File(path)).exists()) { (new File(path)).mkdir(); // creates the directory if it does not exist } boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List /* FileItem */ items = upload.parseRequest(request); // Process the uploaded form items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { } else { try { String str = item.getName(); String ext = FilenameUtils.getExtension(str); if (ext.equals("txt") || ext.equals("text")) { if ((new File(path + str)).exists()) { (new File(path + str)).delete(); // deletes the file if it does already exist } File savedFile = new File(path + str); item.write(savedFile); BufferedReader br = new BufferedReader(new FileReader(path + str)); String line; while ((line = br.readLine()) != null) { rollList.add(Integer.parseInt(line.trim())); } br.close(); DocIds = m.getDocIds(p_id, rollList); Iterator it = DocIds.iterator(); while (it.hasNext()) { int temp = (Integer) it.next(); if ((new File(path + temp + "//")).exists()) { try { delete(new File(path + temp + "//")); // deletes the directory if it does already exist } catch (IOException e) { e.printStackTrace(); System.exit(0); } } } m.CreateDocIds(p_id, rollList); DocIds = m.getDocIds(p_id, rollList); it = DocIds.iterator(); while (it.hasNext()) { int temp = (Integer) it.next(); if (!(new File(path + temp + "//")).exists()) { (new File(path + temp + "//")).mkdir(); // creates the directory if it does not exist } } } else { // To Store Split Files if ((new File(path + "-1" + "//")).exists()) { try { delete(new File(path + "-1" + "//")); // deletes the directory if it does already exist } catch (IOException e) { e.printStackTrace(); System.exit(0); } } if (!(new File(path + "-1" + "//")).exists()) { (new File(path + "-1" + "//")).mkdir(); // creates the directory if it does not exist } //Splitting PDF int n = 0; // no.of pages try { File savedFile = new File(path + "-1" + "//" + str); item.write(savedFile); String inFile = path + "-1" + "//" + str; System.out.println("Reading " + inFile); PdfReader reader = new PdfReader(inFile); n = reader.getNumberOfPages(); // Reply User if PDF has invalid number of scans if (n != total_sheets * DocIds.size()) { m.deleteDocIds(p_id, rollList); Iterator it = DocIds.iterator(); while (it.hasNext()) { int temp = (Integer) it.next(); if ((new File(path + temp + "//")).exists()) { try { delete(new File(path + temp + "//")); // deletes the directory if it does already exist } catch (IOException e) { e.printStackTrace(); System.exit(0); } } } err.add("PDF has missing scans!! It must have " + total_sheets * DocIds.size() + " pages"); break; } // postData(); System.out.println("Number of pages : " + n); int i = 0; while (i < n) { String outFile = (i + 1) + ".pdf"; System.out.println("Writing " + outFile); Document document = new Document(reader.getPageSizeWithRotation(1)); PdfCopy writer = new PdfCopy(document, new FileOutputStream(path + "-1" + "//" + outFile)); document.open(); PdfImportedPage page = writer.getImportedPage(reader, ++i); writer.addPage(page); document.close(); writer.close(); } } catch (Exception e) { e.printStackTrace(); } // Placing files in Corresponding directories //System.out.println(DocIds); for (int i = 1; i <= n; i++) { int temp2 = (i - 1) / total_sheets; int d_id = (Integer) DocIds.get(temp2); String itemName = ""; if ((i % total_sheets) == 0) { itemName = ((Integer) total_sheets).toString(); } else { itemName = ((Integer) (i % total_sheets)).toString(); } File source = new File(path + "-1" + "//" + i + ".pdf"); File desc = new File( path + "-1//" + p_id + "_" + d_id + "_" + itemName + ".pdf"); try { FileUtils.copyFile(source, desc); uploadFile(path + "-1//" + p_id + "_" + d_id + "_" + itemName + ".pdf", (String) getServletContext().getInitParameter("UploadPhP")); } catch (IOException e) { e.printStackTrace(); } } try { delete(new File(path + "-1" + "//")); // deletes the directory if it does already exist delete(new File(path)); // deletes all docs in this paper id } catch (IOException e) { e.printStackTrace(); System.exit(0); } err.add("Scans sucessfully saved !"); } } catch (Exception e) { e.printStackTrace(); } } } request.setAttribute("err", err); RequestDispatcher rd = request.getRequestDispatcher("Paper_Spec_Fetcher"); rd.forward(request, response); } else { // Normal request. request.getParameter will suffice. } } catch (Exception e) { e.printStackTrace(); } finally { out.close(); } }
From source file:fr.opensagres.odfdom.converter.pdf.internal.BackgroundImage.java
License:Open Source License
private ByteArrayOutputStream insertImage(ByteArrayOutputStream out, Image image) { try {// ww w . ja va 2 s . com 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 w w . j a v a2 s. com*/ * * @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(); }