Example usage for com.lowagie.text.pdf PdfReader getAcroFields

List of usage examples for com.lowagie.text.pdf PdfReader getAcroFields

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfReader getAcroFields.

Prototype

public AcroFields getAcroFields() 

Source Link

Document

Gets a read-only version of AcroFields.

Usage

From source file:org.obiba.onyx.marble.core.service.FdfProducer.java

License:Open Source License

/**
 * Builds a FDF file that can be used to merge with the a consent PDF template.
 * /*  w w w .j  av  a2 s  .c  om*/
 * @param pdfUrl the URL of the PDF file
 * @param acceptUrl the URL to submit the PDF when the consent is accepted
 * @param refuseUrl the URL to submit the PDF when the consent is refused
 * @return a FDF formated byte array.
 * @throws IOException when an unexpected error occurs
 */
public byte[] buildFdf(String pdfUrl, String acceptUrl, String refuseUrl) throws IOException {

    buildReplaceContext(acceptUrl, refuseUrl);

    PdfReader pdfReader = new PdfReader(getPdfTemplate());
    log.debug("PDF template has {} fields.", pdfReader.getAcroFields().getFields().size());

    CustomFdfWriter fdf = new CustomFdfWriter();
    // Initialize the FDF with fields that already have a value.
    fdf.setFields(pdfReader);
    fdf.setFile(pdfUrl);

    try {
        setFields(pdfReader.getAcroFields(), fdf);
    } catch (DocumentException e) {
        log.error("An error occurred during FDF file generation.", e);
        throw new RuntimeException(e);
    }

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    fdf.writeTo(output);
    output.close();
    pdfReader.close();

    return output.toByteArray();
}

From source file:org.obiba.onyx.marble.core.service.impl.DefaultActiveConsentServiceImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
public boolean validateElectronicConsent() {

    byte[] pdfForm = consent.getPdfForm();
    if (pdfForm != null) {

        // Access PDF content with IText library.
        PdfReader reader;
        try {//from  w  ww.  j ava2s  .c om
            reader = new PdfReader(pdfForm);
        } catch (IOException ex) {
            log.error("Could not read PDF consent form", ex);
            throw new RuntimeException(ex);
        }

        // Get the PDF form fields.
        AcroFields form = reader.getAcroFields();

        // Make sure that all mandatory fields have been filled.
        Collection<String> fieldNameList = form.getFields().keySet();
        for (String fieldName : fieldNameList) {
            if (isMandatoryField(form, fieldName)) {
                if (Strings.isEmpty(form.getField(fieldName))) {
                    log.debug("The following mandatory field was not filled in : {}", fieldName);
                    return false;
                }
            }
        }

        return true;

        // Invalid if PDF form does not exist.
    } else {
        return false;
    }
}

From source file:org.obiba.onyx.marble.domain.consent.Consent.java

License:Open Source License

@Transient
public Map<String, String> getPdfFormFields() {
    Map<String, String> pdfFormFields = new HashMap<String, String>();

    if (pdfForm != null) {
        PdfReader reader = getPdfReader();
        AcroFields pdfForm = reader.getAcroFields();
        for (String fieldName : pdfFormFieldNames()) {
            pdfFormFields.put(fieldName, pdfForm.getField(fieldName));
        }//from  w  w  w . j a va2 s.c o m
    }

    return pdfFormFields;
}

From source file:org.obiba.onyx.marble.engine.MarbleModule.java

License:Open Source License

public String getConsentField(Consent consent, String fieldName) {

    byte[] pdfForm = consent.getPdfForm();
    // Access PDF content with IText library.
    PdfReader reader;
    try {/*from  w  w w . j a  va 2 s .c o m*/
        reader = new PdfReader(pdfForm);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }

    // Get the PDF form fields.
    AcroFields form = reader.getAcroFields();
    return form.getField(fieldName);
}

From source file:org.openelis.bean.WorksheetPrintReportBean.java

License:Open Source License

private Path fillPDFWorksheet(Integer worksheetId, String templateName, String userName) throws Exception {
    int i, j, formCapacity, diagramCapacity, pageNumber;
    AcroFields form;/*from  ww  w. j a  va  2  s . c  om*/
    AnalysisViewDO aVDO;
    ArrayList<AnalysisQaEventViewDO> aqeVDOs;
    ArrayList<Integer> analysisIds, qcLotIds;
    ArrayList<NoteViewDO> nVDOs;
    ArrayList<QcAnalyteViewDO> qaVDOs;
    ArrayList<QcLotViewDO> qlVDOs;
    ArrayList<SampleManager1> sMans;
    ArrayList<SampleOrganizationViewDO> sOrgs;
    ArrayList<SampleQaEventViewDO> sqeVDOs;
    ArrayList<SystemVariableDO> sysVars;
    ArrayList<WorksheetAnalysisViewDO> waVDOs;
    ByteArrayOutputStream page;
    Document doc;
    HashMap<Integer, ArrayList<QcAnalyteViewDO>> qaVDOMap;
    HashMap<Integer, ArrayList<WorksheetAnalysisViewDO>> waVDOMap;
    HashMap<Integer, QcLotViewDO> qlMap;
    HashMap<Integer, SampleManager1> sMap;
    OutputStream out;
    Path path;
    PatientDO patDO;
    PdfCopy writer;
    PdfReader reader;
    PdfStamper stamper;
    ProviderDO proDO;
    QcLotViewDO qlVDO;
    RandomAccessFileOrArray original;
    SampleEnvironmentalDO seDO;
    SampleDO sDO;
    SampleItemViewDO siVDO;
    SampleManager1 sMan;
    String collectionDateTime, dirName, now, qcLink;
    StringBuilder aNotes, aQaevents, sNotes, sQaevents;
    WorksheetAnalysisDO waDO1;
    WorksheetItemDO wiDO1;
    WorksheetManager1 wMan;
    WorksheetViewDO wVDO;

    now = ReportUtil.toString(new Date(), Messages.get().dateTimePattern());

    dirName = "";
    try {
        sysVars = systemVariable.fetchByName("worksheet_template_directory", 1);
        if (sysVars.size() > 0)
            dirName = ((SystemVariableDO) sysVars.get(0)).getValue();
    } catch (Exception anyE) {
        throw new Exception("Error retrieving temp directory variable: " + anyE.getMessage());
    }

    analysisIds = new ArrayList<Integer>();
    qcLotIds = new ArrayList<Integer>();
    waVDOMap = new HashMap<Integer, ArrayList<WorksheetAnalysisViewDO>>();
    wMan = worksheetManager.fetchById(worksheetId, WorksheetManager1.Load.DETAIL,
            WorksheetManager1.Load.REAGENT);
    for (WorksheetAnalysisViewDO data : WorksheetManager1Accessor.getAnalyses(wMan)) {
        waVDOs = waVDOMap.get(data.getWorksheetItemId());
        if (waVDOs == null) {
            waVDOs = new ArrayList<WorksheetAnalysisViewDO>();
            waVDOMap.put(data.getWorksheetItemId(), waVDOs);
        }
        waVDOs.add(data);

        if (data.getAnalysisId() != null)
            analysisIds.add(data.getAnalysisId());
        else if (data.getQcLotId() != null)
            qcLotIds.add(data.getQcLotId());
    }

    sMap = new HashMap<Integer, SampleManager1>();
    if (analysisIds.size() > 0) {
        sMans = sampleManager.fetchByAnalyses(analysisIds, SampleManager1.Load.ORGANIZATION,
                SampleManager1.Load.QA, SampleManager1.Load.NOTE, SampleManager1.Load.SINGLEANALYSIS,
                SampleManager1.Load.PROVIDER);
        for (SampleManager1 data : sMans) {
            for (AnalysisViewDO data1 : SampleManager1Accessor.getAnalyses(data))
                sMap.put(data1.getId(), data);
        }
    }

    qaVDOMap = new HashMap<Integer, ArrayList<QcAnalyteViewDO>>();
    qlMap = new HashMap<Integer, QcLotViewDO>();
    if (qcLotIds.size() > 0) {
        qlVDOs = qcLot.fetchByIds(qcLotIds);
        for (QcLotViewDO data : qlVDOs) {
            qlMap.put(data.getId(), data);
            try {
                qaVDOs = qcAnalyte.fetchByQcId(data.getQcId());
                qaVDOMap.put(data.getQcId(), qaVDOs);
            } catch (NotFoundException nfE) {
                // ignore this error as leaving the hash record blank will not
                // cause an error due to a null check later on in the code
            }
        }
    }

    formCapacity = 1;
    out = null;
    try {
        path = ReportUtil.createTempFile("worksheetPrint", ".pdf", null);
        out = Files.newOutputStream(path);

        reader = new PdfReader(dirName + "OEWorksheet" + templateName + ".pdf");
        original = reader.getSafeFile();

        form = reader.getAcroFields();
        if (form.getField("capacity") != null)
            formCapacity = Integer.parseInt(form.getField("capacity"));
        if (form.getField("diagram_capacity") != null)
            diagramCapacity = Integer.parseInt(form.getField("diagram_capacity"));
        else
            diagramCapacity = formCapacity;

        doc = new Document(reader.getPageSizeWithRotation(1));
        writer = new PdfCopy(doc, out);
        doc.open();
        reader.close();

        i = -1;
        pageNumber = -1;
        form = null;
        page = null;
        stamper = null;
        wVDO = wMan.getWorksheet();
        for (WorksheetItemDO wiDO : WorksheetManager1Accessor.getItems(wMan)) {
            j = wiDO.getPosition() % diagramCapacity;
            if (j == 0)
                j = diagramCapacity;
            for (WorksheetAnalysisViewDO waVDO : waVDOMap.get(wiDO.getId())) {
                if (i == -1 || i > formCapacity || j > diagramCapacity) {
                    if (i != -1) {
                        fillReagentFields(form, wMan);
                        stamper.setFormFlattening(true);
                        renameFields(form, pageNumber);
                        flattenFilledFields(stamper, form, formCapacity, pageNumber);
                        stamper.close();
                        reader.close();
                        reader = new PdfReader(page.toByteArray());
                        writer.addPage(writer.getImportedPage(reader, 1));
                        reader.close();
                    }
                    reader = new PdfReader(original, null);
                    page = new ByteArrayOutputStream();
                    stamper = new PdfStamper(reader, page);
                    form = stamper.getAcroFields();
                    i = 1;
                    pageNumber++;

                    form.setField("current_date_time", now);
                    form.setField("username", userName);
                    form.setField("worksheet_description_1", wVDO.getDescription());
                }

                qcLink = "";
                if (waVDO.getWorksheetAnalysisId() != null) {
                    try {
                        waDO1 = worksheetAnalysis.fetchById(waVDO.getWorksheetAnalysisId());
                        wiDO1 = worksheetItem.fetchById(waDO1.getWorksheetItemId());
                        qcLink = waDO1.getAccessionNumber() + " (" + wiDO1.getPosition() + ")";
                    } catch (Exception anyE) {
                        log.log(Level.SEVERE, anyE.getMessage(), anyE);
                    }
                }

                form.setField("worksheet_id_" + (i), wVDO.getId().toString());
                form.setField("created_date_" + (i),
                        ReportUtil.toString(wVDO.getCreatedDate(), Messages.get().dateTimePattern()));
                if (waVDOMap.get(wiDO.getId()).indexOf(waVDO) == 0)
                    form.setField("position_" + (i), wiDO.getPosition().toString());

                if (waVDO.getAnalysisId() != null) {
                    sMan = sMap.get(waVDO.getAnalysisId());
                    sDO = sMan.getSample();
                    patDO = null;
                    proDO = null;
                    seDO = null;
                    if (Constants.domain().CLINICAL.equals(sDO.getDomain())) {
                        patDO = sMan.getSampleClinical().getPatient();
                        proDO = sMan.getSampleClinical().getProvider();
                    } else if (Constants.domain().NEONATAL.equals(sDO.getDomain())) {
                        patDO = sMan.getSampleNeonatal().getPatient();
                        proDO = sMan.getSampleNeonatal().getProvider();
                    } else if (Constants.domain().ENVIRONMENTAL.equals(sDO.getDomain())) {
                        seDO = sMan.getSampleEnvironmental();
                    }
                    sOrgs = SampleManager1Accessor.getOrganizations(sMan);
                    aVDO = (AnalysisViewDO) sMan.getObject(Constants.uid().getAnalysis(waVDO.getAnalysisId()));
                    siVDO = (SampleItemViewDO) sMan
                            .getObject(Constants.uid().getSampleItem(aVDO.getSampleItemId()));

                    sQaevents = new StringBuilder();
                    sqeVDOs = SampleManager1Accessor.getSampleQAs(sMan);
                    if (sqeVDOs != null && sqeVDOs.size() > 0) {
                        for (SampleQaEventViewDO sqeVDO : sqeVDOs) {
                            if (sQaevents.length() > 0)
                                sQaevents.append(" | ");
                            sQaevents.append(sqeVDO.getQaEventName());
                        }
                    }

                    aQaevents = new StringBuilder();
                    aqeVDOs = SampleManager1Accessor.getAnalysisQAs(sMan);
                    if (aqeVDOs != null && aqeVDOs.size() > 0) {
                        for (AnalysisQaEventViewDO aqeVDO : aqeVDOs) {
                            if (!waVDO.getAnalysisId().equals(aqeVDO.getAnalysisId()))
                                continue;
                            if (aQaevents.length() > 0)
                                aQaevents.append(" | ");
                            aQaevents.append(aqeVDO.getQaEventName());
                        }
                    }

                    sNotes = new StringBuilder();
                    nVDOs = new ArrayList<NoteViewDO>();
                    if (SampleManager1Accessor.getSampleInternalNotes(sMan) != null)
                        nVDOs.addAll(SampleManager1Accessor.getSampleInternalNotes(sMan));
                    if (SampleManager1Accessor.getSampleExternalNote(sMan) != null)
                        nVDOs.add(SampleManager1Accessor.getSampleExternalNote(sMan));
                    if (nVDOs != null && nVDOs.size() > 0) {
                        for (NoteViewDO nVDO : nVDOs) {
                            if (sNotes.length() > 0)
                                sNotes.append(" | ");
                            sNotes.append(nVDO.getText());
                        }
                    }

                    aNotes = new StringBuilder();
                    nVDOs = new ArrayList<NoteViewDO>();
                    if (SampleManager1Accessor.getAnalysisInternalNotes(sMan) != null)
                        nVDOs.addAll(SampleManager1Accessor.getAnalysisInternalNotes(sMan));
                    if (SampleManager1Accessor.getAnalysisExternalNotes(sMan) != null)
                        nVDOs.addAll(SampleManager1Accessor.getAnalysisExternalNotes(sMan));
                    if (nVDOs != null && nVDOs.size() > 0) {
                        for (NoteViewDO nVDO : nVDOs) {
                            if (!waVDO.getAnalysisId().equals(nVDO.getReferenceId()))
                                continue;
                            if (aNotes.length() > 0)
                                aNotes.append(" | ");
                            aNotes.append(nVDO.getText());
                        }
                    }

                    if (waVDOMap.get(wiDO.getId()).size() > 1)
                        form.setField("well_label_" + (j), wiDO.getPosition().toString());
                    else
                        form.setField("well_label_" + (j), sDO.getAccessionNumber().toString());
                    form.setField("accession_number_" + (i), sDO.getAccessionNumber().toString());
                    form.setField("qc_link_" + (i), qcLink);
                    if (sDO.getCollectionDate() != null) {
                        collectionDateTime = ReportUtil.toString(sDO.getCollectionDate(),
                                Messages.get().datePattern());
                        if (sDO.getCollectionTime() != null) {
                            collectionDateTime += " ";
                            collectionDateTime += ReportUtil.toString(sDO.getCollectionTime(),
                                    Messages.get().timePattern());
                        }
                        form.setField("collection_date_" + (i), collectionDateTime);
                    }
                    form.setField("received_date_" + (i),
                            ReportUtil.toString(sDO.getReceivedDate(), Messages.get().dateTimePattern()));
                    if (patDO != null) {
                        form.setField("patient_last_" + (i), patDO.getLastName());
                        form.setField("patient_first_" + (i), patDO.getFirstName());
                    }
                    if (proDO != null) {
                        form.setField("provider_last_" + (i), proDO.getLastName());
                        form.setField("provider_first_" + (i), proDO.getFirstName());
                    }
                    if (seDO != null) {
                        form.setField("env_location_" + (i), seDO.getLocation());
                        form.setField("env_description_" + (i), seDO.getDescription());
                    }
                    if (sOrgs != null && sOrgs.size() > 0) {
                        for (SampleOrganizationViewDO soVDO : sOrgs) {
                            if (Constants.dictionary().ORG_REPORT_TO.equals(soVDO.getTypeId()))
                                form.setField("organization_name_" + (i), soVDO.getOrganizationName());
                            else if (Constants.dictionary().ORG_BILL_TO.equals(soVDO.getTypeId()))
                                form.setField("bill_to_name_" + (i), soVDO.getOrganizationName());
                        }
                    }
                    form.setField("type_of_sample_" + (i), siVDO.getTypeOfSample());
                    form.setField("source_of_sample_" + (i), siVDO.getSourceOfSample());
                    form.setField("source_other_" + (i), siVDO.getSourceOther());
                    form.setField("container_reference_" + (i), siVDO.getContainerReference());
                    form.setField("test_" + (i), aVDO.getTestName());
                    form.setField("method_" + (i), aVDO.getMethodName());
                    form.setField("sample_qaevent_" + (i), sQaevents.toString());
                    form.setField("analysis_qaevent_" + (i), aQaevents.toString());
                    form.setField("sample_note_" + (i), sNotes.toString());
                    form.setField("analysis_note_" + (i), aNotes.toString());
                } else if (waVDO.getQcLotId() != null) {
                    qlVDO = qlMap.get(waVDO.getQcLotId());
                    form.setField("well_label_" + (j), qlVDO.getQcName());
                    form.setField("qc_link_" + (i), qcLink);
                    form.setField("qc_name_" + (i), qlVDO.getQcName());
                    form.setField("qc_lot_" + (i), qlVDO.getLotNumber());
                    form.setField("qc_usable_" + (i),
                            ReportUtil.toString(qlVDO.getUsableDate(), Messages.get().dateTimePattern()));
                    form.setField("qc_expiration_" + (i),
                            ReportUtil.toString(qlVDO.getExpireDate(), Messages.get().dateTimePattern()));
                    qaVDOs = qaVDOMap.get(qlVDO.getQcId());
                    if (qaVDOs != null && !qaVDOs.isEmpty())
                        form.setField("qc_expected_value_" + (i), qaVDOs.get(0).getValue());
                }
                i++;
            }
        }
        fillReagentFields(form, wMan);
        stamper.setFormFlattening(true);
        renameFields(form, pageNumber);
        flattenFilledFields(stamper, form, formCapacity, pageNumber);
        stamper.close();
        reader.close();

        reader = new PdfReader(page.toByteArray());
        writer.addPage(writer.getImportedPage(reader, 1));
        doc.close();
        reader.close();
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (Exception e) {
            log.severe("Could not close output stream for worksheet print report");
        }
    }
    return path;
}

From source file:org.opensignature.opensignpdf.tools.Pkcs7Extractor.java

License:Open Source License

/**
 * @param args/*from  www .  j  av a2s  . c o  m*/
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    try {
        if (args.length < 1) {
            System.out.println("Usage: EstraiPkcs7 <pdf file relative to current dir>");
            System.exit(1);
        }
        String filename = args[0];

        PdfReader reader = new PdfReader(filename);
        AcroFields af = reader.getAcroFields();
        ArrayList names = af.getSignatureNames();
        for (int k = 0; k < names.size(); ++k) {
            String name = (String) names.get(k);
            System.out.println("Signature name: " + name);
            System.out.println("Signature covers whole document: " + af.signatureCoversWholeDocument(name));
            System.out.println("Document revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());
            // Start revision extraction
            // FileOutputStream out = new FileOutputStream("revision_" +
            // af.getRevision(name) + ".pdf");
            // byte bb[] = new byte[8192];
            // InputStream ip = af.extractRevision(name);
            // int n = 0;
            // while ((n = ip.read(bb)) > 0)
            // out.write(bb, 0, n);
            // out.close();
            // ip.close();
            // End revision extraction

            // PdfPKCS7 pk = af.verifySignature(name);

            PdfDictionary v = af.getSignatureDictionary(name);

            PdfString contents = (PdfString) PdfReader.getPdfObject(v.get(PdfName.CONTENTS));

            // Start pkcs7 extraction
            FileOutputStream fos = new FileOutputStream(filename + "_signeddata_" + name + ".pk7");
            System.out.println(k + ") Estrazione pkcs7: " + filename + "_signeddata_" + name + ".pk7");
            fos.write(contents.getOriginalBytes());
            fos.flush();
            fos.close();
            // End pkcs7 extraction

            /* Commentato per evitare dipendenze da BC
            Security.insertProviderAt(new BouncyCastleProvider(), 3);
                    
            // nota: dipendenza da provider BC per "SHA1withRSA"
            PdfPKCS7 pk = new PdfPKCS7(contents.getOriginalBytes(), "BC");
                    
                    
                    
            Calendar cal = pk.getSignDate();
            Certificate pkc[] = pk.getCertificates();
            System.out.println("Got " + pkc.length
                + " certificates from pdf");
            System.out
                .println("Subject of signer: "
                        + PdfPKCS7.getSubjectFields(pk
                                .getSigningCertificate()));
            // System.out.println("Document modified: " + !pk.verify());
            // Object fails[] = PdfPKCS7.verifyCertificates(pkc, kall, null,
            // cal);
            // if (fails == null)
            // System.out.println("Certificates verified against the
            // KeyStore");
            // else
            // System.out.println("Certificate failed: " + fails[1]);
                     
            */
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    }

    /* decommentare se si riabilita la parte relativa a PdfPKCS7 nel main
            
    catch (InvalidKeyException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (SecurityException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (CRLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (CertificateException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (NoSuchProviderException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    */

}

From source file:org.signserver.module.pdfsigner.PDFSigner.java

License:Open Source License

protected byte[] addSignatureToPDFDocument(final ICryptoInstance crypto, PDFSignerParameters params,
        byte[] pdfbytes, byte[] password, int contentEstimated, final ProcessRequest request,
        final RequestContext context) throws IOException, DocumentException, CryptoTokenOfflineException,
        SignServerException, IllegalRequestException {
    // when given a content length (i.e. non-zero), it means we are running a second try
    boolean secondTry = contentEstimated != 0;

    // get signing cert certificate chain and private key
    final List<Certificate> certs = getSigningCertificateChain(crypto);
    if (certs == null) {
        throw new SignServerException("Null certificate chain. This signer needs a certificate.");
    }/*from  ww  w . ja  v  a  2  s  . c o m*/
    final List<Certificate> includedCerts = includedCertificates(certs);
    Certificate[] certChain = includedCerts.toArray(new Certificate[includedCerts.size()]);
    PrivateKey privKey = crypto.getPrivateKey();

    // need to check digest algorithms for DSA private key at signing
    // time since we can't be sure what key a configured alias selector gives back
    if (privKey instanceof DSAPrivateKey) {
        if (!"SHA1".equals(digestAlgorithm)) {
            throw new IllegalRequestException(
                    "Only SHA1 is permitted as digest algorithm for DSA private keys");
        }
    }

    PdfReader reader = new PdfReader(pdfbytes, password);
    boolean appendMode = true; // TODO: This could be good to have as a property in the future

    int pdfVersion;

    try {
        pdfVersion = Integer.parseInt(Character.toString(reader.getPdfVersion()));
    } catch (NumberFormatException e) {
        pdfVersion = 0;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("PDF version: " + pdfVersion);
    }

    // Don't certify already certified documents
    if (reader.getCertificationLevel() != PdfSignatureAppearance.NOT_CERTIFIED
            && params.getCertification_level() != PdfSignatureAppearance.NOT_CERTIFIED) {
        throw new IllegalRequestException("Will not certify an already certified document");
    }

    // Don't sign documents where the certification does not allow it
    if (reader.getCertificationLevel() == PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED
            || reader.getCertificationLevel() == PdfSignatureAppearance.CERTIFIED_FORM_FILLING) {
        throw new IllegalRequestException("Will not sign a certified document where signing is not allowed");
    }

    Permissions currentPermissions = Permissions.fromInt(reader.getPermissions());

    if (params.getSetPermissions() != null && params.getRemovePermissions() != null) {
        throw new SignServerException("Signer " + workerId + " missconfigured. Only one of " + SET_PERMISSIONS
                + " and " + REMOVE_PERMISSIONS + " should be specified.");
    }

    Permissions newPermissions;
    if (params.getSetPermissions() != null) {
        newPermissions = params.getSetPermissions();
    } else if (params.getRemovePermissions() != null) {
        newPermissions = currentPermissions.withRemoved(params.getRemovePermissions());
    } else {
        newPermissions = null;
    }

    Permissions rejectPermissions = Permissions.fromSet(params.getRejectPermissions());
    byte[] userPassword = reader.computeUserPassword();
    int cryptoMode = reader.getCryptoMode();
    if (LOG.isDebugEnabled()) {
        StringBuilder buff = new StringBuilder();
        buff.append("Current permissions: ").append(currentPermissions).append("\n")
                .append("Remove permissions: ").append(params.getRemovePermissions()).append("\n")
                .append("Reject permissions: ").append(rejectPermissions).append("\n")
                .append("New permissions: ").append(newPermissions).append("\n").append("userPassword: ")
                .append(userPassword == null ? "null" : "yes").append("\n").append("ownerPassword: ")
                .append(password == null ? "no" : (isUserPassword(reader, password) ? "no" : "yes"))
                .append("\n").append("setOwnerPassword: ")
                .append(params.getSetOwnerPassword() == null ? "no" : "yes").append("\n").append("cryptoMode: ")
                .append(cryptoMode);
        LOG.debug(buff.toString());
    }

    if (appendMode && (newPermissions != null || params.getSetOwnerPassword() != null)) {
        appendMode = false;
        if (LOG.isDebugEnabled()) {
            LOG.debug("Changing appendMode to false to be able to change permissions");
        }
    }

    ByteArrayOutputStream fout = new ByteArrayOutputStream();

    // increase PDF version if needed by digest algorithm
    final char updatedPdfVersion;
    if (minimumPdfVersion > pdfVersion) {
        updatedPdfVersion = Character.forDigit(minimumPdfVersion, 10);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Need to upgrade PDF to version 1." + updatedPdfVersion);
        }

        // check that the document isn't already signed 
        // when trying to upgrade version
        final AcroFields af = reader.getAcroFields();
        final List<String> sigNames = af.getSignatureNames();

        if (!sigNames.isEmpty()) {
            // TODO: in the future we might want to support
            // a fallback option in this case to allow re-signing using the same version (using append)
            throw new IllegalRequestException(
                    "Can not upgrade an already signed PDF and a higher version is required to support the configured digest algorithm");
        }

        appendMode = false;
    } else {
        updatedPdfVersion = '\0';
    }

    PdfStamper stp = PdfStamper.createSignature(reader, fout, updatedPdfVersion, null, appendMode);
    PdfSignatureAppearance sap = stp.getSignatureAppearance();

    // Set the new permissions
    if (newPermissions != null || params.getSetOwnerPassword() != null) {
        if (cryptoMode < 0) {
            cryptoMode = PdfWriter.STANDARD_ENCRYPTION_128;
            if (LOG.isDebugEnabled()) {
                LOG.debug("Setting default encryption algorithm");
            }
        }
        if (newPermissions == null) {
            newPermissions = currentPermissions;
        }
        if (params.getSetOwnerPassword() != null) {
            password = params.getSetOwnerPassword().getBytes("ISO-8859-1");
        } else if (isUserPassword(reader, password)) {
            // We do not have an owner password so lets use a random one
            password = new byte[16];
            random.nextBytes(password);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Setting random owner password");
            }
        }
        stp.setEncryption(userPassword, password, newPermissions.asInt(), cryptoMode);
        currentPermissions = newPermissions;
    }

    // Reject if any permissions are rejected and the document does not use a permission password
    // or if it contains any of the rejected permissions
    if (rejectPermissions.asInt() != 0) {
        if (cryptoMode < 0 || currentPermissions.containsAnyOf(rejectPermissions)) {
            throw new IllegalRequestException("Document contains permissions not allowed by this signer");
        }
    }

    // include signer certificate crl inside cms package if requested
    CRL[] crlList = null;
    if (params.isEmbed_crl()) {
        crlList = getCrlsForChain(certs);
    }
    sap.setCrypto(null, certChain, crlList, PdfSignatureAppearance.SELF_SIGNED);

    // add visible signature if requested
    if (params.isAdd_visible_signature()) {
        int signaturePage = getPageNumberForSignature(reader, params);
        sap.setVisibleSignature(new com.lowagie.text.Rectangle(params.getVisible_sig_rectangle_llx(),
                params.getVisible_sig_rectangle_lly(), params.getVisible_sig_rectangle_urx(),
                params.getVisible_sig_rectangle_ury()), signaturePage, null);

        // set custom image if requested
        if (params.isUse_custom_image()) {
            sap.setAcro6Layers(true);
            PdfTemplate n2 = sap.getLayer(2);
            params.getCustom_image().setAbsolutePosition(0, 0);
            n2.addImage(params.getCustom_image());
        }
    }

    // Certification level
    sap.setCertificationLevel(params.getCertification_level());

    PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached"));
    dic.setReason(params.getReason());
    dic.setLocation(params.getLocation());
    dic.setDate(new PdfDate(Calendar.getInstance()));

    sap.setCryptoDictionary(dic);

    // add timestamp to signature if requested
    TSAClient tsc = null;
    if (params.isUse_timestamp()) {
        final String tsaUrl = params.getTsa_url();

        if (tsaUrl != null) {
            tsc = getTimeStampClient(params.getTsa_url(), params.getTsa_username(), params.getTsa_password());
        } else {
            tsc = new InternalTSAClient(getWorkerSession(), params.getTsa_worker(), params.getTsa_username(),
                    params.getTsa_password());
        }
    }

    // embed ocsp response in cms package if requested
    // for ocsp request to be formed there needs to be issuer certificate in
    // chain
    byte[] ocsp = null;
    if (params.isEmbed_ocsp_response() && certChain.length >= 2) {
        String url;
        try {
            url = PdfPKCS7.getOCSPURL((X509Certificate) certChain[0]);
            if (url != null && url.length() > 0) {
                ocsp = new OcspClientBouncyCastle((X509Certificate) certChain[0],
                        (X509Certificate) certChain[1], url).getEncoded();
            }
        } catch (CertificateParsingException e) {
            throw new SignServerException("Error getting OCSP URL from certificate", e);
        }

    }

    PdfPKCS7 sgn;
    try {
        sgn = new PdfPKCS7(privKey, certChain, crlList, digestAlgorithm, null, false);
    } catch (InvalidKeyException e) {
        throw new SignServerException("Error constructing PKCS7 package", e);
    } catch (NoSuchProviderException e) {
        throw new SignServerException("Error constructing PKCS7 package", e);
    } catch (NoSuchAlgorithmException e) {
        throw new SignServerException("Error constructing PKCS7 package", e);
    }

    MessageDigest messageDigest;
    try {
        messageDigest = MessageDigest.getInstance(digestAlgorithm);
    } catch (NoSuchAlgorithmException e) {
        throw new SignServerException("Error creating " + digestAlgorithm + " digest", e);
    }

    Calendar cal = Calendar.getInstance();

    // calculate signature size
    if (contentEstimated == 0) {
        contentEstimated = calculateEstimatedSignatureSize(certChain, tsc, ocsp, crlList);
    }

    byte[] encodedSig = calculateSignature(sgn, contentEstimated, messageDigest, cal, params, certChain, tsc,
            ocsp, sap);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Estimated size: " + contentEstimated);
        LOG.debug("Encoded length: " + encodedSig.length);
    }

    if (contentEstimated + 2 < encodedSig.length) {
        if (!secondTry) {
            int contentExact = encodedSig.length;
            LOG.warn(
                    "Estimated signature size too small, usinging accurate calculation (resulting in an extra signature computation).");

            if (LOG.isDebugEnabled()) {
                LOG.debug("Estimated size: " + contentEstimated + ", actual size: " + contentExact);
            }

            // try signing again
            return addSignatureToPDFDocument(crypto, params, pdfbytes, password, contentExact, request,
                    context);
        } else {
            // if we fail to get an accurate signature size on the second attempt, bail out (this shouldn't happen)
            throw new SignServerException("Failed to calculate signature size");
        }
    }

    byte[] paddedSig = new byte[contentEstimated];
    System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);

    PdfDictionary dic2 = new PdfDictionary();
    dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
    sap.close(dic2);
    reader.close();

    fout.close();
    return fout.toByteArray();
}

From source file:org.webpki.pdf.PDFVerifier.java

License:Apache License

public void verifyDocumentSignature(byte[] indoc) throws IOException {
    try {// ww w. ja va  2  s.c  o m
        PdfReader reader = new PdfReader(indoc);
        AcroFields af = reader.getAcroFields();
        ArrayList<?> names = af.getSignatureNames();
        for (int k = 0; k < names.size(); ++k) {
            String name = (String) names.get(k);
            whole_doc_signature = af.signatureCoversWholeDocument(name);
            if ((stop_on_index && k == stop_index) || (!stop_on_index && whole_doc_signature)) {
                signature_name = name;
                document_revision = af.getRevision(name);
                ByteArrayOutputStream bout = new ByteArrayOutputStream(8192);
                byte buffer[] = new byte[8192];
                InputStream ip = af.extractRevision(name);
                int n = 0;
                while ((n = ip.read(buffer)) > 0) {
                    bout.write(buffer, 0, n);
                }
                bout.close();
                ip.close();
                file_data = bout.toByteArray();
                PdfPKCS7 pk = af.verifySignature(name);
                signing_time = pk.getSignDate().getTime();
                X509Certificate pkc[] = (X509Certificate[]) pk.getCertificates();
                is_modified = !pk.verify();
                X509Certificate cert = pk.getSigningCertificate();
                for (int q = 0; q < pkc.length; q++) {
                    if (cert.equals(pkc[q])) {
                        verifier.verifyCertificatePath(CertificateUtil.getSortedPath(pkc));
                        return;
                    }
                }
                throw new IOException("Signature certificate not found in path");
            }
        }
        if (stop_on_index) {
            throw new IOException("Signature with index " + stop_index + " not found");
        }
        throw new IOException("No whole-document signature found");
    } catch (GeneralSecurityException gse) {
        throw new IOException(gse.getMessage());
    }
}

From source file:questions.forms.GetTextFields.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    try {/*from  www .j  a  v  a 2s .  co m*/
        PrintStream out = new PrintStream(new File(RESULT));

        PdfLister lister = new PdfLister(out);

        PdfReader reader = new PdfReader(RESOURCE);

        PdfDictionary root = reader.getCatalog();
        PdfDictionary acroform = root.getAsDict(PdfName.ACROFORM);

        out.println("These are the form's font dictionaries:");
        PdfDictionary fonts = acroform.getAsDict(PdfName.DR).getAsDict(PdfName.FONT);
        for (PdfName key : (Set<PdfName>) fonts.getKeys()) {
            lister.listDict((PdfDictionary) PdfReader.getPdfObject(fonts.get(key)));
        }
        out.println("--------------");

        out.println("This is the default appearance for the complete form:");
        lister.listAnyObject(PdfReader.getPdfObject(acroform.get(PdfName.DA)));
        out.println("--------------");

        AcroFields form = reader.getAcroFields();
        Map<String, Item> fields = form.getFields();
        Item item;
        for (String name : fields.keySet()) {
            out.println(name);
            if (form.getFieldType(name) == AcroFields.FIELD_TYPE_TEXT) {
                item = form.getFieldItem(name);
                PdfDictionary dict = (PdfDictionary) item.getMerged(0);

                out.println("This is the field's font dictionary:");
                fonts = dict.getAsDict(PdfName.DR).getAsDict(PdfName.FONT);
                for (PdfName key : (Set<PdfName>) fonts.getKeys()) {
                    lister.listDict((PdfDictionary) PdfReader.getPdfObject(fonts.get(key)));
                }
                out.println("---");
                out.println("This is the field's default appearance");
                lister.listAnyObject(PdfReader.getPdfObject(dict.get(PdfName.DA)));
            } else {
                out.println("NOT A TEXT FIELD!");
            }
            out.println("--------------");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:questions.forms.MultipleChoice.java

public static void readList() throws IOException {
    PdfReader reader = new PdfReader(RESULT);
    AcroFields form = reader.getAcroFields();
    String[] selection = form.getListSelection("iText");
    for (int i = 0; i < selection.length; i++) {
        System.out.println(selection[i]);
    }//from w ww .jav a2 s  .com
}