Example usage for com.lowagie.text.pdf PdfDictionary getAsDict

List of usage examples for com.lowagie.text.pdf PdfDictionary getAsDict

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfDictionary getAsDict.

Prototype

public PdfDictionary getAsDict(PdfName key) 

Source Link

Document

Returns a PdfObject as a PdfDictionary, resolving indirect references.

Usage

From source file:es.gob.afirma.signers.pades.ltv.PdfDocumentSecurityStore.java

License:Open Source License

/** Constructor para inicializar la clase con una estructura DSS ya creada.
 * @param dss Diccionario DSS//  w  w  w .j  av a 2  s .c o  m
 * @throws IOException En caso de errores de entrada / salida */
PdfDocumentSecurityStore(final PdfDictionary dss) throws IOException {
    int i = 0;
    PdfArray arrayCerts = dss.getAsArray(new PdfName(PDF_NAME_CERTS));
    if (arrayCerts != null) {
        for (final Iterator<PdfObject> iterator = arrayCerts.listIterator(); iterator.hasNext();) {
            final PdfIndirectReference reference = (PdfIndirectReference) iterator.next();
            this.certificates.put(Integer.valueOf(i),
                    getContentBytesFromContentObject(PdfReader.getPdfObject(reference)));
            i++;
        }

    }
    PdfArray arrayOcsps = dss.getAsArray(new PdfName(PDF_NAME_OCSPS));
    if (arrayOcsps != null) {
        i = 0;
        for (final Iterator<PdfObject> iterator = arrayOcsps.listIterator(); iterator.hasNext();) {
            final PdfIndirectReference reference = (PdfIndirectReference) iterator.next();
            this.ocsps.put(Integer.valueOf(i),
                    getContentBytesFromContentObject(PdfReader.getPdfObject(reference)));
            i++;
        }

    }
    PdfArray arrayCrls = dss.getAsArray(new PdfName(PDF_NAME_CRLS));
    if (arrayCrls != null) {
        i = 0;
        for (final Iterator<PdfObject> iterator = arrayCrls.listIterator(); iterator.hasNext();) {
            final PdfIndirectReference reference = (PdfIndirectReference) iterator.next();
            this.crls.put(Integer.valueOf(i),
                    getContentBytesFromContentObject(PdfReader.getPdfObject(reference)));
            i++;
        }

    }
    final PdfDictionary vri = dss.getAsDict(new PdfName(PDF_NAME_VRI));
    if (vri != null) {
        PdfName key;
        ValidationInformation val;
        for (final Iterator<PdfName> iterator = vri.getKeys().iterator(); iterator.hasNext(); this.signatures
                .put(key.toString().substring(1), val)) {
            key = iterator.next();
            final PdfDictionary vriEntry = vri.getAsDict(key);
            arrayCerts = vriEntry.getAsArray(new PdfName(PDF_NAME_CERT));
            int certId[];
            if (arrayCerts != null) {
                certId = new int[arrayCerts.size()];
                for (i = 0; i < arrayCerts.size(); i++) {
                    final PdfIndirectReference reference = (PdfIndirectReference) arrayCerts.getPdfObject(i);
                    final byte referenceBytes[] = getContentBytesFromContentObject(
                            PdfReader.getPdfObject(reference));
                    final Iterator<Integer> iteratorKeys = this.certificates.keySet().iterator();
                    do {
                        if (!iteratorKeys.hasNext()) {
                            break;
                        }
                        final int index = iteratorKeys.next().intValue();
                        if (Arrays.equals(referenceBytes, this.certificates.get(Integer.valueOf(index)))) {
                            certId[i] = index;
                        }
                    } while (true);
                }

            } else {
                certId = new int[0];
            }
            arrayOcsps = vriEntry.getAsArray(new PdfName(PDF_NAME_OCSP));
            int ocspId[];
            if (arrayOcsps != null) {
                ocspId = new int[arrayOcsps.size()];
                i = 0;
                for (final Iterator<PdfObject> iteratorOcsps = arrayOcsps.listIterator(); iteratorOcsps
                        .hasNext();) {
                    final PdfIndirectReference reference = (PdfIndirectReference) iteratorOcsps.next();
                    final byte referenceBytes[] = getContentBytesFromContentObject(
                            PdfReader.getPdfObject(reference));
                    final Iterator<Integer> iteratorKeys = this.ocsps.keySet().iterator();
                    do {
                        if (!iteratorKeys.hasNext()) {
                            break;
                        }
                        final int index = iteratorKeys.next().intValue();
                        if (Arrays.equals(referenceBytes, this.ocsps.get(Integer.valueOf(index)))) {
                            ocspId[i] = index;
                        }
                    } while (true);
                    i++;
                }

            } else {
                ocspId = new int[0];
            }
            arrayCrls = vriEntry.getAsArray(new PdfName(PDF_NAME_CRL));
            int crlId[];
            if (arrayCrls != null) {
                crlId = new int[arrayCrls.size()];
                i = 0;
                for (final Iterator<PdfObject> iteratorCRLs = arrayCrls.listIterator(); iteratorCRLs
                        .hasNext();) {
                    final PdfIndirectReference reference = (PdfIndirectReference) iteratorCRLs.next();
                    final byte referenceBytes[] = getContentBytesFromContentObject(
                            PdfReader.getPdfObject(reference));
                    final Iterator<Integer> iteratorKeys = this.crls.keySet().iterator();
                    do {
                        if (!iteratorKeys.hasNext()) {
                            break;
                        }
                        final int index = iteratorKeys.next().intValue();
                        if (Arrays.equals(referenceBytes, this.crls.get(Integer.valueOf(index)))) {
                            crlId[i] = index;
                        }
                    } while (true);
                    i++;
                }

            } else {
                crlId = new int[0];
            }
            Calendar date = null;
            if (vriEntry.get(PdfName.TU) != null) {
                if (vriEntry.get(PdfName.TU) instanceof PdfDate) {
                    date = PdfDate.decode(((PdfDate) vriEntry.get(PdfName.TU)).getEncoding());
                }
                if (vriEntry.get(PdfName.TU) instanceof PdfString) {
                    date = PdfDate.decode(vriEntry.getAsString(PdfName.TU).getEncoding());
                }
            }
            val = new ValidationInformation(key, certId, ocspId, crlId, date);
        }
    }
}

From source file:eu.europa.ec.markt.dss.validation.pades.PDFDocumentValidator.java

License:Open Source License

@Override
protected SignatureLevelLTV verifyLevelLTV(AdvancedSignature signature, Date referenceTime,
        ValidationContext ctx) {/*from  w ww.j  av  a  2 s.  c om*/
    try {
        PAdESSignature pades = (PAdESSignature) signature;
        LOG.info("Starting LTV validation of signature: " + pades.getPdfPkcs7().getSignName() + " / "
                + PdfPKCS7.getSubjectFields(pades.getPdfPkcs7().getSigningCertificate()));

        PdfDictionary catalog = pades.getOuterCatalog();
        if (catalog == null) {
            catalog = pades.getPdfReader().getCatalog();
        }

        PdfDictionary dss = catalog.getAsDict(new PdfName("DSS"));

        if (dss == null) {
            LOG.info("No DSS dictionary!");
            return new SignatureLevelLTV(new Result(ResultStatus.INVALID, "no.dss.dictionary"), null, null);
        }

        LOG.info("DSS dictionary found");

        PdfName sigType = pades.getSignatureDictionary().getAsName(PdfName.TYPE);
        // PdfName subfilter = pades.getSignatureDictionary().getAsName(PdfName.SUBFILTER);

        TimestampVerificationResult docTimestampCheck = null;

        boolean dssCertsVerificationResult = everyCertificateValueAreThere(ctx,
                pades.getExtendedCertificateSource().getCertificates(), pades.getSigningCertificate());
        boolean dssRevocationVerificationResult = true;
        dssRevocationVerificationResult &= everyCRLValueOrRefAreThere(ctx, pades.getCRLs());
        dssRevocationVerificationResult &= everyOCSPValueOrRefAreThere(ctx, pades.getOCSPs());
        boolean vriVerificationresult = true;

        if (sigType != null) {
            if (sigType.equals(new PdfName("Sig"))) {
                // Standard signature

                PdfDictionary vri = dss.getAsDict(new PdfName("VRI"));

                if (vri == null) {
                    LOG.info("No VRI dictionary, this is optional but required by Adobe Acrobat");
                    return new SignatureLevelLTV(new Result(ResultStatus.INVALID, "no.vri.dictionary"), null,
                            null);
                }

                // Verify the VRI
                MessageDigest _md = MessageDigest.getInstance("SHA1");
                String hexHash = Hex
                        .encodeHexString(
                                _md.digest(pades.getSignatureDictionary().get(PdfName.CONTENTS).getBytes()))
                        .toUpperCase();

            } else if (sigType.equals(new PdfName("DocTimeStamp"))) {

            } else {
                throw new RuntimeException("Unknown signature dictionary type");
            }
        }

        Result levelReached = null;
        if (dssCertsVerificationResult && dssRevocationVerificationResult) {
            levelReached = new Result(ResultStatus.VALID, null);
        } else {
            levelReached = new Result();
            if (!dssCertsVerificationResult) {
                levelReached.setStatus(ResultStatus.INVALID, "dss.certs.verification.result.error");
            } else if (!dssRevocationVerificationResult) {
                levelReached.setStatus(ResultStatus.INVALID, "dss.revocation.verification.result.error");
            } else if (!vriVerificationresult) {
                levelReached.setStatus(ResultStatus.INVALID, "vri.verification.result.error");
            }
        }

        return new SignatureLevelLTV(levelReached,
                new Result((dssCertsVerificationResult) ? ResultStatus.VALID : ResultStatus.INVALID, null),
                new Result((dssRevocationVerificationResult) ? ResultStatus.VALID : ResultStatus.INVALID,
                        null));

    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:questions.forms.AddActionToField.java

public static void main(String[] args) {
    try {/* w w w .  ja  v  a  2  s. c om*/
        PdfReader reader = new PdfReader(RESOURCE);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
        AcroFields form = stamper.getAcroFields();
        Item fd = form.getFieldItem("Who");
        PdfDictionary dict = (PdfDictionary) PdfReader.getPdfObject((PdfObject) fd.getWidgetRef(0));
        PdfDictionary aa = dict.getAsDict(PdfName.AA);
        if (aa == null)
            aa = new PdfDictionary();
        aa.put(new PdfName("Fo"),
                PdfAction.javaScript("app.alert('Who has got the focus!?');", stamper.getWriter()));
        dict.put(PdfName.AA, aa);
        stamper.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:questions.forms.FillDynamicXfa.java

public static void main(String[] args) {
    try {/*  w  ww  . ja  va 2  s.c o  m*/
        PdfReader reader = new PdfReader(RESOURCE_PDF);
        File file = new File(RESOURCE_DATA);
        byte[] data = new byte[(int) file.length()];
        FileInputStream is = new FileInputStream(file);
        int offset = 0;
        int numRead = 0;
        int datalength = data.length;
        while (offset < datalength && (numRead = is.read(data, offset, datalength - offset)) >= 0) {
            offset += numRead;
        }
        PdfDictionary root = reader.getCatalog();
        PdfDictionary acroform = root.getAsDict(PdfName.ACROFORM);
        PdfArray xfa = acroform.getAsArray(PdfName.XFA);
        for (int i = 0; i < xfa.size(); i += 2) {
            if ("datasets".equals(xfa.getAsString(i).toString())) {
                PRStream s = (PRStream) xfa.getAsStream(i + 1);
                s.setData(data);
            }
        }
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
        stamper.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:questions.forms.GetTextFields.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    try {/*www . j av a2s  .c  o 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.ReadXfa.java

public static void main(String[] args) {
    try {//from ww w  .j ava2  s  . c  o m
        PdfReader reader = new PdfReader(RESOURCE);
        FileOutputStream os = new FileOutputStream(RESULT);
        PdfDictionary root = reader.getCatalog();
        PdfDictionary acroform = root.getAsDict(PdfName.ACROFORM);
        PdfArray xfa = acroform.getAsArray(PdfName.XFA);
        for (int i = 0; i < xfa.size(); i += 2) {
            System.out.println("Reading: " + xfa.getAsString(i));
            PRStream s = (PRStream) xfa.getAsStream(i + 1);
            os.write(PdfReader.getStreamBytes(s));
        }
        os.flush();
        os.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:questions.forms.RemoveXfa.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    try {//from ww  w.j a va2 s . c  o m
        PdfReader reader = new PdfReader(RESOURCE);
        PdfDictionary root = reader.getCatalog();
        PdfDictionary acroform = root.getAsDict(PdfName.ACROFORM);
        acroform.remove(PdfName.XFA);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
        AcroFields form = stamper.getAcroFields();
        Map<String, Item> fields = form.getFields();
        for (String field : fields.keySet()) {
            System.out.println(field);
            form.setField(field, "value");
        }
        stamper.partialFormFlattening("topmostSubform[0].Page1[0].SN_NUMBER[0]");
        stamper.setFormFlattening(true);
        stamper.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:questions.javascript.AddJavaScriptToForm.java

public static void addJavaScript(String input, String output) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(input);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(output));
    stamper.getWriter()//from   w  w w . j a va 2s .co  m
            .addJavaScript("function setReadOnly(readonly) {" + "var partner = this.getField('partner');"
                    + "if(readonly) {" + "partner.value = '';" + "}" + "partner.readonly = readonly;" + " }"
                    + "function validate() {" + "var married = this.getField('married');"
                    + "var partner = this.getField('partner');"
                    + "if (married.value == 'yes' && partner.value == '') {"
                    + "app.alert('please enter the name of your partner');" + "}" + "else {"
                    + "this.submitForm({" + " cURL:\"http://1t3xt.info/examples/request.php\","
                    + " cSubmitAs: \"HTML\"" + "});" + "}" + " }");
    AcroFields form = stamper.getAcroFields();
    Item fd = form.getFieldItem("married");

    PdfDictionary dictYes = (PdfDictionary) PdfReader.getPdfObject((PdfObject) fd.getWidgetRef(0));
    PdfDictionary yesAction = dictYes.getAsDict(PdfName.AA);
    if (yesAction == null)
        yesAction = new PdfDictionary();
    yesAction.put(new PdfName("Fo"), PdfAction.javaScript("setReadOnly(false);", stamper.getWriter()));
    dictYes.put(PdfName.AA, yesAction);

    PdfDictionary dictNo = (PdfDictionary) PdfReader.getPdfObject((PdfObject) fd.getWidgetRef(1));
    PdfDictionary noAction = dictNo.getAsDict(PdfName.AA);
    if (noAction == null)
        noAction = new PdfDictionary();
    noAction.put(new PdfName("Fo"), PdfAction.javaScript("setReadOnly(true);", stamper.getWriter()));
    dictNo.put(PdfName.AA, noAction);

    PdfWriter writer = stamper.getWriter();
    PushbuttonField button = new PushbuttonField(writer, new Rectangle(40, 690, 200, 710), "submit");
    button.setText("validate and submit");
    button.setOptions(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
    PdfFormField validateAndSubmit = button.getField();
    validateAndSubmit.setAction(PdfAction.javaScript("validate();", stamper.getWriter()));
    stamper.addAnnotation(validateAndSubmit, 1);

    stamper.close();
}

From source file:questions.javascript.RemoveJavaScript.java

public static void main(String[] args) throws DocumentException, IOException {
    // creating the form with JS
    AddJavaScriptToForm.main(args);/*from  w  w w . j  a  v a 2 s  .  c o  m*/
    // removing the document level JS
    PdfReader reader = new PdfReader(AddJavaScriptToForm.RESULT);
    PdfDictionary root = reader.getCatalog();
    PdfDictionary names = root.getAsDict(PdfName.NAMES);
    names.remove(PdfName.JAVASCRIPT);
    if (names.size() == 0) {
        root.remove(PdfName.NAMES);
    }
    reader.removeUnusedObjects();
    // filling out and flattening the form
    // (if you don't flatten, you'll get JS errors!)
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
    AcroFields form = stamper.getAcroFields();
    form.setField("married", "no");
    stamper.setFormFlattening(true);
    stamper.close();
}