Example usage for org.apache.pdfbox.pdmodel PDDocument isEncrypted

List of usage examples for org.apache.pdfbox.pdmodel PDDocument isEncrypted

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel PDDocument isEncrypted.

Prototype

public boolean isEncrypted() 

Source Link

Document

This will tell if this document is encrypted or not.

Usage

From source file:PrintImageLocations.java

License:Apache License

/**
 * This will print the documents data.//from   www .  j  a  va 2s . c o  m
 *
 * @param args The command line arguments.
 *
 * @throws Exception If there is an error parsing the document.
 */
public static void main2() throws Exception {
    if (flag) {
        usage();
    } else {
        PDDocument document = null;
        try {
            document = PDDocument.load(PrintTextLocations.INPUTFILE);
            if (document.isEncrypted()) {
                try {
                    document.decrypt("");
                } catch (InvalidPasswordException e) {
                    System.err.println("Error: Document is encrypted with a password.");
                    System.exit(1);
                }
            }
            PrintImageLocations printer = new PrintImageLocations();
            List allPages = document.getDocumentCatalog().getAllPages();
            for (int i = 0; i < allPages.size(); i++) {
                PDPage page = (PDPage) allPages.get(i);
                System.out.println("Processing page: " + i);
                printer.processStream(page, page.findResources(), page.getContents().getStream());
            }
        } finally {
            if (document != null) {
                document.close();
            }
        }
    }
}

From source file:PDFConverter.java

License:Apache License

/**
 * Implementation is informed by PDFBox authors.
 *
 * @param doc/*  w w  w  .  j  ava 2 s  .c  o  m*/
 * @return
 * @throws IOException
 */
@Override
public synchronized ConvertedDocument convert(java.io.File doc) throws IOException {

    /*
     * Licensed to the Apache Software Foundation (ASF) under one or more
     * contributor license agreements.  See the NOTICE file distributed with
     * this work for additional information regarding copyright ownership.
     * The ASF licenses this file to You under the Apache License, Version 2.0
     * (the "License"); you may not use this file except in compliance with
     * the License.  You may obtain a copy of the License at
     *
     *      http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    /**
     * Adapted from LucenePDFDocument.java from PDFBox lucene project
     *
     * This class is used to create a document for the lucene search engine.
     * This should easily plug into the IndexHTML or IndexFiles that comes
     * with the lucene project. This class will populate the following
     * fields.
     * <table> <tr> <th>Lucene Field Name</th> <th>Description</th> </tr>
     * <tr>
     * <td>path</td> <td>File system path if loaded from a file</td> </tr>
     * <tr>
     * <td>url</td> <td>URL to PDF document</td> </tr> <tr>
     * <td>contents</td>
     * <td>Entire contents of PDF document, indexed but not stored</td>
     * </tr>
     * <tr> <td>summary</td> <td>First 500 characters of content</td> </tr>
     * <tr>
     * <td>modified</td> <td>The modified date/time according to the url or
     * path</td> </tr> <tr> <td>uid</td> <td>A unique identifier for the
     * Lucene document.</td> </tr> <tr> <td>CreationDate</td> <td>From PDF
     * meta-data if available</td> </tr> <tr> <td>Creator</td> <td>From PDF
     * meta-data if available</td> </tr> <tr> <td>Keywords</td> <td>From PDF
     * meta-data if available</td> </tr> <tr> <td>ModificationDate</td>
     * <td>From PDF meta-data if available</td> </tr> <tr> <td>Producer</td>
     * <td>From PDF meta-data if available</td> </tr> <tr> <td>Subject</td>
     * <td>From PDF meta-data if available</td> </tr> <tr> <td>Trapped</td>
     * <td>From PDF meta-data if available</td> </tr> <tr>
     * <td>Encrypted</td> <td>From PDF meta-data if available</td> </tr>
     * </table>
     *
     * @author <a href="mailto:ben@benlitchfield.com">Ben Litchfield</a>
     * @version $Revision: 1.23 $
     *
     * @throws IOException If there is an error parsing the document.
     */
    PDDocument pdfDocument = null;
    ConvertedDocument textdoc = new ConvertedDocument(doc);

    try {
        pdfDocument = PDDocument.load(doc);

        if (pdfDocument.isEncrypted()) {
            //Just try using the default password and move on
            // Even if the doc is encrypted, apparently you can try. Throw exception if it fails.
            textdoc.addProperty("encrypted", "YES");
        }

        //create a writer where to append the text content.
        StringWriter writer = new StringWriter();
        stripper.resetEngine();
        stripper.writeText(pdfDocument, writer);

        PDDocumentInformation info = pdfDocument.getDocumentInformation();
        if (info != null) {
            textdoc.addAuthor(info.getAuthor());
            try {
                textdoc.addCreateDate(info.getCreationDate());
            } catch (IOException io) {
                //ignore, bad date but continue with indexing
            }
            textdoc.addProperty("creator_tool", info.getCreator());
            textdoc.addProperty("keywords", info.getKeywords());
            /* try {
             metadata.add("ModificationDate", info.getModificationDate());
             } catch (IOException io) {
             //ignore, bad date but continue with indexing
             } */
            //metadata.add("Producer", info.getProducer());
            textdoc.addProperty("subject", info.getSubject());
            String ttl = info.getTitle();
            if (ttl == null || "untitled".equalsIgnoreCase(ttl)) {
                ttl = textdoc.filename;
            }
            textdoc.addTitle(ttl);
            // metadata.add("Trapped", info.getTrapped());

            // TODO: Character set is what?
            textdoc.setEncoding("UTF-8");
        }

        // Note: the buffer to string operation is costless;
        // the char array value of the writer buffer and the content string
        // is shared as long as the buffer content is not modified, which will
        // not occur here.
        textdoc.setText(writer.getBuffer().toString());

        return textdoc;

    } finally {
        if (pdfDocument != null) {
            pdfDocument.close();
        }
    }
}

From source file:ShowSignature.java

License:Apache License

private void showSignature(String[] args) throws IOException, CertificateException {
    if (args.length != 2) {
        usage();/*from w  w w.ja v  a  2 s.  c o m*/
    } else {
        String password = args[0];
        String infile = args[1];
        PDDocument document = null;
        try {
            document = PDDocument.load(new File(infile), password);
            if (!document.isEncrypted()) {
                System.err.println("Warning: Document is not encrypted.");
            }

            COSDictionary trailer = document.getDocument().getTrailer();
            COSDictionary root = (COSDictionary) trailer.getDictionaryObject(COSName.ROOT);
            COSDictionary acroForm = (COSDictionary) root.getDictionaryObject(COSName.ACRO_FORM);
            COSArray fields = (COSArray) acroForm.getDictionaryObject(COSName.FIELDS);
            for (int i = 0; i < fields.size(); i++) {
                COSDictionary field = (COSDictionary) fields.getObject(i);
                COSName type = field.getCOSName(COSName.FT);
                if (COSName.SIG.equals(type)) {
                    COSDictionary cert = (COSDictionary) field.getDictionaryObject(COSName.V);
                    if (cert != null) {
                        System.out.println("Certificate found");
                        System.out.println("Name=" + cert.getDictionaryObject(COSName.NAME));
                        System.out.println("Modified=" + cert.getDictionaryObject(COSName.M));
                        COSName subFilter = (COSName) cert.getDictionaryObject(COSName.SUB_FILTER);
                        if (subFilter != null) {
                            if (subFilter.getName().equals("adbe.x509.rsa_sha1")) {
                                COSString certString = (COSString) cert
                                        .getDictionaryObject(COSName.getPDFName("Cert"));
                                byte[] certData = certString.getBytes();
                                CertificateFactory factory = CertificateFactory.getInstance("X.509");
                                ByteArrayInputStream certStream = new ByteArrayInputStream(certData);
                                Collection<? extends Certificate> certs = factory
                                        .generateCertificates(certStream);
                                System.out.println("certs=" + certs);
                            } else if (subFilter.getName().equals("adbe.pkcs7.sha1")) {
                                COSString certString = (COSString) cert.getDictionaryObject(COSName.CONTENTS);
                                byte[] certData = certString.getBytes();
                                CertificateFactory factory = CertificateFactory.getInstance("X.509");
                                ByteArrayInputStream certStream = new ByteArrayInputStream(certData);
                                Collection<? extends Certificate> certs = factory
                                        .generateCertificates(certStream);
                                System.out.println("certs=" + certs);
                            } else {
                                System.err.println("Unknown certificate type:" + subFilter);
                            }
                        } else {
                            throw new IOException("Missing subfilter for cert dictionary");
                        }
                    } else {
                        System.out.println("Signature found, but no certificate");
                    }
                }
            }
        } finally {
            if (document != null) {
                document.close();
            }
        }
    }
}

From source file:com.ackpdfbox.app.Decrypt.java

License:Apache License

private void decrypt() throws IOException {
    PDDocument document = null;
    try {/*from w w  w  .j  a  va  2s  . c o  m*/
        InputStream keyStoreStream = null;
        if (keyStore != null) {
            keyStoreStream = new FileInputStream(keyStore);
        }

        document = PDDocument.load(new File(infile), password, keyStoreStream, alias);

        if (document.isEncrypted()) {
            AccessPermission ap = document.getCurrentAccessPermission();
            if (ap.isOwnerPermission()) {
                document.setAllSecurityToBeRemoved(true);
                document.save(outfile);
            } else {
                throw new IOException(
                        "Error: You are only allowed to decrypt a document with the owner password.");
            }
        } else {
            System.err.println("Error: Document is not encrypted.");
        }
    } finally {
        if (document != null) {
            document.close();
        }
    }
}

From source file:com.ackpdfbox.app.Encrypt.java

License:Apache License

private void encrypt(String[] args) throws IOException, CertificateException {
    if (args.length < 1) {
        usage();//from   ww w  .ja va 2 s  .co m
    } else {
        AccessPermission ap = new AccessPermission();

        String infile = null;
        String outfile = null;
        String certFile = null;
        String userPassword = "";
        String ownerPassword = "";

        int keyLength = 40;

        PDDocument document = null;

        try {
            for (int i = 0; i < args.length; i++) {
                String key = args[i];
                if (key.equals("-O")) {
                    ownerPassword = args[++i];
                } else if (key.equals("-U")) {
                    userPassword = args[++i];
                } else if (key.equals("-canAssemble")) {
                    ap.setCanAssembleDocument(args[++i].equalsIgnoreCase("true"));
                } else if (key.equals("-canExtractContent")) {
                    ap.setCanExtractContent(args[++i].equalsIgnoreCase("true"));
                } else if (key.equals("-canExtractForAccessibility")) {
                    ap.setCanExtractForAccessibility(args[++i].equalsIgnoreCase("true"));
                } else if (key.equals("-canFillInForm")) {
                    ap.setCanFillInForm(args[++i].equalsIgnoreCase("true"));
                } else if (key.equals("-canModify")) {
                    ap.setCanModify(args[++i].equalsIgnoreCase("true"));
                } else if (key.equals("-canModifyAnnotations")) {
                    ap.setCanModifyAnnotations(args[++i].equalsIgnoreCase("true"));
                } else if (key.equals("-canPrint")) {
                    ap.setCanPrint(args[++i].equalsIgnoreCase("true"));
                } else if (key.equals("-canPrintDegraded")) {
                    ap.setCanPrintDegraded(args[++i].equalsIgnoreCase("true"));
                } else if (key.equals("-certFile")) {
                    certFile = args[++i];
                } else if (key.equals("-keyLength")) {
                    try {
                        keyLength = Integer.parseInt(args[++i]);
                    } catch (NumberFormatException e) {
                        throw new NumberFormatException(
                                "Error: -keyLength is not an integer '" + args[i] + "'");
                    }
                } else if (infile == null) {
                    infile = key;
                } else if (outfile == null) {
                    outfile = key;
                } else {
                    usage();
                }
            }
            if (infile == null) {
                usage();
            }
            if (outfile == null) {
                outfile = infile;
            }
            document = PDDocument.load(new File(infile));

            if (!document.isEncrypted()) {
                if (certFile != null) {
                    PublicKeyProtectionPolicy ppp = new PublicKeyProtectionPolicy();
                    PublicKeyRecipient recip = new PublicKeyRecipient();
                    recip.setPermission(ap);

                    CertificateFactory cf = CertificateFactory.getInstance("X.509");

                    InputStream inStream = null;
                    try {
                        inStream = new FileInputStream(certFile);
                        X509Certificate certificate = (X509Certificate) cf.generateCertificate(inStream);
                        recip.setX509(certificate);
                    } finally {
                        if (inStream != null) {
                            inStream.close();
                        }
                    }

                    ppp.addRecipient(recip);

                    ppp.setEncryptionKeyLength(keyLength);

                    document.protect(ppp);
                } else {
                    StandardProtectionPolicy spp = new StandardProtectionPolicy(ownerPassword, userPassword,
                            ap);
                    spp.setEncryptionKeyLength(keyLength);
                    document.protect(spp);
                }
                document.save(outfile);
            } else {
                System.err.println("Error: Document is already encrypted.");
            }
        } finally {
            if (document != null) {
                document.close();
            }
        }
    }
}

From source file:com.ecmkit.service.convert.impl.PDFToImage.java

License:Apache License

/**
 * Infamous main method./* w w  w. java  2s  .c  o  m*/
 *
 * @param args Command line arguments, should be one and a reference to a file.
 *
 * @throws Exception If there is an error parsing the document.
 */
public static void main(String[] args) throws Exception {
    boolean useNonSeqParser = false;
    String password = "";
    String pdfFile = null;
    String outputPrefix = null;
    String imageFormat = "jpg";
    int startPage = 1;
    int endPage = Integer.MAX_VALUE;
    String color = "rgb";
    int resolution;
    float cropBoxLowerLeftX = 0;
    float cropBoxLowerLeftY = 0;
    float cropBoxUpperRightX = 0;
    float cropBoxUpperRightY = 0;
    try {
        resolution = Toolkit.getDefaultToolkit().getScreenResolution();
    } catch (HeadlessException e) {
        resolution = 96;
    }
    for (int i = 0; i < args.length; i++) {
        if (args[i].equals(PASSWORD)) {
            i++;
            if (i >= args.length) {
                usage();
            }
            password = args[i];
        } else if (args[i].equals(START_PAGE)) {
            i++;
            if (i >= args.length) {
                usage();
            }
            startPage = Integer.parseInt(args[i]);
        } else if (args[i].equals(END_PAGE)) {
            i++;
            if (i >= args.length) {
                usage();
            }
            endPage = Integer.parseInt(args[i]);
        } else if (args[i].equals(IMAGE_FORMAT)) {
            i++;
            imageFormat = args[i];
        } else if (args[i].equals(OUTPUT_PREFIX)) {
            i++;
            outputPrefix = args[i];
        } else if (args[i].equals(COLOR)) {
            i++;
            color = args[i];
        } else if (args[i].equals(RESOLUTION)) {
            i++;
            resolution = Integer.parseInt(args[i]);
        } else if (args[i].equals(CROPBOX)) {
            i++;
            cropBoxLowerLeftX = Float.valueOf(args[i]).floatValue();
            i++;
            cropBoxLowerLeftY = Float.valueOf(args[i]).floatValue();
            i++;
            cropBoxUpperRightX = Float.valueOf(args[i]).floatValue();
            i++;
            cropBoxUpperRightY = Float.valueOf(args[i]).floatValue();
        } else if (args[i].equals(NONSEQ)) {
            useNonSeqParser = true;
        } else {
            if (pdfFile == null) {
                pdfFile = args[i];
            }
        }
    }
    if (pdfFile == null) {
        usage();
    } else {
        if (outputPrefix == null) {
            outputPrefix = pdfFile.substring(0, pdfFile.lastIndexOf('.'));
        }

        PDDocument document = null;
        try {
            if (useNonSeqParser) {
                document = PDDocument.loadNonSeq(new File(pdfFile), null, password);
            } else {
                document = PDDocument.load(pdfFile);
                if (document.isEncrypted()) {
                    try {
                        document.decrypt(password);
                    } catch (InvalidPasswordException e) {
                        if (args.length == 4)//they supplied the wrong password
                        {
                            System.err.println("Error: The supplied password is incorrect.");
                            System.exit(2);
                        } else {
                            //they didn't supply a password and the default of "" was wrong.
                            System.err.println("Error: The document is encrypted.");
                            usage();
                        }
                    }
                }
            }
            //PDFont font = PDTrueTypeFont.loadTTF(document, new File("/usr/share/fonts/truetype/simsun.ttc"));
            int imageType = 24;
            if ("bilevel".equalsIgnoreCase(color)) {
                imageType = BufferedImage.TYPE_BYTE_BINARY;
            } else if ("indexed".equalsIgnoreCase(color)) {
                imageType = BufferedImage.TYPE_BYTE_INDEXED;
            } else if ("gray".equalsIgnoreCase(color)) {
                imageType = BufferedImage.TYPE_BYTE_GRAY;
            } else if ("rgb".equalsIgnoreCase(color)) {
                imageType = BufferedImage.TYPE_INT_RGB;
            } else if ("rgba".equalsIgnoreCase(color)) {
                imageType = BufferedImage.TYPE_INT_ARGB;
            } else {
                System.err.println("Error: the number of bits per pixel must be 1, 8 or 24.");
                System.exit(2);
            }

            //if a CropBox has been specified, update the CropBox:
            //changeCropBoxes(PDDocument document,float a, float b, float c,float d)
            if (cropBoxLowerLeftX != 0 || cropBoxLowerLeftY != 0 || cropBoxUpperRightX != 0
                    || cropBoxUpperRightY != 0) {
                changeCropBoxes(document, cropBoxLowerLeftX, cropBoxLowerLeftY, cropBoxUpperRightX,
                        cropBoxUpperRightY);
            }

            //Make the call
            PDFImageWriter imageWriter = new PDFImageWriter();
            boolean success = imageWriter.writeImage(document, imageFormat, password, startPage, endPage,
                    outputPrefix, imageType, resolution);
            if (!success) {
                System.err.println("Error: no writer found for image format '" + imageFormat + "'");
                System.exit(1);
            }
        } catch (Exception e) {
            System.err.println(e);
        } finally {
            if (document != null) {
                document.close();
            }
        }
    }
}

From source file:com.enginkutuk.pdfboxsample.PDFBoxSample.java

public void readPdfFile(String path) {
    try {/* w ww  . j  a v a2  s .  c o  m*/
        PDDocument document = null;
        document = PDDocument.load(new File(path));
        document.getClass();
        if (!document.isEncrypted()) {
            PDFTextStripperByArea stripper = new PDFTextStripperByArea();
            stripper.setSortByPosition(true);
            PDFTextStripper Tstripper = new PDFTextStripper();
            String st = Tstripper.getText(document);
            System.out.println(st);
            JOptionPane.showMessageDialog(null, st);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.fangxin365.core.utils.PDFMerger.java

License:Apache License

/**
 * append all pages from source to destination.
 * /*w w w . j a v  a2s.  com*/
 * @param destination
 *            the document to receive the pages
 * @param source
 *            the document originating the new pages
 * 
 * @throws IOException
 *             If there is an error accessing data from either document.
 */
public void appendDocument(PDDocument destination, PDDocument source) throws IOException {
    if (destination.isEncrypted()) {
        System.out.println("Error: destination PDF is encrypted, can't append encrypted PDF documents.");
    }
    if (source.isEncrypted()) {
        System.out.println("Error: source PDF is encrypted, can't append encrypted PDF documents.");
    }
    PDDocumentInformation destInfo = destination.getDocumentInformation();
    PDDocumentInformation srcInfo = source.getDocumentInformation();
    destInfo.getDictionary().mergeInto(srcInfo.getDictionary());

    PDDocumentCatalog destCatalog = destination.getDocumentCatalog();
    PDDocumentCatalog srcCatalog = source.getDocumentCatalog();

    // use the highest version number for the resulting pdf
    float destVersion = destination.getDocument().getVersion();
    float srcVersion = source.getDocument().getVersion();

    if (destVersion < srcVersion) {
        destination.getDocument().setVersion(srcVersion);
    }

    if (destCatalog.getOpenAction() == null) {
        destCatalog.setOpenAction(srcCatalog.getOpenAction());
    }

    // maybe there are some shared resources for all pages
    COSDictionary srcPages = (COSDictionary) srcCatalog.getCOSDictionary().getDictionaryObject(COSName.PAGES);
    COSDictionary srcResources = (COSDictionary) srcPages.getDictionaryObject(COSName.RESOURCES);
    COSDictionary destPages = (COSDictionary) destCatalog.getCOSDictionary().getDictionaryObject(COSName.PAGES);
    COSDictionary destResources = (COSDictionary) destPages.getDictionaryObject(COSName.RESOURCES);
    if (srcResources != null) {
        if (destResources != null) {
            destResources.mergeInto(srcResources);
        } else {
            destPages.setItem(COSName.RESOURCES, srcResources);
        }
    }

    PDFCloneUtility cloner = new PDFCloneUtility(destination);

    try {
        PDAcroForm destAcroForm = destCatalog.getAcroForm();
        PDAcroForm srcAcroForm = srcCatalog.getAcroForm();
        if (destAcroForm == null) {
            cloner.cloneForNewDocument(srcAcroForm);
            destCatalog.setAcroForm(srcAcroForm);
        } else {
            if (srcAcroForm != null) {
                mergeAcroForm(cloner, destAcroForm, srcAcroForm);
            }
        }
    } catch (Exception e) {
        // if we are not ignoring exceptions, we'll re-throw this
        if (!ignoreAcroFormErrors) {
            throw (IOException) e;
        }
    }

    COSArray destThreads = (COSArray) destCatalog.getCOSDictionary().getDictionaryObject(COSName.THREADS);
    COSArray srcThreads = (COSArray) cloner
            .cloneForNewDocument(destCatalog.getCOSDictionary().getDictionaryObject(COSName.THREADS));
    if (destThreads == null) {
        destCatalog.getCOSDictionary().setItem(COSName.THREADS, srcThreads);
    } else {
        destThreads.addAll(srcThreads);
    }

    PDDocumentNameDictionary destNames = destCatalog.getNames();
    PDDocumentNameDictionary srcNames = srcCatalog.getNames();
    if (srcNames != null) {
        if (destNames == null) {
            destCatalog.getCOSDictionary().setItem(COSName.NAMES, cloner.cloneForNewDocument(srcNames));
        } else {
            cloner.cloneMerge(srcNames, destNames);
        }

    }

    PDDocumentOutline destOutline = destCatalog.getDocumentOutline();
    PDDocumentOutline srcOutline = srcCatalog.getDocumentOutline();
    if (srcOutline != null) {
        if (destOutline == null) {
            PDDocumentOutline cloned = new PDDocumentOutline(
                    (COSDictionary) cloner.cloneForNewDocument(srcOutline));
            destCatalog.setDocumentOutline(cloned);
        } else {
            PDOutlineItem first = srcOutline.getFirstChild();
            if (first != null) {
                PDOutlineItem clonedFirst = new PDOutlineItem(
                        (COSDictionary) cloner.cloneForNewDocument(first));
                destOutline.appendChild(clonedFirst);
            }
        }
    }

    String destPageMode = destCatalog.getPageMode();
    String srcPageMode = srcCatalog.getPageMode();
    if (destPageMode == null) {
        destCatalog.setPageMode(srcPageMode);
    }

    COSDictionary destLabels = (COSDictionary) destCatalog.getCOSDictionary()
            .getDictionaryObject(COSName.PAGE_LABELS);
    COSDictionary srcLabels = (COSDictionary) srcCatalog.getCOSDictionary()
            .getDictionaryObject(COSName.PAGE_LABELS);
    if (srcLabels != null) {
        int destPageCount = destination.getNumberOfPages();
        COSArray destNums = null;
        if (destLabels == null) {
            destLabels = new COSDictionary();
            destNums = new COSArray();
            destLabels.setItem(COSName.NUMS, destNums);
            destCatalog.getCOSDictionary().setItem(COSName.PAGE_LABELS, destLabels);
        } else {
            destNums = (COSArray) destLabels.getDictionaryObject(COSName.NUMS);
        }
        COSArray srcNums = (COSArray) srcLabels.getDictionaryObject(COSName.NUMS);
        if (srcNums != null) {
            for (int i = 0; i < srcNums.size(); i += 2) {
                COSNumber labelIndex = (COSNumber) srcNums.getObject(i);
                long labelIndexValue = labelIndex.intValue();
                destNums.add(COSInteger.get(labelIndexValue + destPageCount));
                destNums.add(cloner.cloneForNewDocument(srcNums.getObject(i + 1)));
            }
        }
    }

    COSStream destMetadata = (COSStream) destCatalog.getCOSDictionary().getDictionaryObject(COSName.METADATA);
    COSStream srcMetadata = (COSStream) srcCatalog.getCOSDictionary().getDictionaryObject(COSName.METADATA);
    if (destMetadata == null && srcMetadata != null) {
        PDStream newStream = new PDStream(destination, srcMetadata.getUnfilteredStream(), false);
        newStream.getStream().mergeInto(srcMetadata);
        newStream.addCompression();
        destCatalog.getCOSDictionary().setItem(COSName.METADATA, newStream);
    }

    // finally append the pages
    @SuppressWarnings("unchecked")
    List<PDPage> pages = srcCatalog.getAllPages();
    Iterator<PDPage> pageIter = pages.iterator();
    while (pageIter.hasNext()) {
        PDPage page = pageIter.next();
        PDPage newPage = new PDPage((COSDictionary) cloner.cloneForNewDocument(page.getCOSDictionary()));
        newPage.setCropBox(page.findCropBox());
        newPage.setMediaBox(page.findMediaBox());
        newPage.setRotation(page.findRotation());
        destination.addPage(newPage);
    }
}

From source file:com.fileOperations.StampPDF.java

/**
 * This stamps docketed files./*from   w w w . jav  a2s .  c o m*/
 *
 * @param file String (full file path)
 * @param docketTime Timestamp
 * @param dept
 */
public static void stampDocument(String file, Timestamp docketTime, String dept) {
    // the document
    PDDocument doc = null;
    try {
        PDFont stampFont = PDType1Font.TIMES_ROMAN;
        float stampFontSize = 14;
        String title = PDFBoxTools.HeaderTimeStamp(docketTime) + " " + dept;
        float titleWidth = stampFont.getStringWidth(title) / 1000 * stampFontSize;
        float titleHeight = stampFont.getFontDescriptor().getFontBoundingBox().getHeight() / 1000
                * stampFontSize;
        int marginTop = 20;

        doc = PDDocument.load(new File(file));

        if (!doc.isEncrypted()) {
            for (int i = 0; i < doc.getPages().getCount(); i++) {
                PDPageContentStream contentStream = null;

                PDPage page = (PDPage) doc.getPages().get(i);

                contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true);
                page.getResources().getFontNames();

                contentStream.beginText();
                contentStream.setFont(stampFont, stampFontSize);
                contentStream.setNonStrokingColor(Color.RED);
                contentStream.newLineAtOffset((page.getMediaBox().getWidth() - titleWidth) / 2,
                        page.getMediaBox().getHeight() - marginTop - titleHeight);
                contentStream.showText(title);
                contentStream.endText();

                contentStream.close();
            }
            doc.save(file);
        }
    } catch (IOException ex) {
        ExceptionHandler.Handle(ex);
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                ExceptionHandler.Handle(ex);
            }
        }
    }
}

From source file:com.itdhq.poc.ocrsign.ShowSignature.java

License:Apache License

private void showSignature(String[] args) throws IOException, CertificateException {
    if (args.length != 2) {
        usage();/*w  w  w. j av a 2  s .c  o m*/
    } else {
        String password = args[0];
        String infile = args[1];
        PDDocument document = null;
        try {
            document = PDDocument.load(new File(infile));
            if (!document.isEncrypted()) {
                System.err.println("Warning: Document is not encrypted.");
            }

            COSDictionary trailer = document.getDocument().getTrailer();
            COSDictionary root = (COSDictionary) trailer.getDictionaryObject(COSName.ROOT);
            COSDictionary acroForm = (COSDictionary) root.getDictionaryObject(COSName.ACRO_FORM);
            COSArray fields = (COSArray) acroForm.getDictionaryObject(COSName.FIELDS);
            for (int i = 0; i < fields.size(); i++) {
                COSDictionary field = (COSDictionary) fields.getObject(i);
                // FIXME
                /*
                COSName type = field.getCOSName( COSName.FT );
                if( COSName.SIG.equals( type ) )
                {
                COSDictionary cert = (COSDictionary)field.getDictionaryObject( COSName.V );
                if( cert != null )
                {
                    System.out.println( "Certificate found" );
                    System.out.println( "Name=" + cert.getDictionaryObject( COSName.NAME ) );
                    System.out.println( "Modified=" + cert.getDictionaryObject( COSName.M ) );
                    COSName subFilter = (COSName)cert.getDictionaryObject( COSName.SUB_FILTER );
                    if( subFilter != null )
                    {
                        if( subFilter.getName().equals( "adbe.x509.rsa_sha1" ) )
                        {
                            COSString certString = (COSString)cert.getDictionaryObject(
                                    COSName.getPDFName( "Cert" ) );
                            byte[] certData = certString.getBytes();
                            CertificateFactory factory = CertificateFactory.getInstance( "X.509" );
                            ByteArrayInputStream certStream = new ByteArrayInputStream( certData );
                            Collection<? extends Certificate> certs = factory.generateCertificates( certStream );
                            System.out.println( "certs=" + certs );
                        }
                        else if( subFilter.getName().equals( "adbe.pkcs7.sha1" ) )
                        {
                            COSString certString = (COSString)cert.getDictionaryObject(
                                    COSName.CONTENTS );
                            byte[] certData = certString.getBytes();
                            CertificateFactory factory = CertificateFactory.getInstance( "X.509" );
                            ByteArrayInputStream certStream = new ByteArrayInputStream( certData );
                            Collection<? extends Certificate> certs = factory.generateCertificates( certStream );
                            System.out.println( "certs=" + certs );
                        }
                        else
                        {
                            System.err.println( "Unknown certificate type:" + subFilter );
                        }
                    }
                    else
                    {
                        throw new IOException( "Missing subfilter for cert dictionary" );
                    }
                }
                else
                {
                    System.out.println( "Signature found, but no certificate" );
                }
                }
                */
            }
        } finally {
            if (document != null) {
                document.close();
            }
        }
    }
}