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

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

Introduction

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

Prototype

public PdfObject getPdfObject(int idx) 

Source Link

Usage

From source file:org.opensignature.opensignpdf.PDFSigner.java

License:Open Source License

/**
 * //  w w  w  .  j  a  v  a  2  s  .co  m
 * @param pdfFile
 * @return
 * @throws IOException
 * @throws DocumentException
 * @throws FileNotFoundException
 */
private PdfReader createPDFReader(File pdfFile) throws IOException, DocumentException, FileNotFoundException {

    logger.info("[createPDFReader.in]:: " + Arrays.asList(new Object[] { pdfFile }));

    PdfReader reader;

    if ("true".equals(openOfficeSelected)) {
        String fileName = pdfFile.getPath();
        String tempFileName = fileName + ".temp";
        PdfReader documentPDF = new PdfReader(fileName);

        PdfStamperOSP stamperTemp = new PdfStamperOSP(documentPDF, new FileOutputStream(tempFileName));
        AcroFields af = stamperTemp.getAcroFields();
        af.setGenerateAppearances(true);
        PdfDictionary acro = (PdfDictionary) PdfReader
                .getPdfObject(documentPDF.getCatalog().get(PdfName.ACROFORM));
        acro.remove(PdfName.DR);
        HashMap fields = af.getFields();
        String key;
        for (Iterator it = fields.keySet().iterator(); it.hasNext();) {
            key = (String) it.next();
            int a = af.getFieldType(key);
            if (a == 4) {
                ArrayList widgets = af.getFieldItem(key).widgets;
                PdfDictionary widget = (PdfDictionary) widgets.get(0);
                widget.put(PdfName.FT, new PdfName("Sig"));
                widget.remove(PdfName.V);
                widget.remove(PdfName.DV);
                widget.remove(PdfName.TU);
                widget.remove(PdfName.FF);
                widget.remove(PdfName.DA);
                widget.remove(PdfName.DR);
                widget.remove(PdfName.AP);
            }
        }

        stamperTemp.close();
        documentPDF.close();
        reader = new PdfReader(pdfFile.getPath() + ".temp");

    } else {
        reader = new PdfReader(pdfFile.getPath());

    }

    logger.info("[createPDFReader.retorna]:: ");
    return reader;

}

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

License:Open Source License

/**
 * @param args// ww w .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.pdfsam.console.business.pdf.handlers.UnpackCmdExecutor.java

License:Open Source License

public void execute(AbstractParsedCommand parsedCommand) throws ConsoleException {
    if ((parsedCommand != null) && (parsedCommand instanceof UnpackParsedCommand)) {

        UnpackParsedCommand inputCommand = (UnpackParsedCommand) parsedCommand;
        try {/*from  w w  w. ja  va  2  s  . c  o m*/
            PdfFile[] fileList = arraysConcat(inputCommand.getInputFileList(),
                    getPdfFiles(inputCommand.getInputDirectory()));
            //check if empty
            if (fileList == null || !(fileList.length > 0)) {
                throw new UnpackException(UnpackException.CMD_NO_INPUT_FILE);
            }

            for (int i = 0; i < fileList.length; i++) {
                int unpackedFiles = 0;
                try {
                    pdfReader = PdfUtility.readerFor(fileList[i]);
                    pdfReader.removeUnusedObjects();
                    pdfReader.consolidateNamedDestinations();

                    PdfDictionary catalog = pdfReader.getCatalog();
                    PdfDictionary names = (PdfDictionary) PdfReader.getPdfObject(catalog.get(PdfName.NAMES));
                    if (names != null) {
                        PdfDictionary embFiles = (PdfDictionary) PdfReader
                                .getPdfObject(names.get(new PdfName("EmbeddedFiles")));
                        if (embFiles != null) {
                            HashMap embMap = PdfNameTree.readTree(embFiles);
                            for (Iterator iter = embMap.values().iterator(); iter.hasNext();) {
                                PdfDictionary filespec = (PdfDictionary) PdfReader
                                        .getPdfObject((PdfObject) iter.next());
                                unpackedFiles += unpackFile(filespec, inputCommand.getOutputFile(),
                                        inputCommand.isOverwrite());
                            }
                        }
                    }
                    for (int k = 1; k <= pdfReader.getNumberOfPages(); ++k) {
                        PdfArray annots = (PdfArray) PdfReader
                                .getPdfObject(pdfReader.getPageN(k).get(PdfName.ANNOTS));
                        if (annots != null) {
                            for (Iterator iter = annots.listIterator(); iter.hasNext();) {
                                PdfDictionary annot = (PdfDictionary) PdfReader
                                        .getPdfObject((PdfObject) iter.next());
                                PdfName subType = (PdfName) PdfReader.getPdfObject(annot.get(PdfName.SUBTYPE));
                                if (PdfName.FILEATTACHMENT.equals(subType)) {
                                    PdfDictionary filespec = (PdfDictionary) PdfReader
                                            .getPdfObject(annot.get(PdfName.FS));
                                    unpackedFiles += unpackFile(filespec, inputCommand.getOutputFile(),
                                            inputCommand.isOverwrite());
                                }
                            }
                        }
                    }
                    pdfReader.close();
                    if (unpackedFiles > 0) {
                        LOG.info("File " + fileList[i].getFile().getName() + " unpacked, found " + unpackedFiles
                                + " attachments.");
                    } else {
                        LOG.info("No attachments in " + fileList[i].getFile().getName() + ".");
                    }
                    setPercentageOfWorkDone(((i + 1) * WorkDoneDataModel.MAX_PERGENTAGE) / fileList.length);
                } catch (Exception e) {
                    LOG.error("Error unpacking file " + fileList[i].getFile().getName(), e);
                }
            }
        } catch (Exception e) {
            throw new UnpackException(e);
        } finally {
            setWorkCompleted();
        }
    } else {
        throw new ConsoleException(ConsoleException.ERR_BAD_COMMAND);
    }
}

From source file:org.pdfsam.console.business.pdf.handlers.UnpackCmdExecutor.java

License:Open Source License

/**
 * Unpack//from   ww w . ja  va  2s.  com
 * @param filespec the dictionary
 * @param outPath output directory
 * @param overwrite if true overwrite if already exists
 * @return number of unpacked files
 * @throws IOException
 */
private int unpackFile(PdfDictionary filespec, File outPath, boolean overwrite) throws IOException {
    int retVal = 0;
    if (filespec != null) {
        PdfName type = (PdfName) PdfReader.getPdfObject(filespec.get(PdfName.TYPE));
        if (PdfName.F.equals(type) || PdfName.FILESPEC.equals(type)) {
            PdfDictionary ef = (PdfDictionary) PdfReader.getPdfObject(filespec.get(PdfName.EF));
            PdfString fn = (PdfString) PdfReader.getPdfObject(filespec.get(PdfName.F));
            if (fn != null && ef != null) {
                LOG.debug("Unpacking file " + fn + " to " + outPath);
                File fLast = new File(fn.toUnicodeString());
                File fullPath = new File(outPath, fLast.getName());
                if (fullPath.exists()) {
                    //check if overwrite is allowed
                    if (overwrite) {
                        if (!fullPath.delete()) {
                            LOG.warn("Unable to overwrite " + fullPath.getAbsolutePath()
                                    + ", unable to unpack.");
                        }
                    } else {
                        LOG.warn("Cannot overwrite " + fullPath.getAbsolutePath()
                                + " (overwrite is false), unable to unpack.");
                    }
                } else {
                    PRStream prs = (PRStream) PdfReader.getPdfObject(ef.get(PdfName.F));
                    if (prs != null) {
                        byte b[] = PdfReader.getStreamBytes(prs);
                        FileOutputStream fout = new FileOutputStream(fullPath);
                        fout.write(b);
                        fout.close();
                        retVal = 1;
                    }
                }
            }
        }
    }
    return retVal;
}

From source file:org.sejda.impl.itext.component.PdfUnpacker.java

License:Apache License

private void unpack(Set<PdfDictionary> dictionaries) throws TaskIOException {
    for (PdfDictionary dictionary : dictionaries) {
        PdfName type = (PdfName) PdfReader.getPdfObject(dictionary.get(PdfName.TYPE));
        if (PdfName.F.equals(type) || PdfName.FILESPEC.equals(type)) {
            PdfDictionary ef = (PdfDictionary) PdfReader.getPdfObject(dictionary.get(PdfName.EF));
            PdfString fn = (PdfString) PdfReader.getPdfObject(dictionary.get(PdfName.F));
            if (fn != null && ef != null) {
                PRStream prs = (PRStream) PdfReader.getPdfObject(ef.get(PdfName.F));
                if (prs != null) {
                    File tmpFile = copyToTemporaryFile(prs);
                    outputWriter.addOutput(file(tmpFile).name(fn.toUnicodeString()));
                }//from   w w  w . j  a va 2 s . c  o m
            }
        }
    }
}

From source file:org.sejda.impl.itext.component.PdfUnpacker.java

License:Apache License

private Set<PdfDictionary> getEmbeddedFilesDictionaries(PdfReader reader) {
    Set<PdfDictionary> retSet = new NullSafeSet<PdfDictionary>();
    PdfDictionary catalog = reader.getCatalog();
    PdfDictionary names = (PdfDictionary) PdfReader.getPdfObject(catalog.get(PdfName.NAMES));
    if (names != null) {
        PdfDictionary embFiles = (PdfDictionary) PdfReader.getPdfObject(names.get(PdfName.EMBEDDEDFILES));
        if (embFiles != null) {
            @SuppressWarnings("unchecked")
            HashMap<String, PdfObject> embMap = PdfNameTree.readTree(embFiles);
            for (PdfObject value : embMap.values()) {
                retSet.add((PdfDictionary) PdfReader.getPdfObject(value));
            }/*from  w w  w . j a va2s. c  o  m*/
        }
    }
    return retSet;
}

From source file:org.sejda.impl.itext.component.PdfUnpacker.java

License:Apache License

private Set<PdfDictionary> getFileAttachmentsDictionaries(PdfReader reader) {
    Set<PdfDictionary> retSet = new NullSafeSet<PdfDictionary>();
    for (int k = 1; k <= reader.getNumberOfPages(); ++k) {
        PdfArray annots = (PdfArray) PdfReader.getPdfObject(reader.getPageN(k).get(PdfName.ANNOTS));
        if (annots != null) {
            for (@SuppressWarnings("unchecked")
            Iterator<PdfObject> iter = annots.listIterator(); iter.hasNext();) {
                PdfDictionary annot = (PdfDictionary) PdfReader.getPdfObject(iter.next());
                PdfName subType = (PdfName) PdfReader.getPdfObject(annot.get(PdfName.SUBTYPE));
                if (PdfName.FILEATTACHMENT.equals(subType)) {
                    retSet.add((PdfDictionary) PdfReader.getPdfObject(annot.get(PdfName.FS)));
                }/*from w w w. ja  v a  2  s  .c  om*/
            }
        }
    }
    return retSet;
}

From source file:org.squale.welcom.outils.pdf.advanced.WPdfFieldWriter.java

License:Open Source License

/**
 * Tranforme les champs en nom modifiable
 * /*from  ww w  .  j  a v a  2s.c  o  m*/
 * @param form le field
 * @param name le nom
 */
private static void lockField(final AcroFields form, final String name) {
    final AcroFields.Item item = form.getFieldItem(name);
    if (item != null) {
        for (int k = 0; k < item.merged.size(); ++k) {
            PdfNumber num = (PdfNumber) PdfReader
                    .getPdfObject(((PdfDictionary) item.values.get(k)).get(PdfName.FF));
            int val = 0;

            if (num != null) {
                val = num.intValue();
            }

            num = new PdfNumber(val | PdfFormField.FF_READ_ONLY);

            ((PdfDictionary) item.merged.get(k)).put(PdfName.FF, num);
            ((PdfDictionary) item.values.get(k)).put(PdfName.FF, num);
        }
    }
}

From source file:questions.forms.AddActionToField.java

public static void main(String[] args) {
    try {//w  w w  .  j ava  2s .  c o m
        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.GetTextFields.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    try {//from w w  w  .  j  a v a2 s .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();
    }
}