List of usage examples for com.lowagie.text.pdf PdfReader getAcroFields
public AcroFields getAcroFields()
AcroFields
. 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(); /*/* w w w .j a v a2 s . c o m*/ * 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:it.jugpadova.blo.ParticipantBadgeBo.java
License:Apache License
protected int getParticipantsPerPage(Event event) throws IOException { int count = 0; InputStream templateIs = getBadgePageTemplateInputStream(event); RandomAccessFileOrArray rafa = new RandomAccessFileOrArray(templateIs); PdfReader template = new PdfReader(rafa, null); AcroFields form = template.getAcroFields(); HashMap fields = form.getFields(); while (true) { if (fields.containsKey("firstName" + (count + 1))) { count++;//from w ww . j a v a 2s . co m } else { break; } } template.close(); return count; }
From source file:net.sf.jsignpdf.verify.SignatureCounter.java
License:Mozilla Public License
/** * Main program./*from www .j ava2 s .c o m*/ * * @param args */ public static void main(String[] args) { // create the Options final Option optHelp = new Option("h", "help", false, "print this message"); final Option optDebug = new Option("d", "debug", false, "enables debug output"); final Option optNames = new Option("n", "names", false, "print comma separated signature names instead of the count"); final Option optPasswd = new Option("p", "password", true, "set password for opening PDF"); optPasswd.setArgName("password"); final Options options = new Options(); options.addOption(optHelp); options.addOption(optDebug); options.addOption(optNames); options.addOption(optPasswd); CommandLine line = null; try { // create the command line parser CommandLineParser parser = new PosixParser(); // parse the command line arguments line = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Unable to parse command line (Use -h for the help)\n" + exp.getMessage()); System.exit(Constants.EXIT_CODE_PARSE_ERR); } final String[] tmpArgs = line.getArgs(); if (line.hasOption("h") || args == null || args.length == 0) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(70, "java -jar SignatureCounter.jar [file1.pdf [file2.pdf ...]]", "JSignPdf SignatureCounter is a command line tool which prints count of signatures in given PDF document.", options, null, true); } else { byte[] tmpPasswd = null; if (line.hasOption("p")) { tmpPasswd = line.getOptionValue("p").getBytes(); } final boolean debug = line.hasOption("d"); final boolean names = line.hasOption("n"); for (String tmpFilePath : tmpArgs) { if (debug) { System.out.print("Counting signatures in " + tmpFilePath + ": "); } final File tmpFile = new File(tmpFilePath); if (!tmpFile.canRead()) { System.err.println("Couldn't read the file. Check the path and permissions: " + tmpFilePath); System.exit(Constants.EXIT_CODE_CANT_READ_FILE); } try { final PdfReader pdfReader = PdfUtils.getPdfReader(tmpFilePath, tmpPasswd); @SuppressWarnings("unchecked") final List<String> sigNames = pdfReader.getAcroFields().getSignatureNames(); if (names) { //print comma-separated names boolean isNotFirst = false; for (String sig : sigNames) { if (isNotFirst) { System.out.println(","); } else { isNotFirst = true; } System.out.println(sig); } } else { //normal processing print only count of signatures System.out.println(sigNames.size()); if (debug) { System.out.println("Signature names: " + sigNames); } } } catch (IOException e) { e.printStackTrace(); System.exit(Constants.EXIT_CODE_COMMON_ERROR); } } } }
From source file:net.sf.jsignpdf.verify.VerifierLogic.java
License:Mozilla Public License
/** * Verifies signature(s) in PDF document. * /*w w w . j ava2s . c o m*/ * @param tmpReader * PdfReader for given PDF * @return */ @SuppressWarnings("unchecked") private VerificationResult verify(final PdfReader tmpReader) { final VerificationResult tmpResult = new VerificationResult(); try { final AcroFields tmpAcroFields = tmpReader.getAcroFields(); final List<String> tmpNames = tmpAcroFields.getSignatureNames(); tmpResult.setTotalRevisions(tmpAcroFields.getTotalRevisions()); final int lastSignatureIdx = tmpNames.size() - 1; if (lastSignatureIdx < 0) { // there is no signature tmpResult.setWithoutSignature(); } for (int i = lastSignatureIdx; i >= 0; i--) { final String name = tmpNames.get(i); final SignatureVerification tmpVerif = new SignatureVerification(name); tmpVerif.setLastSignature(i == lastSignatureIdx); tmpVerif.setWholeDocument(tmpAcroFields.signatureCoversWholeDocument(name)); tmpVerif.setRevision(tmpAcroFields.getRevision(name)); final PdfPKCS7 pk = tmpAcroFields.verifySignature(name); final TimeStampToken tst = pk.getTimeStampToken(); tmpVerif.setTsTokenPresent(tst != null); tmpVerif.setTsTokenValidationResult(validateTimeStampToken(tst)); tmpVerif.setDate(pk.getTimeStampDate() != null ? pk.getTimeStampDate() : pk.getSignDate()); tmpVerif.setLocation(pk.getLocation()); tmpVerif.setReason(pk.getReason()); tmpVerif.setSignName(pk.getSignName()); final Certificate pkc[] = pk.getCertificates(); final X509Name tmpX509Name = PdfPKCS7.getSubjectFields(pk.getSigningCertificate()); tmpVerif.setSubject(tmpX509Name.toString()); tmpVerif.setModified(!pk.verify()); tmpVerif.setOcspPresent(pk.getOcsp() != null); tmpVerif.setOcspValid(pk.isRevocationValid()); tmpVerif.setCrlPresent(pk.getCRLs() != null && pk.getCRLs().size() > 0); tmpVerif.setFails(PdfPKCS7.verifyCertificates(pkc, kall, pk.getCRLs(), tmpVerif.getDate())); tmpVerif.setSigningCertificate(pk.getSigningCertificate()); // generate CertPath List<Certificate> certList = Arrays.asList(pkc); CertificateFactory cf = CertificateFactory.getInstance("X.509"); CertPath cp = cf.generateCertPath(certList); tmpVerif.setCertPath(cp); // to save time - check OCSP in certificate only if document's OCSP is not present and valid if (!tmpVerif.isOcspValid()) { // try to get OCSP url from signing certificate String url = PdfPKCS7.getOCSPURL((X509Certificate) pk.getSigningCertificate()); tmpVerif.setOcspInCertPresent(url != null); if (url != null) { // OCSP url is found in signing certificate - verify certificate with that url tmpVerif.setOcspInCertValid(validateCertificateOCSP(pk.getSignCertificateChain(), url)); } } String certificateAlias = kall.getCertificateAlias(pk.getSigningCertificate()); if (certificateAlias != null) { // this means that signing certificate is directly trusted String verifyCertificate = PdfPKCS7.verifyCertificate(pk.getSigningCertificate(), pk.getCRLs(), tmpVerif.getDate()); if (verifyCertificate == null) { // this means that signing certificate is valid tmpVerif.setSignCertTrustedAndValid(true); } } final InputStream revision = tmpAcroFields.extractRevision(name); try { final PdfReader revisionReader = new PdfReader(revision); tmpVerif.setCertLevelCode(revisionReader.getCertificationLevel()); } finally { if (revision != null) { revision.close(); } } tmpResult.addVerification(tmpVerif); if (failFast && tmpVerif.containsError()) { return tmpResult; } } } catch (Exception e) { tmpResult.setException(e); } return tmpResult; }
From source file:net.sf.jsignpdf.verify.VerifierLogic.java
License:Mozilla Public License
/** * Returns InputStream which contains extracted revision (PDF) which was * signed with signature of given name.// w w w .ja va 2 s . co m * * @param aFileName * @param aPassword * @param aSignatureName * @return * @throws IOException */ public InputStream extractRevision(String aFileName, byte[] aPassword, String aSignatureName) throws IOException { final PdfReader tmpReader = PdfUtils.getPdfReader(aFileName, aPassword); final AcroFields tmpAcroFields = tmpReader.getAcroFields(); return tmpAcroFields.extractRevision(aSignatureName); }
From source file:org.kuali.coeus.propdev.impl.budget.subaward.PropDevPropDevBudgetSubAwardServiceImpl.java
License:Open Source License
/** * extracts XML from PDF//from w ww. j av a 2s .c o m */ protected byte[] getXMLFromPDF(PdfReader reader) throws Exception { XfaForm xfaForm = reader.getAcroFields().getXfa(); Node domDocument = xfaForm.getDomDocument(); if (domDocument == null) return null; Element documentElement = ((Document) domDocument).getDocumentElement(); Element datasetsElement = (Element) documentElement.getElementsByTagNameNS(XFA_NS, "datasets").item(0); Element dataElement = (Element) datasetsElement.getElementsByTagNameNS(XFA_NS, "data").item(0); Element xmlElement = (Element) dataElement.getChildNodes().item(0); Node budgetElement = getBudgetElement(xmlElement); byte[] serializedXML = XfaForm.serializeDoc(budgetElement); return serializedXML; }
From source file:org.kuali.coeus.propdev.impl.s2s.S2sUserAttachedFormServiceImpl.java
License:Open Source License
private List<S2sUserAttachedForm> extractAndPopulateXml(ProposalDevelopmentDocument developmentProposal, PdfReader reader, S2sUserAttachedForm userAttachedForm, Map attachments) throws Exception { List<S2sUserAttachedForm> formBeans = new ArrayList<S2sUserAttachedForm>(); XfaForm xfaForm = reader.getAcroFields().getXfa(); Node domDocument = xfaForm.getDomDocument(); if (domDocument == null) { S2SException s2sException = new S2SException(KeyConstants.S2S_USER_ATTACHED_FORM_WRONG_FILE_TYPE, "Uploaded file is not Grants.Gov fillable form"); s2sException.setTabErrorKey("userAttachedFormsErrors"); throw s2sException; }/* ww w. jav a2 s .co m*/ Element documentElement = ((Document) domDocument).getDocumentElement(); Element datasetsElement = (Element) documentElement.getElementsByTagNameNS(XFA_NS, "datasets").item(0); Element dataElement = (Element) datasetsElement.getElementsByTagNameNS(XFA_NS, "data").item(0); Element grantApplicationElement = (Element) dataElement.getChildNodes().item(0); byte[] serializedXML = XfaForm.serializeDoc(grantApplicationElement); DocumentBuilderFactory domParserFactory = DocumentBuilderFactory.newInstance(); domParserFactory.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder domParser = domParserFactory.newDocumentBuilder(); domParserFactory.setIgnoringElementContentWhitespace(true); ByteArrayInputStream byteArrayInputStream = null; org.w3c.dom.Document document = null; try { byteArrayInputStream = new ByteArrayInputStream(serializedXML); document = domParser.parse(byteArrayInputStream); } finally { if (byteArrayInputStream != null) byteArrayInputStream.close(); } if (document != null) { Element form = null; NodeList elements = document .getElementsByTagNameNS("http://apply.grants.gov/system/MetaGrantApplication", "Forms"); Element element = (Element) elements.item(0); if (element != null) { NodeList formChildren = element.getChildNodes(); int formsCount = formChildren.getLength(); if (formsCount > 1) { NodeList selectedOptionalFormElements = document.getElementsByTagNameNS( "http://apply.grants.gov/system/MetaGrantApplicationWrapper", "SelectedOptionalForms"); int selectedOptionalFormsCount = selectedOptionalFormElements == null ? 0 : selectedOptionalFormElements.getLength(); if (selectedOptionalFormsCount > 0) { Element selectedFormNode = (Element) selectedOptionalFormElements.item(0); NodeList selectedForms = selectedFormNode.getElementsByTagNameNS( "http://apply.grants.gov/system/MetaGrantApplicationWrapper", "FormTagName"); int selectedFormsCount = selectedForms == null ? 0 : selectedForms.getLength(); if (selectedFormsCount > 0) { List seletctedForms = new ArrayList(); for (int j = 0; j < selectedFormsCount; j++) { Element selectedForm = (Element) selectedForms.item(j); String formName = selectedForm.getTextContent(); seletctedForms.add(formName); } List exceptions = new ArrayList(); for (int i = 0; i < formsCount; i++) { form = (Element) formChildren.item(i); String formNodeName = form.getLocalName(); if (seletctedForms.contains(formNodeName)) { try { addForm(developmentProposal, formBeans, form, userAttachedForm, attachments); } catch (UnmarshalException ume) { exceptions.add("Not able to create xml for the form " + formNodeName + " Root Cause:" + ume.getMessage() + "<br>"); } } } if (!exceptions.isEmpty()) throw new S2SException(exceptions.toString()); } } } else { form = (Element) formChildren.item(0); addForm(developmentProposal, formBeans, form, userAttachedForm, attachments); } } else { form = document.getDocumentElement(); addForm(developmentProposal, formBeans, form, userAttachedForm, attachments); } } return formBeans; }
From source file:org.kuali.kra.proposaldevelopment.budget.service.impl.BudgetSubAwardServiceImpl.java
License:Educational Community License
/** * extracts XML from PDF/*www. j a v a 2s. c o m*/ */ protected byte[] getXMLFromPDF(PdfReader reader) throws Exception { XfaForm xfaForm = reader.getAcroFields().getXfa(); Node domDocument = xfaForm.getDomDocument(); if (domDocument == null) throw new Exception("Not a valid pdf form"); Element documentElement = ((Document) domDocument).getDocumentElement(); Element datasetsElement = (Element) documentElement.getElementsByTagNameNS(XFA_NS, "datasets").item(0); Element dataElement = (Element) datasetsElement.getElementsByTagNameNS(XFA_NS, "data").item(0); Element xmlElement = (Element) dataElement.getChildNodes().item(0); Node budgetElement = getBudgetElement(xmlElement); byte[] serializedXML = XfaForm.serializeDoc(budgetElement); return serializedXML; }
From source file:org.kuali.kra.s2s.service.impl.S2SUserAttachedFormServiceImpl.java
License:Educational Community License
private List<S2sUserAttachedForm> extractAndPopulateXml(DevelopmentProposal developmentProposal, PdfReader reader, S2sUserAttachedForm userAttachedForm, Map attachments) throws Exception { List<S2sUserAttachedForm> formBeans = new ArrayList<S2sUserAttachedForm>(); XfaForm xfaForm = reader.getAcroFields().getXfa(); Node domDocument = xfaForm.getDomDocument(); if (domDocument == null) { S2SException s2sException = new S2SException(KeyConstants.S2S_USER_ATTACHED_FORM_WRONG_FILE_TYPE, "Uploaded file is not Grants.Gov fillable form"); s2sException.setTabErrorKey("userAttachedFormsErrors"); throw s2sException; }//from w ww . j a v a 2 s. c o m Element documentElement = ((Document) domDocument).getDocumentElement(); Element datasetsElement = (Element) documentElement.getElementsByTagNameNS(XFA_NS, "datasets").item(0); Element dataElement = (Element) datasetsElement.getElementsByTagNameNS(XFA_NS, "data").item(0); Element grantApplicationElement = (Element) dataElement.getChildNodes().item(0); byte[] serializedXML = XfaForm.serializeDoc(grantApplicationElement); DocumentBuilderFactory domParserFactory = DocumentBuilderFactory.newInstance(); domParserFactory.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder domParser = domParserFactory.newDocumentBuilder(); domParserFactory.setIgnoringElementContentWhitespace(true); ByteArrayInputStream byteArrayInputStream = null; org.w3c.dom.Document document = null; try { byteArrayInputStream = new ByteArrayInputStream(serializedXML); document = domParser.parse(byteArrayInputStream); } finally { if (byteArrayInputStream != null) byteArrayInputStream.close(); } if (document != null) { Element form = null; NodeList elements = document .getElementsByTagNameNS("http://apply.grants.gov/system/MetaGrantApplication", "Forms"); Element element = (Element) elements.item(0); if (element != null) { NodeList formChildren = element.getChildNodes(); int formsCount = formChildren.getLength(); if (formsCount > 1) { //String xpathSelectedForms = "//*[namespace-uri()='http://apply.grants.gov/system/MetaGrantApplicationWrapper' and *[local-name()='SelectedOptionalForms'] " + // "or @*[namespace-uri()='http://apply.grants.gov/system/MetaGrantApplicationWrapper' and *[local-name()='SelectedOptionalForms']]]"; //NodeList selectedFormElements = XPathAPI.selectNodeList(document,xpathSelectedForms); NodeList selectedOptionalFormElements = document.getElementsByTagNameNS( "http://apply.grants.gov/system/MetaGrantApplicationWrapper", "SelectedOptionalForms"); int selectedOptionalFormsCount = selectedOptionalFormElements == null ? 0 : selectedOptionalFormElements.getLength(); if (selectedOptionalFormsCount > 0) { Element selectedFormNode = (Element) selectedOptionalFormElements.item(0); NodeList selectedForms = selectedFormNode.getElementsByTagNameNS( "http://apply.grants.gov/system/MetaGrantApplicationWrapper", "FormTagName"); int selectedFormsCount = selectedForms == null ? 0 : selectedForms.getLength(); if (selectedFormsCount > 0) { List seletctedForms = new ArrayList(); for (int j = 0; j < selectedFormsCount; j++) { Element selectedForm = (Element) selectedForms.item(j); //NodeList selectedFormNames = selectedForm.getElementsByTagNameNS("http://apply.grants.gov/system/MetaGrantApplicationWrapper","Name-Version"); String formName = selectedForm.getTextContent(); seletctedForms.add(formName); } List exceptions = new ArrayList(); for (int i = 0; i < formsCount; i++) { form = (Element) formChildren.item(i); String formNodeName = form.getLocalName(); if (seletctedForms.contains(formNodeName)) { try { addForm(developmentProposal, formBeans, form, userAttachedForm, attachments); } catch (UnmarshalException ume) { exceptions.add("Not able to create xml for the form " + formNodeName + " Root Cause:" + ume.getMessage() + "<br>"); } } } if (!exceptions.isEmpty()) throw new S2SException(exceptions.toString()); } } } else { form = (Element) formChildren.item(0); addForm(developmentProposal, formBeans, form, userAttachedForm, attachments); } } else { form = document.getDocumentElement(); addForm(developmentProposal, formBeans, form, userAttachedForm, attachments); } } return formBeans; }
From source file:org.nuxeo.ecm.platform.signature.core.sign.SignatureServiceImpl.java
License:Open Source License
protected List<X509Certificate> getCertificates(PdfReader pdfReader) throws SignException { List<X509Certificate> pdfCertificates = new ArrayList<X509Certificate>(); AcroFields acroFields = pdfReader.getAcroFields(); @SuppressWarnings("unchecked") List<String> signatureNames = acroFields.getSignatureNames(); for (String signatureName : signatureNames) { PdfPKCS7 pdfPKCS7 = acroFields.verifySignature(signatureName); X509Certificate signingCertificate = pdfPKCS7.getSigningCertificate(); pdfCertificates.add(signingCertificate); }//from w w w . jav a 2 s . c o m return pdfCertificates; }