Example usage for org.apache.pdfbox.pdmodel PDPage getCOSObject

List of usage examples for org.apache.pdfbox.pdmodel PDPage getCOSObject

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel PDPage getCOSObject.

Prototype

@Override
public COSDictionary getCOSObject() 

Source Link

Document

Convert this standard java object to a COS object.

Usage

From source file:at.gv.egiz.pdfas.lib.impl.signing.pdfbox.PADESPDFBOXSigner.java

License:EUPL

public void signPDF(PDFObject genericPdfObject, RequestedSignature requestedSignature,
        PDFASSignatureInterface genericSigner) throws PdfAsException {
    String fisTmpFile = null;//  www . j av  a 2s.c o  m

    PDFAsVisualSignatureProperties properties = null;

    if (!(genericPdfObject instanceof PDFBOXObject)) {
        // tODO:
        throw new PdfAsException();
    }

    PDFBOXObject pdfObject = (PDFBOXObject) genericPdfObject;

    if (!(genericSigner instanceof PDFASPDFBOXSignatureInterface)) {
        // tODO:
        throw new PdfAsException();
    }

    PDFASPDFBOXSignatureInterface signer = (PDFASPDFBOXSignatureInterface) genericSigner;

    TempFileHelper helper = pdfObject.getStatus().getTempFileHelper();
    PDDocument doc = pdfObject.getDocument();
    SignatureOptions options = new SignatureOptions();
    COSDocument visualSignatureDocumentGuard = null;
    try {
        fisTmpFile = helper.getStaticFilename();

        FileOutputStream tmpOutputStream = null;
        try {
            // write to temporary file
            tmpOutputStream = new FileOutputStream(new File(fisTmpFile));
            InputStream tmpis = null;
            try {
                tmpis = pdfObject.getOriginalDocument().getInputStream();
                IOUtils.copy(tmpis, tmpOutputStream);
                tmpis.close();
            } finally {
                IOUtils.closeQuietly(tmpis);
            }

            SignaturePlaceholderData signaturePlaceholderData = PlaceholderFilter
                    .checkPlaceholderSignature(pdfObject.getStatus(), pdfObject.getStatus().getSettings());

            TablePos tablePos = null;

            if (signaturePlaceholderData != null) {
                // Placeholder found!
                logger.info("Placeholder data found.");
                if (signaturePlaceholderData.getProfile() != null) {
                    logger.debug("Placeholder Profile set to: " + signaturePlaceholderData.getProfile());
                    requestedSignature.setSignatureProfileID(signaturePlaceholderData.getProfile());
                }

                tablePos = signaturePlaceholderData.getTablePos();
                if (tablePos != null) {

                    SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus()
                            .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID());

                    float minWidth = signatureProfileConfiguration.getMinWidth();

                    if (minWidth > 0) {
                        if (tablePos.getWidth() < minWidth) {
                            tablePos.width = minWidth;
                            logger.debug("Correcting placeholder with to minimum width {}", minWidth);
                        }
                    }
                    logger.debug("Placeholder Position set to: " + tablePos.toString());
                }
            }

            PDSignature signature = new PDSignature();
            signature.setFilter(COSName.getPDFName(signer.getPDFFilter())); // default
            // filter
            signature.setSubFilter(COSName.getPDFName(signer.getPDFSubFilter()));

            SignatureProfileSettings signatureProfileSettings = TableFactory.createProfile(
                    requestedSignature.getSignatureProfileID(), pdfObject.getStatus().getSettings());

            ValueResolver resolver = new ValueResolver(requestedSignature, pdfObject.getStatus());
            String signerName = resolver.resolve("SIG_SUBJECT",
                    signatureProfileSettings.getValue("SIG_SUBJECT"), signatureProfileSettings);

            signature.setName(signerName);

            // take signing time from provided signer...
            signature.setSignDate(signer.getSigningDate());
            // ...and update operation status in order to use exactly this date for the complete signing process
            requestedSignature.getStatus().setSigningDate(signer.getSigningDate());

            String signerReason = signatureProfileSettings.getSigningReason();

            if (signerReason == null) {
                signerReason = "PAdES Signature";
            }

            signature.setReason(signerReason);
            logger.debug("Signing reason: " + signerReason);

            logger.debug("Signing @ " + signer.getSigningDate().getTime().toString());

            // the signing date, needed for valid signature
            // signature.setSignDate(signer.getSigningDate());

            signer.setPDSignature(signature);

            int signatureSize = 0x1000;
            try {
                String reservedSignatureSizeString = signatureProfileSettings.getValue(SIG_RESERVED_SIZE);
                if (reservedSignatureSizeString != null) {
                    signatureSize = Integer.parseInt(reservedSignatureSizeString);
                }
                logger.debug("Reserving {} bytes for signature", signatureSize);
            } catch (NumberFormatException e) {
                logger.warn("Invalid configuration value: {} should be a number using 0x1000",
                        SIG_RESERVED_SIZE);
            }
            options.setPreferedSignatureSize(signatureSize);

            // Is visible Signature
            if (requestedSignature.isVisual()) {
                logger.debug("Creating visual signature block");

                SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus()
                        .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID());

                if (tablePos == null) {
                    // ================================================================
                    // PositioningStage (visual) -> find position or use
                    // fixed
                    // position

                    String posString = pdfObject.getStatus().getSignParamter().getSignaturePosition();

                    TablePos signaturePos = null;

                    String signaturePosString = signatureProfileConfiguration.getDefaultPositioning();

                    if (signaturePosString != null) {
                        logger.debug("using signature Positioning: " + signaturePos);
                        signaturePos = new TablePos(signaturePosString);
                    }

                    logger.debug("using Positioning: " + posString);

                    if (posString != null) {
                        // Merge Signature Position
                        tablePos = new TablePos(posString, signaturePos);
                    } else {
                        // Fallback to signature Position!
                        tablePos = signaturePos;
                    }

                    if (tablePos == null) {
                        // Last Fallback default position
                        tablePos = new TablePos();
                    }
                }
                boolean legacy32Position = signatureProfileConfiguration.getLegacy32Positioning();
                boolean legacy40Position = signatureProfileConfiguration.getLegacy40Positioning();

                // create Table describtion
                Table main = TableFactory.createSigTable(signatureProfileSettings, MAIN, pdfObject.getStatus(),
                        requestedSignature);

                IPDFStamper stamper = StamperFactory.createDefaultStamper(pdfObject.getStatus().getSettings());

                IPDFVisualObject visualObject = stamper.createVisualPDFObject(pdfObject, main);

                /*
                 * PDDocument originalDocument = PDDocument .load(new
                 * ByteArrayInputStream(pdfObject.getStatus()
                 * .getPdfObject().getOriginalDocument()));
                 */

                PositioningInstruction positioningInstruction = Positioning.determineTablePositioning(tablePos,
                        "", doc, visualObject, legacy32Position, legacy40Position);

                logger.debug("Positioning: {}", positioningInstruction.toString());

                if (positioningInstruction.isMakeNewPage()) {
                    int last = doc.getNumberOfPages() - 1;
                    PDDocumentCatalog root = doc.getDocumentCatalog();
                    PDPageNode rootPages = root.getPages();
                    List<PDPage> kids = new ArrayList<PDPage>();
                    rootPages.getAllKids(kids);
                    PDPage lastPage = kids.get(last);
                    rootPages.getCOSObject().setNeedToBeUpdate(true);
                    PDPage p = new PDPage(lastPage.findMediaBox());
                    p.setResources(new PDResources());
                    p.setRotation(lastPage.findRotation());
                    doc.addPage(p);
                }

                // handle rotated page
                PDDocumentCatalog documentCatalog = doc.getDocumentCatalog();
                PDPageNode documentPages = documentCatalog.getPages();
                List<PDPage> documentPagesKids = new ArrayList<PDPage>();
                documentPages.getAllKids(documentPagesKids);
                int targetPageNumber = positioningInstruction.getPage();
                logger.debug("Target Page: " + targetPageNumber);
                // rootPages.getAllKids(kids);
                PDPage targetPage = documentPagesKids.get(targetPageNumber - 1);
                int rot = targetPage.findRotation();
                logger.debug("Page rotation: " + rot);
                // positioningInstruction.setRotation(positioningInstruction.getRotation()
                // + rot);
                logger.debug("resulting Sign rotation: " + positioningInstruction.getRotation());

                SignaturePositionImpl position = new SignaturePositionImpl();
                position.setX(positioningInstruction.getX());
                position.setY(positioningInstruction.getY());
                position.setPage(positioningInstruction.getPage());
                position.setHeight(visualObject.getHeight());
                position.setWidth(visualObject.getWidth());

                requestedSignature.setSignaturePosition(position);

                properties = new PDFAsVisualSignatureProperties(pdfObject.getStatus().getSettings(), pdfObject,
                        (PdfBoxVisualObject) visualObject, positioningInstruction, signatureProfileSettings);

                properties.buildSignature();

                /*
                 * ByteArrayOutputStream sigbos = new
                 * ByteArrayOutputStream();
                 * sigbos.write(StreamUtils.inputStreamToByteArray
                 * (properties .getVisibleSignature())); sigbos.close();
                 */

                if (signaturePlaceholderData != null) {
                    // Placeholder found!
                    // replace placeholder
                    InputStream is = null;
                    try {
                        is = PADESPDFBOXSigner.class.getResourceAsStream("/placeholder/empty.jpg");
                        PDJpeg img = new PDJpeg(doc, is);

                        img.getCOSObject().setNeedToBeUpdate(true);

                        PDDocumentCatalog root = doc.getDocumentCatalog();
                        PDPageNode rootPages = root.getPages();
                        List<PDPage> kids = new ArrayList<PDPage>();
                        rootPages.getAllKids(kids);
                        int pageNumber = positioningInstruction.getPage();
                        // rootPages.getAllKids(kids);
                        PDPage page = kids.get(pageNumber - 1);

                        logger.info("Placeholder name: " + signaturePlaceholderData.getPlaceholderName());
                        COSDictionary xobjectsDictionary = (COSDictionary) page.findResources()
                                .getCOSDictionary().getDictionaryObject(COSName.XOBJECT);
                        xobjectsDictionary.setItem(signaturePlaceholderData.getPlaceholderName(), img);
                        xobjectsDictionary.setNeedToBeUpdate(true);
                        page.findResources().getCOSObject().setNeedToBeUpdate(true);
                        logger.info("Placeholder name: " + signaturePlaceholderData.getPlaceholderName());
                    } finally {
                        IOUtils.closeQuietly(is);
                    }
                }

                if (signatureProfileSettings.isPDFA()) {
                    PDDocumentCatalog root = doc.getDocumentCatalog();
                    COSBase base = root.getCOSDictionary().getItem(COSName.OUTPUT_INTENTS);
                    if (base == null) {
                        InputStream colorProfile = null;
                        try {
                            colorProfile = PDDocumentCatalog.class
                                    .getResourceAsStream("/icm/sRGB Color Space Profile.icm");

                            try {
                                PDOutputIntent oi = new PDOutputIntent(doc, colorProfile);
                                oi.setInfo("sRGB IEC61966-2.1");
                                oi.setOutputCondition("sRGB IEC61966-2.1");
                                oi.setOutputConditionIdentifier("sRGB IEC61966-2.1");
                                oi.setRegistryName("http://www.color.org");

                                root.addOutputIntent(oi);
                                root.getCOSObject().setNeedToBeUpdate(true);
                                logger.info("added Output Intent");
                            } catch (Throwable e) {
                                throw new PdfAsException("Failed to add Output Intent", e);
                            }
                        } finally {
                            IOUtils.closeQuietly(colorProfile);
                        }
                    }
                }

                options.setPage(positioningInstruction.getPage());

                options.setVisualSignature(properties.getVisibleSignature());
            }

            visualSignatureDocumentGuard = options.getVisualSignature();

            doc.addSignature(signature, signer, options);

            // set need to update indirect fields array in acro form
            COSDictionary trailer = doc.getDocument().getTrailer();
            if (trailer != null) {
                COSDictionary troot = (COSDictionary) trailer.getDictionaryObject(COSName.ROOT);
                if (troot != null) {
                    COSDictionary acroForm = (COSDictionary) troot.getDictionaryObject(COSName.ACRO_FORM);
                    if (acroForm != null) {
                        COSArray tfields = (COSArray) acroForm.getDictionaryObject(COSName.FIELDS);
                        if (tfields != null && !tfields.isDirect()) {
                            tfields.setNeedToBeUpdate(true);
                        }
                    }
                }
            }

            String sigFieldName = signatureProfileSettings.getSignFieldValue();

            if (sigFieldName == null) {
                sigFieldName = "PDF-AS Signatur";
            }

            int count = PdfBoxUtils.countSignatures(doc, sigFieldName);

            sigFieldName = sigFieldName + count;

            PDAcroForm acroFormm = doc.getDocumentCatalog().getAcroForm();

            PDSignatureField signatureField = null;
            if (acroFormm != null) {
                @SuppressWarnings("unchecked")
                List<PDField> fields = acroFormm.getFields();

                if (fields != null) {
                    for (PDField pdField : fields) {
                        if (pdField != null) {
                            if (pdField instanceof PDSignatureField) {
                                PDSignatureField tmpSigField = (PDSignatureField) pdField;

                                if (tmpSigField.getSignature() != null
                                        && tmpSigField.getSignature().getDictionary() != null) {
                                    if (tmpSigField.getSignature().getDictionary()
                                            .equals(signature.getDictionary())) {
                                        signatureField = (PDSignatureField) pdField;

                                    }
                                }
                            }
                        }
                    }
                } else {
                    logger.warn("Failed to name Signature Field! [Cannot find Field list in acroForm!]");
                }

                if (signatureField != null) {
                    signatureField.setPartialName(sigFieldName);
                }
                if (properties != null) {
                    signatureField.setAlternateFieldName(properties.getAlternativeTableCaption());
                } else {
                    signatureField.setAlternateFieldName(sigFieldName);
                }
            } else {
                logger.warn("Failed to name Signature Field! [Cannot find acroForm!]");
            }

            // PDF-UA
            logger.info("Adding pdf/ua content.");
            try {
                PDDocumentCatalog root = doc.getDocumentCatalog();
                PDStructureTreeRoot structureTreeRoot = root.getStructureTreeRoot();
                if (structureTreeRoot != null) {
                    logger.info("Tree Root: {}", structureTreeRoot.toString());
                    List<Object> kids = structureTreeRoot.getKids();

                    if (kids == null) {
                        logger.info("No kid-elements in structure tree Root, maybe not PDF/UA document");
                    }

                    PDStructureElement docElement = null;
                    for (Object k : kids) {
                        if (k instanceof PDStructureElement) {
                            docElement = (PDStructureElement) k;
                            break;

                        }
                    }

                    PDStructureElement sigBlock = new PDStructureElement("Form", docElement);

                    // create object dictionary and add as child element
                    COSDictionary objectDic = new COSDictionary();
                    objectDic.setName("Type", "OBJR");
                    objectDic.setItem("Pg", signatureField.getWidget().getPage());
                    objectDic.setItem("Obj", signatureField.getWidget());

                    List<Object> l = new ArrayList<Object>();
                    l.add(objectDic);
                    sigBlock.setKids(l);
                    sigBlock.setPage(signatureField.getWidget().getPage());

                    sigBlock.setTitle("Signature Table");
                    sigBlock.setParent(docElement);
                    docElement.appendKid(sigBlock);

                    // Create and add Attribute dictionary to mitigate PAC
                    // warning
                    COSDictionary sigBlockDic = (COSDictionary) sigBlock.getCOSObject();
                    COSDictionary sub = new COSDictionary();

                    sub.setName("O", "Layout");
                    sub.setName("Placement", "Block");
                    sigBlockDic.setItem(COSName.A, sub);
                    sigBlockDic.setNeedToBeUpdate(true);

                    // Modify number tree
                    PDNumberTreeNode ntn = structureTreeRoot.getParentTree();
                    int parentTreeNextKey = structureTreeRoot.getParentTreeNextKey();
                    if (ntn == null) {
                        ntn = new PDNumberTreeNode(objectDic, null);
                        logger.info("No number-tree-node found!");
                    }

                    COSArray ntnKids = (COSArray) ntn.getCOSDictionary().getDictionaryObject(COSName.KIDS);
                    COSArray ntnNumbers = (COSArray) ntn.getCOSDictionary().getDictionaryObject(COSName.NUMS);

                    if (ntnNumbers == null && ntnKids != null) {//no number array, so continue with the kids array

                        //create dictionary with limits and nums array
                        COSDictionary pTreeEntry = new COSDictionary();
                        COSArray limitsArray = new COSArray();
                        //limits for exact one entry
                        limitsArray.add(COSInteger.get(parentTreeNextKey));
                        limitsArray.add(COSInteger.get(parentTreeNextKey));

                        COSArray numsArray = new COSArray();
                        numsArray.add(COSInteger.get(parentTreeNextKey));
                        numsArray.add(sigBlock);

                        pTreeEntry.setItem(COSName.NUMS, numsArray);
                        pTreeEntry.setItem(COSName.LIMITS, limitsArray);

                        PDNumberTreeNode newKidsElement = new PDNumberTreeNode(pTreeEntry,
                                PDNumberTreeNode.class);

                        ntnKids.add(newKidsElement);
                        ntnKids.setNeedToBeUpdate(true);

                        //working
                        //                     List<PDNumberTreeNode> treeRootKids = structureTreeRoot.getParentTree().getKids();
                        //                     PDNumberTreeNode last = (PDNumberTreeNode)treeRootKids.get(treeRootKids.size()-1);
                        //                     COSArray lim1 = (COSArray) last.getCOSDictionary().getDictionaryObject(COSName.LIMITS);
                        //                     lim1.remove(1);
                        //                     lim1.add(1, COSInteger.get(parentTreeNextKey));
                        //                     PDNumberTreeNode verylast = (PDNumberTreeNode)last.getKids().get(last.getKids().size()-1);
                        //                     COSArray numa = (COSArray) verylast.getCOSDictionary().getDictionaryObject(COSName.NUMS);
                        //                     COSArray lim = (COSArray) verylast.getCOSDictionary().getDictionaryObject(COSName.LIMITS);
                        //                     lim.remove(1);
                        //                     lim.add(1, COSInteger.get(parentTreeNextKey));
                        //
                        //                     int size = numa.size();
                        //                     numa.add(size, COSInteger.get(parentTreeNextKey));
                        //                     numa.add(sigBlock);
                        //working end

                    } else if (ntnNumbers != null && ntnKids == null) {

                        int arrindex = ntnNumbers.size();

                        ntnNumbers.add(arrindex, COSInteger.get(parentTreeNextKey));
                        ntnNumbers.add(arrindex + 1, sigBlock.getCOSObject());

                        ntnNumbers.getCOSObject().setNeedToBeUpdate(true);

                        structureTreeRoot.setParentTree(ntn);

                    } else if (ntnNumbers == null && ntnKids == null) {
                        //document is not pdfua conform before signature creation
                        throw new PdfAsException("error.pdf.sig.pdfua.1");
                    } else {
                        //this is not allowed
                        throw new PdfAsException("error.pdf.sig.pdfua.1");
                    }

                    // set StructureParent for signature field annotation
                    signatureField.getWidget().setStructParent(parentTreeNextKey);

                    //Increase the next Key value in the structure tree root
                    structureTreeRoot.setParentTreeNextKey(parentTreeNextKey + 1);

                    // add the Tabs /S Element for Tabbing through annots
                    PDPage p = signatureField.getWidget().getPage();
                    p.getCOSDictionary().setName("Tabs", "S");
                    p.getCOSObject().setNeedToBeUpdate(true);

                    //check alternative signature field name
                    if (signatureField != null) {
                        if (signatureField.getAlternateFieldName().equals(""))
                            signatureField.setAlternateFieldName(sigFieldName);
                    }

                    ntn.getCOSDictionary().setNeedToBeUpdate(true);
                    sigBlock.getCOSObject().setNeedToBeUpdate(true);
                    structureTreeRoot.getCOSObject().setNeedToBeUpdate(true);
                    objectDic.getCOSObject().setNeedToBeUpdate(true);
                    docElement.getCOSObject().setNeedToBeUpdate(true);

                }

            } catch (Throwable e) {
                if (signatureProfileSettings.isPDFUA() == true) {
                    logger.error("Could not create PDF-UA conform document!");
                    throw new PdfAsException("error.pdf.sig.pdfua.1", e);
                } else {
                    logger.info("Could not create PDF-UA conform signature");
                }
            }

            try {
                applyFilter(doc, requestedSignature);
            } catch (PDFASError e) {
                throw new PdfAsErrorCarrier(e);
            }

            FileInputStream tmpFileIs = null;

            try {
                tmpFileIs = new FileInputStream(new File(fisTmpFile));
                synchronized (doc) {
                    doc.saveIncremental(tmpFileIs, tmpOutputStream);
                }
                tmpFileIs.close();
            } finally {
                IOUtils.closeQuietly(tmpFileIs);
                if (options != null) {
                    if (options.getVisualSignature() != null) {
                        options.getVisualSignature().close();
                    }
                }
            }
            tmpOutputStream.flush();
            tmpOutputStream.close();
        } finally {
            IOUtils.closeQuietly(tmpOutputStream);
            COSDocument visualSignature = options.getVisualSignature();
            if (visualSignature != null) {
                visualSignature.close();
            }
        }

        FileInputStream readReadyFile = null;
        try {
            readReadyFile = new FileInputStream(new File(fisTmpFile));

            // write to resulting output stream
            // ByteArrayOutputStream bos = new ByteArrayOutputStream();
            // bos.write();
            // bos.close();

            pdfObject.setSignedDocument(StreamUtils.inputStreamToByteArray(readReadyFile));
            readReadyFile.close();
        } finally {
            IOUtils.closeQuietly(readReadyFile);
        }
    } catch (IOException e) {
        logger.info(MessageResolver.resolveMessage("error.pdf.sig.01") + ": {}", e.toString());
        throw new PdfAsException("error.pdf.sig.01", e);
    } catch (SignatureException e) {
        logger.info(MessageResolver.resolveMessage("error.pdf.sig.01") + ": {}", e.toString());
        throw new PdfAsException("error.pdf.sig.01", e);
    } catch (COSVisitorException e) {
        logger.info(MessageResolver.resolveMessage("error.pdf.sig.01") + ": {}", e.toString());
        throw new PdfAsException("error.pdf.sig.01", e);
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException e) {
                logger.debug("Failed to close COS Doc!", e);
                // Ignore
            }
        }

        if (fisTmpFile != null) {
            helper.deleteFile(fisTmpFile);
        }
        logger.debug("Signature done!");

    }
}

From source file:at.gv.egiz.pdfas.lib.impl.signing.pdfbox2.PADESPDFBOXSigner.java

License:EUPL

public void signPDF(PDFObject genericPdfObject, RequestedSignature requestedSignature,
        PDFASSignatureInterface genericSigner) throws PdfAsException {
    //String fisTmpFile = null;

    PDFAsVisualSignatureProperties properties = null;

    if (!(genericPdfObject instanceof PDFBOXObject)) {
        // tODO://w  ww. j a v  a  2s.  c  om
        throw new PdfAsException();
    }

    PDFBOXObject pdfObject = (PDFBOXObject) genericPdfObject;

    if (!(genericSigner instanceof PDFASPDFBOXSignatureInterface)) {
        // tODO:
        throw new PdfAsException();
    }

    PDFASPDFBOXSignatureInterface signer = (PDFASPDFBOXSignatureInterface) genericSigner;

    String pdfaVersion = null;

    PDDocument doc = null;
    SignatureOptions options = new SignatureOptions();
    COSDocument visualSignatureDocumentGuard = null;
    try {

        doc = pdfObject.getDocument();

        SignaturePlaceholderData signaturePlaceholderData = PlaceholderFilter
                .checkPlaceholderSignature(pdfObject.getStatus(), pdfObject.getStatus().getSettings());

        TablePos tablePos = null;

        if (signaturePlaceholderData != null) {
            // Placeholder found!
            logger.info("Placeholder data found.");
            if (signaturePlaceholderData.getProfile() != null) {
                logger.debug("Placeholder Profile set to: " + signaturePlaceholderData.getProfile());
                requestedSignature.setSignatureProfileID(signaturePlaceholderData.getProfile());
            }

            tablePos = signaturePlaceholderData.getTablePos();
            if (tablePos != null) {

                SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus()
                        .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID());

                float minWidth = signatureProfileConfiguration.getMinWidth();

                if (minWidth > 0) {
                    if (tablePos.getWidth() < minWidth) {
                        tablePos.width = minWidth;
                        logger.debug("Correcting placeholder with to minimum width {}", minWidth);
                    }
                }
                logger.debug("Placeholder Position set to: " + tablePos.toString());
            }
        }

        PDSignature signature = new PDSignature();
        signature.setFilter(COSName.getPDFName(signer.getPDFFilter())); // default
        // filter
        signature.setSubFilter(COSName.getPDFName(signer.getPDFSubFilter()));

        SignatureProfileSettings signatureProfileSettings = TableFactory
                .createProfile(requestedSignature.getSignatureProfileID(), pdfObject.getStatus().getSettings());

        /*
         * Check if input document is PDF-A conform
         *
        if (signatureProfileSettings.isPDFA()) {
           // TODO: run preflight parser
           runPDFAPreflight(pdfObject.getOriginalDocument());
        }
        */

        ValueResolver resolver = new ValueResolver(requestedSignature, pdfObject.getStatus());
        String signerName = resolver.resolve("SIG_SUBJECT", signatureProfileSettings.getValue("SIG_SUBJECT"),
                signatureProfileSettings);

        signature.setName(signerName);

        // take signing time from provided signer...
        signature.setSignDate(signer.getSigningDate());
        // ...and update operation status in order to use exactly this date for the complete signing process
        requestedSignature.getStatus().setSigningDate(signer.getSigningDate());

        String signerReason = signatureProfileSettings.getSigningReason();

        if (signerReason == null) {
            signerReason = "PAdES Signature";
        }

        signature.setReason(signerReason);
        logger.debug("Signing reason: " + signerReason);

        logger.debug("Signing @ " + signer.getSigningDate().getTime().toString());
        // the signing date, needed for valid signature
        // signature.setSignDate(signer.getSigningDate());

        signer.setPDSignature(signature);

        int signatureSize = 0x1000;
        try {
            String reservedSignatureSizeString = signatureProfileSettings.getValue(SIG_RESERVED_SIZE);
            if (reservedSignatureSizeString != null) {
                signatureSize = Integer.parseInt(reservedSignatureSizeString);
            }
            logger.debug("Reserving {} bytes for signature", signatureSize);
        } catch (NumberFormatException e) {
            logger.warn("Invalid configuration value: {} should be a number using 0x1000", SIG_RESERVED_SIZE);
        }
        options.setPreferredSignatureSize(signatureSize);

        if (signatureProfileSettings.isPDFA() || signatureProfileSettings.isPDFA3()) {
            pdfaVersion = getPDFAVersion(doc);
            signatureProfileSettings.setPDFAVersion(pdfaVersion);
        }

        // Is visible Signature
        if (requestedSignature.isVisual()) {
            logger.debug("Creating visual signature block");

            SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus()
                    .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID());

            if (tablePos == null) {
                // ================================================================
                // PositioningStage (visual) -> find position or use
                // fixed
                // position

                String posString = pdfObject.getStatus().getSignParamter().getSignaturePosition();

                TablePos signaturePos = null;

                String signaturePosString = signatureProfileConfiguration.getDefaultPositioning();

                if (signaturePosString != null) {
                    logger.debug("using signature Positioning: " + signaturePos);
                    signaturePos = new TablePos(signaturePosString);
                }

                logger.debug("using Positioning: " + posString);

                if (posString != null) {
                    // Merge Signature Position
                    tablePos = new TablePos(posString, signaturePos);
                } else {
                    // Fallback to signature Position!
                    tablePos = signaturePos;
                }

                if (tablePos == null) {
                    // Last Fallback default position
                    tablePos = new TablePos();
                }
            }

            //Legacy Modes not supported with pdfbox2 anymore
            //            boolean legacy32Position = signatureProfileConfiguration.getLegacy32Positioning();
            //            boolean legacy40Position = signatureProfileConfiguration.getLegacy40Positioning();

            // create Table describtion
            Table main = TableFactory.createSigTable(signatureProfileSettings, MAIN, pdfObject.getStatus(),
                    requestedSignature);

            IPDFStamper stamper = StamperFactory.createDefaultStamper(pdfObject.getStatus().getSettings());

            IPDFVisualObject visualObject = stamper.createVisualPDFObject(pdfObject, main);

            /*
             * PDDocument originalDocument = PDDocument .load(new
             * ByteArrayInputStream(pdfObject.getStatus()
             * .getPdfObject().getOriginalDocument()));
             */

            PositioningInstruction positioningInstruction = Positioning.determineTablePositioning(tablePos, "",
                    doc, visualObject, pdfObject.getStatus().getSettings());

            logger.debug("Positioning: {}", positioningInstruction.toString());

            if (positioningInstruction.isMakeNewPage()) {
                int last = doc.getNumberOfPages() - 1;
                PDDocumentCatalog root = doc.getDocumentCatalog();
                PDPage lastPage = root.getPages().get(last);
                root.getPages().getCOSObject().setNeedToBeUpdated(true);
                PDPage p = new PDPage(lastPage.getMediaBox());
                p.setResources(new PDResources());
                p.setRotation(lastPage.getRotation());
                doc.addPage(p);
            }

            // handle rotated page
            int targetPageNumber = positioningInstruction.getPage();
            logger.debug("Target Page: " + targetPageNumber);
            PDPage targetPage = doc.getPages().get(targetPageNumber - 1);
            int rot = targetPage.getRotation();
            logger.debug("Page rotation: " + rot);
            // positioningInstruction.setRotation(positioningInstruction.getRotation()
            // + rot);
            logger.debug("resulting Sign rotation: " + positioningInstruction.getRotation());

            SignaturePositionImpl position = new SignaturePositionImpl();
            position.setX(positioningInstruction.getX());
            position.setY(positioningInstruction.getY());
            position.setPage(positioningInstruction.getPage());
            position.setHeight(visualObject.getHeight());
            position.setWidth(visualObject.getWidth());

            requestedSignature.setSignaturePosition(position);

            properties = new PDFAsVisualSignatureProperties(pdfObject.getStatus().getSettings(), pdfObject,
                    (PdfBoxVisualObject) visualObject, positioningInstruction, signatureProfileSettings);

            properties.buildSignature();

            /*
             * ByteArrayOutputStream sigbos = new
             * ByteArrayOutputStream();
             * sigbos.write(StreamUtils.inputStreamToByteArray
             * (properties .getVisibleSignature())); sigbos.close();
             */

            if (signaturePlaceholderData != null) {
                // Placeholder found!
                // replace placeholder

                URL fileUrl = PADESPDFBOXSigner.class.getResource("/placeholder/empty.jpg");

                PDImageXObject img = PDImageXObject.createFromFile(fileUrl.getPath(), doc);

                img.getCOSObject().setNeedToBeUpdated(true);
                //                     PDDocumentCatalog root = doc.getDocumentCatalog();
                //                     PDPageNode rootPages = root.getPages();
                //                     List<PDPage> kids = new ArrayList<PDPage>();
                //                     rootPages.getAllKids(kids);
                int pageNumber = positioningInstruction.getPage();
                PDPage page = doc.getPages().get(pageNumber - 1);

                logger.info("Placeholder name: " + signaturePlaceholderData.getPlaceholderName());
                COSDictionary xobjectsDictionary = (COSDictionary) page.getResources().getCOSObject()
                        .getDictionaryObject(COSName.XOBJECT);
                xobjectsDictionary.setItem(signaturePlaceholderData.getPlaceholderName(), img);
                xobjectsDictionary.setNeedToBeUpdated(true);
                page.getResources().getCOSObject().setNeedToBeUpdated(true);
                logger.info("Placeholder name: " + signaturePlaceholderData.getPlaceholderName());

            }

            if (signatureProfileSettings.isPDFA() || signatureProfileSettings.isPDFA3()) {
                PDDocumentCatalog root = doc.getDocumentCatalog();
                COSBase base = root.getCOSObject().getItem(COSName.OUTPUT_INTENTS);
                if (base == null) {
                    InputStream colorProfile = null;
                    try {
                        colorProfile = PDDocumentCatalog.class
                                .getResourceAsStream("/icm/sRGB Color Space Profile.icm");

                        try {
                            PDOutputIntent oi = new PDOutputIntent(doc, colorProfile);
                            oi.setInfo("sRGB IEC61966-2.1");
                            oi.setOutputCondition("sRGB IEC61966-2.1");
                            oi.setOutputConditionIdentifier("sRGB IEC61966-2.1");
                            oi.setRegistryName("http://www.color.org");

                            root.addOutputIntent(oi);
                            root.getCOSObject().setNeedToBeUpdated(true);
                            logger.info("added Output Intent");
                        } catch (Throwable e) {
                            e.printStackTrace();
                            throw new PdfAsException("Failed to add Output Intent", e);
                        }
                    } finally {
                        IOUtils.closeQuietly(colorProfile);
                    }
                }
            }

            options.setPage(positioningInstruction.getPage());

            options.setVisualSignature(properties.getVisibleSignature());
        }

        visualSignatureDocumentGuard = options.getVisualSignature();

        doc.addSignature(signature, signer, options);

        String sigFieldName = signatureProfileSettings.getSignFieldValue();

        if (sigFieldName == null) {
            sigFieldName = "PDF-AS Signatur";
        }

        int count = PdfBoxUtils.countSignatures(doc, sigFieldName);

        sigFieldName = sigFieldName + count;

        PDAcroForm acroFormm = doc.getDocumentCatalog().getAcroForm();

        // PDStructureTreeRoot pdstRoot =
        // doc.getDocumentCatalog().getStructureTreeRoot();
        // COSDictionary dic =
        // doc.getDocumentCatalog().getCOSDictionary();
        // PDStructureElement el = new PDStructureElement("Widget",
        // pdstRoot);

        PDSignatureField signatureField = null;
        if (acroFormm != null) {
            @SuppressWarnings("unchecked")
            List<PDField> fields = acroFormm.getFields();

            if (fields != null) {
                for (PDField pdField : fields) {
                    if (pdField != null) {
                        if (pdField instanceof PDSignatureField) {
                            PDSignatureField tmpSigField = (PDSignatureField) pdField;

                            if (tmpSigField.getSignature() != null
                                    && tmpSigField.getSignature().getCOSObject() != null) {
                                if (tmpSigField.getSignature().getCOSObject()
                                        .equals(signature.getCOSObject())) {
                                    signatureField = (PDSignatureField) pdField;

                                }
                            }
                        }
                    }
                }
            } else {
                logger.warn("Failed to name Signature Field! [Cannot find Field list in acroForm!]");
            }

            if (signatureField != null) {
                signatureField.setPartialName(sigFieldName);
            }
            if (properties != null) {
                signatureField.setAlternateFieldName(properties.getAlternativeTableCaption());
            } else {
                signatureField.setAlternateFieldName(sigFieldName);
            }
        } else {
            logger.warn("Failed to name Signature Field! [Cannot find acroForm!]");
        }

        // PDF-UA
        logger.info("Adding pdf/ua content.");
        try {
            PDDocumentCatalog root = doc.getDocumentCatalog();
            PDStructureTreeRoot structureTreeRoot = root.getStructureTreeRoot();
            if (structureTreeRoot != null) {
                logger.info("Tree Root: {}", structureTreeRoot.toString());
                List<Object> kids = structureTreeRoot.getKids();

                if (kids == null) {
                    logger.info("No kid-elements in structure tree Root, maybe not PDF/UA document");
                }

                PDStructureElement docElement = null;
                for (Object k : kids) {
                    if (k instanceof PDStructureElement) {
                        docElement = (PDStructureElement) k;
                        break;

                    }
                }

                PDStructureElement sigBlock = new PDStructureElement("Form", docElement);

                // create object dictionary and add as child element
                COSDictionary objectDic = new COSDictionary();
                objectDic.setName("Type", "OBJR");
                objectDic.setItem("Pg", signatureField.getWidget().getPage());
                objectDic.setItem("Obj", signatureField.getWidget());

                List<Object> l = new ArrayList<Object>();
                l.add(objectDic);
                sigBlock.setKids(l);
                sigBlock.setPage(signatureField.getWidget().getPage());

                sigBlock.setTitle("Signature Table");
                sigBlock.setParent(docElement);
                docElement.appendKid(sigBlock);

                // Create and add Attribute dictionary to mitigate PAC
                // warning
                COSDictionary sigBlockDic = (COSDictionary) sigBlock.getCOSObject();
                COSDictionary sub = new COSDictionary();

                sub.setName("O", "Layout");
                sub.setName("Placement", "Block");
                sigBlockDic.setItem(COSName.A, sub);
                sigBlockDic.setNeedToBeUpdated(true);

                // Modify number tree
                PDNumberTreeNode ntn = structureTreeRoot.getParentTree();
                int parentTreeNextKey = structureTreeRoot.getParentTreeNextKey();
                if (ntn == null) {
                    ntn = new PDNumberTreeNode(objectDic, null);
                    logger.info("No number-tree-node found!");
                }

                COSArray ntnKids = (COSArray) ntn.getCOSObject().getDictionaryObject(COSName.KIDS);
                COSArray ntnNumbers = (COSArray) ntn.getCOSObject().getDictionaryObject(COSName.NUMS);

                if (ntnNumbers == null && ntnKids != null) {//no number array, so continue with the kids array

                    //create dictionary with limits and nums array
                    COSDictionary pTreeEntry = new COSDictionary();
                    COSArray limitsArray = new COSArray();
                    //limits for exact one entry
                    limitsArray.add(COSInteger.get(parentTreeNextKey));
                    limitsArray.add(COSInteger.get(parentTreeNextKey));

                    COSArray numsArray = new COSArray();
                    numsArray.add(COSInteger.get(parentTreeNextKey));
                    numsArray.add(sigBlock);

                    pTreeEntry.setItem(COSName.NUMS, numsArray);
                    pTreeEntry.setItem(COSName.LIMITS, limitsArray);

                    PDNumberTreeNode newKidsElement = new PDNumberTreeNode(pTreeEntry, PDNumberTreeNode.class);

                    ntnKids.add(newKidsElement);
                    ntnKids.setNeedToBeUpdated(true);

                } else if (ntnNumbers != null && ntnKids == null) {

                    int arrindex = ntnNumbers.size();

                    ntnNumbers.add(arrindex, COSInteger.get(parentTreeNextKey));
                    ntnNumbers.add(arrindex + 1, sigBlock.getCOSObject());

                    ntnNumbers.setNeedToBeUpdated(true);

                    structureTreeRoot.setParentTree(ntn);

                } else if (ntnNumbers == null && ntnKids == null) {
                    //document is not pdfua conform before signature creation
                    throw new PdfAsException("error.pdf.sig.pdfua.1");
                } else {
                    //this is not allowed
                    throw new PdfAsException("error.pdf.sig.pdfua.1");
                }

                // set StructureParent for signature field annotation
                signatureField.getWidget().setStructParent(parentTreeNextKey);

                //Increase the next Key value in the structure tree root
                structureTreeRoot.setParentTreeNextKey(parentTreeNextKey + 1);

                // add the Tabs /S Element for Tabbing through annots
                PDPage p = signatureField.getWidget().getPage();
                p.getCOSObject().setName("Tabs", "S");
                p.getCOSObject().setNeedToBeUpdated(true);

                //check alternative signature field name
                if (signatureField != null) {
                    if (signatureField.getAlternateFieldName().equals(""))
                        signatureField.setAlternateFieldName(sigFieldName);
                }

                ntn.getCOSObject().setNeedToBeUpdated(true);
                sigBlock.getCOSObject().setNeedToBeUpdated(true);
                structureTreeRoot.getCOSObject().setNeedToBeUpdated(true);
                objectDic.setNeedToBeUpdated(true);
                docElement.getCOSObject().setNeedToBeUpdated(true);

            }
        } catch (Throwable e) {
            if (signatureProfileSettings.isPDFUA() == true) {
                logger.error("Could not create PDF-UA conform document!");
                throw new PdfAsException("error.pdf.sig.pdfua.1", e);
            } else {
                logger.info("Could not create PDF-UA conform signature");
            }
        }

        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            synchronized (doc) {
                doc.saveIncremental(bos);
                byte[] outputDocument = bos.toByteArray();

                /*
                Check if resulting pdf is PDF-A conform
                 */
                //if (signatureProfileSettings.isPDFA()) {
                //   // TODO: run preflight parser
                //   runPDFAPreflight(outputDocument);
                //}

                pdfObject.setSignedDocument(outputDocument);
            }

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

        System.gc();
    } catch (IOException e) {
        logger.warn(MessageResolver.resolveMessage("error.pdf.sig.01"), e);
        throw new PdfAsException("error.pdf.sig.01", e);
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException e) {
                logger.debug("Failed to close COS Doc!", e);
                // Ignore
            }
        }

        logger.debug("Signature done!");

    }
}

From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox2.PDFAsVisualSignatureBuilder.java

License:EUPL

@Override
public void injectProcSetArray(PDFormXObject innerForm, PDPage page, PDResources innerFormResources,
        PDResources imageFormResources, PDResources holderFormResources, COSArray procSet) {
    innerForm.getResources().getCOSObject().setItem(COSName.PROC_SET, procSet); //
    page.getCOSObject().setItem(COSName.PROC_SET, procSet);
    innerFormResources.getCOSObject().setItem(COSName.PROC_SET, procSet);
    /*/*w  ww.j  a  va  2 s  .c  om*/
     * imageFormResources.getCOSDictionary() .setItem(COSName.PROC_SET,
     * procSet);
     */
    holderFormResources.getCOSObject().setItem(COSName.PROC_SET, procSet);
    logger.debug("inserted ProcSet to PDF");
}

From source file:cdiscisa.StreamUtil.java

private static void imprimirDiplomas(ArrayList<Participante> listaParticipantes, Curso c, Directorio d,
            String chkDipFirma, String chkDipLogo, String savePath, Map<String, String> dosc, String instructor,
            Map<String, String> abreviaturas) throws IOException {

        ListIterator<Participante> it = listaParticipantes.listIterator();
        Participante p1 = null;/*from w  w w  .ja  va2s  . co  m*/
        Participante p2 = null;
        String abrev_curso = "";

        // Create a document and add a page to it
        PDDocument document = new PDDocument();
        PDDocument documentSingle;

        InputStream file = null;

        BufferedImage logo = null;
        BufferedImage firma = null;

        try {

            //logo = new File(cdiscisa.Cdiscisa.class.getClassLoader().getResource("files/logo.png").getFile());
            //logo = cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/logo.png");
            logo = ImageIO.read(cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/logo.png"));
            //logo = cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/logo.png");

            if (instructor.equalsIgnoreCase("Ing. Jorge Antonio Razn Gutierrez")) {
                //firma = new File(cdiscisa.Cdiscisa.class.getClassLoader().getResource("files/firmaCoco.png").getFile());
                firma = ImageIO
                        .read(cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/firmaCoco.png"));
            } else if (instructor.equalsIgnoreCase("Manuel Anguiano Razn")) {
                firma = ImageIO.read(
                        cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/firmaManuel.png"));
                //firma = new File(cdiscisa.Cdiscisa.class.getClassLoader().getResource("files/firmaManuel.png").getFile());
            } else {
                firma = ImageIO
                        .read(cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/firmaJorge.png"));
                //firma = new File(cdiscisa.Cdiscisa.class.getClassLoader().getResource("files/firmaJorge.png").getFile());
            }

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al cargar la imagen del logo o la firma \nfile: "
                    + String.valueOf(logo) + "\n" + String.valueOf(firma) + "\n" + ex.toString());
        }

        PDImageXObject firmaObject = null;
        PDImageXObject logoObject = null;

        try {
            if (chkDipLogo.equalsIgnoreCase("true")) {
                //logoObject = PDImageXObject.createFromFile(logo, document);                
                logoObject = LosslessFactory.createFromImage(document, logo);
            }

            if (chkDipFirma.equalsIgnoreCase("true")) {
                // firmaObject = PDImageXObject.createFromFile(firma, document);
                firmaObject = LosslessFactory.createFromImage(document, firma);
            }

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error al crear objetos de logo o firma \nfile: "
                    + String.valueOf(logoObject) + "\n" + String.valueOf(firmaObject) + "\n" + ex.toString());
        }

        try {
            file = cdiscisa.Cdiscisa.class.getClassLoader()
                    .getResourceAsStream("files/n_diploma_simple_vacio_nf_nl_nr.pdf");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null,
                    "Error al cargar el el diploma single base. \ndiploma: files/n_diploma_simple_vacio_nf_nl_nr.pdf \nfile: "
                            + String.valueOf(file) + "\n" + ex.toString());
        }

        documentSingle = PDDocument.load(file);

        PDPage pageSingle = (PDPage) documentSingle.getDocumentCatalog().getPages().get(0);
        COSDictionary pageDictSingle = pageSingle.getCOSObject();
        COSDictionary newPageSingleDict = new COSDictionary(pageDictSingle);
        PDPage templatePageSingle = new PDPage(newPageSingleDict);

        // Create a document and add a page to it

        PDDocument documentDoble;

        InputStream file2 = null;

        try {
            file2 = cdiscisa.Cdiscisa.class.getClassLoader()
                    .getResourceAsStream("files/n_diploma_doble_vacio_nf_nl_nr.pdf");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null,
                    "Error al cargar el el diploma doble base. \ndiploma: n_diploma_doble_vacio_nf_nl_nr.pdf\nfile: "
                            + String.valueOf(file2) + "\n" + ex.toString());
        }

        documentDoble = PDDocument.load(file2);

        PDPage pageDoble = (PDPage) documentDoble.getDocumentCatalog().getPages().get(0);
        COSDictionary pageDobleDict = pageDoble.getCOSObject();
        COSDictionary newPageDobleDict = new COSDictionary(pageDobleDict);

        PDPage templatePageDoble = new PDPage(newPageDobleDict);

        InputStream isFont1 = null, isFont2 = null, isFont3 = null;

        try {
            isFont1 = cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/Calibri.ttf");
            isFont2 = cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/CalibriBold.ttf");
            isFont3 = cdiscisa.Cdiscisa.class.getClassLoader().getResourceAsStream("files/Pristina.ttf");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null,
                    "Error al cargar el una fuente \nisFont1: " + String.valueOf(isFont1) + "\nisFont2: "
                            + String.valueOf(isFont2) + "\nisFont3: " + String.valueOf(isFont3) + "\n"
                            + ex.toString());
        }
        PDFont calibri = null;
        PDFont calibriBold = null;
        PDFont pristina = null;

        calibri = PDType0Font.load(document, isFont1);
        calibriBold = PDType0Font.load(document, isFont2);
        pristina = PDType0Font.load(document, isFont3);

        if (listaParticipantes.size() % 2 == 0 && listaParticipantes.size() >= 2) {

            while (it.hasNext()) {
                p1 = it.next();
                p2 = it.next();

                imprimirDiplomaDoble(p1, p2, c, d, document, templatePageDoble, calibri, calibriBold, pristina,
                        logoObject, firmaObject, instructor);
            }
        } else {
            if (listaParticipantes.size() > 1) {
                //Lista es impar y contiene mas de 2 participantes.
                while (it.hasNext()) {

                    if (it.nextIndex() == listaParticipantes.size() - 1) {
                        p1 = it.next();
                        imprimirDiplomaArriba(p1, c, d, document, templatePageSingle, calibri, calibriBold,
                                pristina, logoObject, firmaObject, instructor);
                        break;
                    }

                    p1 = it.next();
                    p2 = it.next();

                    imprimirDiplomaDoble(p1, p2, c, d, document, templatePageDoble, calibri, calibriBold, pristina,
                            logoObject, firmaObject, instructor);
                }
            } else if (listaParticipantes.size() == 1) {
                p1 = it.next();
                imprimirDiplomaArriba(p1, c, d, document, templatePageSingle, calibri, calibriBold, pristina,
                        logoObject, firmaObject, instructor);
            }

        }

        Format formatter = new SimpleDateFormat("ddMMMYYYY", new Locale("es", "MX"));
        String formatedDate = formatter.format(c.fecha_inicio);

        String abrev = abreviaturas.get(c.nombre_curso);

        if (c.walmart) {
            document.save(savePath + File.separator + "Diplomas_" + d.formato + "_" + d.unidad + "_"
                    + d.determinante + "_" + abrev + "_" + formatedDate + ".pdf");
            document.close();
            dosc.put(savePath + File.separator + "Diplomas_" + d.formato + "_" + d.unidad + "_" + d.determinante
                    + "_" + abrev + "_" + formatedDate + ".pdf", d.determinante);
        } else {
            document.save(savePath + File.separator + "Diplomas_" + d.determinante + "_" + abrev + "_"
                    + formatedDate + ".pdf");
            document.close();
            dosc.put(savePath + File.separator + "Diplomas_" + d.determinante + "_" + abrev + "_" + formatedDate
                    + ".pdf", d.determinante);
        }
    }

From source file:cdiscisa.StreamUtil.java

private static void imprimirDiplomaArriba(Participante p1, Curso c, Directorio d, PDDocument document,
            PDPage page, PDFont calibri, PDFont calibriBold, PDFont pristina, PDImageXObject logoObject,
            PDImageXObject firmaObject, String instructor) throws IOException {

        COSDictionary pageDict = page.getCOSObject();
        COSDictionary newPageDict = new COSDictionary(pageDict);

        PDPage newPage = new PDPage(newPageDict);
        document.addPage(newPage);/*  w  w  w . j  a  va 2  s.  co  m*/

        // Start a new content stream which will "hold" the to be created content
        PDPageContentStream contentStream = new PDPageContentStream(document, newPage, true, true);

        float pageWidth = newPage.getMediaBox().getWidth();
        //float pageHeight = newPage.getMediaBox().getHeight();

        //System.out.println("pageWidth: " + pageWidth + "\npageHeight: " + pageHeight);

        // Print Name
        contentStream.beginText();
        contentStream.setFont(pristina, 28);
        //contentStream.setNonStrokingColor(0,112,192);
        contentStream.setNonStrokingColor(0, 128, 0);

        float nameWidth = pristina.getStringWidth(p1.nombre + " " + p1.apellidos) / 1000 * 28;

        //System.out.println(p1.nombre + " " + p1.apellidos + "::" + nameWidth);

        float xPosition;
        if (nameWidth < 470) {
            xPosition = (pageWidth - nameWidth) / 2;
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 641));
            contentStream.showText(p1.nombre + " " + p1.apellidos);
        } else {
            contentStream.setFont(pristina, 22);
            nameWidth = pristina.getStringWidth(p1.nombre + " " + p1.apellidos) / 1000 * 22;
            xPosition = (pageWidth - nameWidth) / 2;
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 641));
            contentStream.showText(p1.nombre + " " + p1.apellidos);
        }

        contentStream.setFont(calibri, 15);
        contentStream.setNonStrokingColor(Color.BLACK);

        nameWidth = calibri.getStringWidth(c.razon_social) / 1000 * 15;
        //System.out.println("nameWidth: " + nameWidth);
        xPosition = (pageWidth - nameWidth) / 2;

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 615));
        contentStream.showText(c.razon_social);

        contentStream.setFont(calibri, 11);
        contentStream.setNonStrokingColor(Color.BLACK);

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 255, 593));
        if (c.walmart) {
            contentStream.showText(p1.determinante + " " + d.unidad);
        } else if (d.sucursal.isEmpty() || d.sucursal.equalsIgnoreCase("")) {
            contentStream.endText();
            contentStream.addRect(100, 590, 400, 20);
            contentStream.setNonStrokingColor(Color.WHITE);
            contentStream.fill();
            contentStream.beginText();
            contentStream.setNonStrokingColor(Color.BLACK);
        } else {
            contentStream.showText(d.sucursal);
        }

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 210, (float) 538.5));
        contentStream.showText(c.horas_texto);

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 394, (float) 538.5));
        contentStream.showText(c.fecha_texto_diploma);

        contentStream.setFont(calibriBold, 10);

        float nameWidthStroked = calibri.getStringWidth(c.nombre_curso) / 1000 * 10;
        //System.out.println("nameWidth: " + nameWidthStroked);
        float strokePosition = (pageWidth - nameWidthStroked) / 2;
        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, strokePosition, 554));
        contentStream.showText(c.nombre_curso);

        contentStream.setFont(calibri, 8);
        contentStream.setNonStrokingColor(Color.GRAY);

        if (instructor.equalsIgnoreCase("Manuel Anguiano Razn")) {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 457));
            contentStream.showText("Registro STPS: GIS100219KK8003");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 447));
            contentStream.showText("Registro PC: " + c.registro_manuel);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 437));
            contentStream.showText("Registro PC: " + c.registro_jorge);

        } else if (instructor.equalsIgnoreCase("Ing. Jorge Antonio Razn Gutierrez")) {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 457));
            contentStream.showText("Registro STPS: GIS100219KK8003");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 447));
            contentStream.showText("Registro PC: " + c.registro_coco);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 437));
            contentStream.showText("Registro PC: " + c.registro_jorge);
        } else {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 150, 457));
            contentStream.showText("Registro STPS: GIS100219KK8003");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 150, 447));
            contentStream.showText("Registro STPS: RAGJ610813BIA005");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 150, 437));
            contentStream.showText("Registro PC: " + c.registro_jorge);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 270, 447));
            contentStream.showText("Registro PC: SPC-COAH-056-2015");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 270, 437));
            contentStream.showText("Registro PC: CGPC-28/6016/026/NL-PS14");
        }
        // "Registro PC: DPC-ENL-CE-002/2015"
        // DPC-ENL-I-103_2015 "Ing. Jorge Antonio Razn Gutierrez"
        // DPC-ENL-I-056_2015 "Manuel Anguiano Razn"
        // "TSI. Jorge Antonio Razn Gil"

        contentStream.endText();

        contentStream.setStrokingColor(Color.BLACK);
        contentStream.setLineWidth(1);
        contentStream.moveTo(strokePosition, 552);
        contentStream.lineTo(strokePosition + nameWidthStroked + 6, 552);
        contentStream.stroke();

        if (logoObject != null && !logoObject.isEmpty()) {
            contentStream.drawImage(logoObject, 451, 700, 130, 65);
        }
        if (firmaObject != null && !firmaObject.isEmpty()) {
            contentStream.drawImage(firmaObject, 452, 440, 110, 42);

            contentStream.beginText();
            contentStream.setFont(calibri, 10);
            contentStream.setNonStrokingColor(Color.BLACK);
            nameWidth = calibri.getStringWidth(instructor) / 1000 * 10;
            xPosition = 505 - nameWidth / 2;

            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 445));
            contentStream.showText(instructor);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 485, 435));
            contentStream.showText("Instructor");
            contentStream.endText();
        }
        /*
        System.out.println("logoWidth: " + logoObject.getWidth());
        System.out.println("logoHeight: " + logoObject.getHeight());
        System.out.println("firmaWidth: " + firmaObject.getWidth());
        System.out.println("firmaHeight: " + firmaObject.getHeight());
        */

        /*
        contentStream.addRect(50, 750, 500, 100);
        contentStream.setNonStrokingColor(Color.WHITE);
        contentStream.fill();
        contentStream.drawImage(logo, 430,700,150,75);
        contentStream.drawImage(firma, 93,239,72,29);
        */

        // Make sure that the content stream is closed:
        contentStream.close();

        // Save the results and ensure that the document is properly closed:

    }

From source file:cdiscisa.StreamUtil.java

private static void imprimirDiplomaDoble(Participante p1, Participante p2, Curso c, Directorio d,
            PDDocument document, PDPage page, PDFont calibri, PDFont calibriBold, PDFont pristina,
            PDImageXObject logoObject, PDImageXObject firmaObject, String instructor) throws IOException {

        COSDictionary pageDict = page.getCOSObject();
        COSDictionary newPageDict = new COSDictionary(pageDict);

        PDPage newPage = new PDPage(newPageDict);
        document.addPage(newPage);//w  ww .j  av  a  2s.c o  m

        // Start a new content stream which will "hold" the to be created content
        PDPageContentStream contentStream = new PDPageContentStream(document, newPage, true, true);

        float pageWidth = newPage.getMediaBox().getWidth();
        //float pageHeight = newPage.getMediaBox().getHeight();

        //System.out.println("pageWidth: " + pageWidth + "\npageHeight: " + pageHeight);

        // Print UP Side

        contentStream.beginText();
        contentStream.setFont(pristina, 28);
        //contentStream.setNonStrokingColor(0,112,192);
        contentStream.setNonStrokingColor(0, 128, 0);

        float nameWidth = pristina.getStringWidth(p1.nombre + " " + p1.apellidos) / 1000 * 28;

        //System.out.println(p1.nombre + " " + p1.apellidos + "::" + nameWidth);

        float xPosition;
        if (nameWidth < 470) {
            xPosition = (pageWidth - nameWidth) / 2;
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 641));
            contentStream.showText(p1.nombre + " " + p1.apellidos);
        } else {
            contentStream.setFont(pristina, 22);
            nameWidth = pristina.getStringWidth(p1.nombre + " " + p1.apellidos) / 1000 * 22;
            xPosition = (pageWidth - nameWidth) / 2;
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 641));
            contentStream.showText(p1.nombre + " " + p1.apellidos);
        }

        contentStream.setFont(calibri, 15);
        contentStream.setNonStrokingColor(Color.BLACK);

        nameWidth = calibri.getStringWidth(c.razon_social) / 1000 * 15;
        //System.out.println("nameWidth: " + nameWidth);
        xPosition = (pageWidth - nameWidth) / 2;

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 615));
        contentStream.showText(c.razon_social);

        contentStream.setFont(calibri, 11);
        contentStream.setNonStrokingColor(Color.BLACK);

        if (c.walmart) {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 275, 593));
            contentStream.showText(p1.determinante + " " + d.unidad);
        } else if (d.sucursal.isEmpty() || d.sucursal.equalsIgnoreCase("")) {
            contentStream.endText();
            contentStream.addRect(100, 590, 400, 20);
            contentStream.setNonStrokingColor(Color.WHITE);
            contentStream.fill();
            contentStream.beginText();
            contentStream.setNonStrokingColor(Color.BLACK);
        } else {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 275, 593));
            contentStream.showText(d.sucursal);
        }

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 210, (float) 538.5));
        contentStream.showText(c.horas_texto);

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 394, (float) 538.5));
        contentStream.showText(c.fecha_texto_diploma);

        contentStream.setFont(calibriBold, 10);

        float nameWidthStroked = calibri.getStringWidth(c.nombre_curso) / 1000 * 10;
        //System.out.println("nameWidth: " + nameWidthStroked);
        float strokePosition = (pageWidth - nameWidthStroked) / 2;
        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, strokePosition, 554));
        contentStream.showText(c.nombre_curso);

        contentStream.setFont(calibri, 8);
        contentStream.setNonStrokingColor(Color.GRAY);

        if (instructor.equalsIgnoreCase("Manuel Anguiano Razn")) {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 457));
            contentStream.showText("Registro STPS: GIS100219KK8003");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 447));
            contentStream.showText("Registro PC: " + c.registro_manuel);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 437));
            contentStream.showText("Registro PC: " + c.registro_jorge);

        } else if (instructor.equalsIgnoreCase("Ing. Jorge Antonio Razn Gutierrez")) {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 457));
            contentStream.showText("Registro STPS: GIS100219KK8003");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 447));
            contentStream.showText("Registro PC: " + c.registro_coco);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 437));
            contentStream.showText("Registro PC: " + c.registro_jorge);
        } else {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 150, 457));
            contentStream.showText("Registro STPS: GIS100219KK8003");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 150, 447));
            contentStream.showText("Registro STPS: RAGJ610813BIA005");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 150, 437));
            contentStream.showText("Registro PC: " + c.registro_jorge);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 270, 447));
            contentStream.showText("Registro PC: SPC-COAH-056-2015");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 270, 437));
            contentStream.showText("Registro PC: CGPC-28/6016/026/NL-PS14");
        }

        contentStream.endText();

        contentStream.setStrokingColor(Color.BLACK);
        contentStream.setLineWidth(1);
        contentStream.moveTo(strokePosition, 552);
        contentStream.lineTo(strokePosition + nameWidthStroked + 6, 552);
        contentStream.stroke();

        if (logoObject != null && !logoObject.isEmpty()) {
            contentStream.drawImage(logoObject, 451, 700, 130, 65);
        }
        if (firmaObject != null && !firmaObject.isEmpty()) {
            contentStream.setStrokingColor(Color.BLACK);
            contentStream.drawImage(firmaObject, 452, 440, 110, 42);
            contentStream.beginText();
            contentStream.setFont(calibri, 10);
            nameWidth = calibri.getStringWidth(instructor) / 1000 * 10;
            xPosition = 505 - nameWidth / 2;

            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 445));
            contentStream.showText(instructor);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 485, 435));
            contentStream.showText("Instructor");
            contentStream.endText();
        }

        // Print DOWN Side

        contentStream.beginText();
        contentStream.setFont(pristina, 28);
        //contentStream.setNonStrokingColor(0,112,192);
        contentStream.setNonStrokingColor(0, 128, 0);

        nameWidth = pristina.getStringWidth(p2.nombre + " " + p2.apellidos) / 1000 * 28;

        //System.out.println(p2.nombre + " " + p2.apellidos + "::" + nameWidth);

        if (nameWidth < 470) {
            xPosition = (pageWidth - nameWidth) / 2;
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 262));
            contentStream.showText(p2.nombre + " " + p2.apellidos);
        } else {
            contentStream.setFont(pristina, 22);
            nameWidth = pristina.getStringWidth(p2.nombre + " " + p2.apellidos) / 1000 * 22;
            xPosition = (pageWidth - nameWidth) / 2;
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 262));
            contentStream.showText(p2.nombre + " " + p2.apellidos);
        }

        contentStream.setFont(calibri, 15);
        contentStream.setNonStrokingColor(Color.BLACK);

        nameWidth = calibri.getStringWidth(c.razon_social) / 1000 * 15;
        //System.out.println("nameWidth: " + nameWidth);
        xPosition = (pageWidth - nameWidth) / 2;

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 235));
        contentStream.showText(c.razon_social);

        contentStream.setFont(calibri, 11);
        contentStream.setNonStrokingColor(Color.BLACK);

        if (c.walmart) {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 275, (float) 213.4));
            contentStream.showText(p2.determinante + " " + d.unidad);
        } else if (d.sucursal.isEmpty() || d.sucursal.equalsIgnoreCase("")) {
            contentStream.endText();
            contentStream.addRect(100, 211, 400, 20);
            contentStream.setNonStrokingColor(Color.WHITE);
            contentStream.fill();
            contentStream.beginText();
            contentStream.setNonStrokingColor(Color.BLACK);
        } else {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 275, (float) 213.4));
            contentStream.showText(d.sucursal);
        }

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 210, 159));
        contentStream.showText(c.horas_texto);

        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 394, 159));
        contentStream.showText(c.fecha_texto_diploma);

        contentStream.setFont(calibriBold, 10);

        nameWidthStroked = calibri.getStringWidth(c.nombre_curso) / 1000 * 10;
        //System.out.println("nameWidth: " + nameWidthStroked);
        strokePosition = (pageWidth - nameWidthStroked) / 2;
        contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, strokePosition, 174));
        contentStream.showText(c.nombre_curso);

        contentStream.setFont(calibri, 8);
        contentStream.setNonStrokingColor(Color.GRAY);

        if (instructor.equalsIgnoreCase("Manuel Anguiano Razn")) {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 74));
            contentStream.showText("Registro STPS: GIS100219KK8003");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 64));
            contentStream.showText("Registro PC: " + c.registro_manuel);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 54));
            contentStream.showText("Registro PC: " + c.registro_jorge);

        } else if (instructor.equalsIgnoreCase("Ing. Jorge Antonio Razn Gutierrez")) {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 74));
            contentStream.showText("Registro STPS: GIS100219KK8003");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 64));
            contentStream.showText("Registro PC: " + c.registro_coco);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 170, 54));
            contentStream.showText("Registro PC: " + c.registro_jorge);
        } else {
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 150, 74));
            contentStream.showText("Registro STPS: GIS100219KK8003");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 150, 64));
            contentStream.showText("Registro STPS: RAGJ610813BIA005");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 150, 54));
            contentStream.showText("Registro PC: " + c.registro_jorge);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 270, 64));
            contentStream.showText("Registro PC: SPC-COAH-056-2015");
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 270, 54));
            contentStream.showText("Registro PC: CGPC-28/6016/026/NL-PS14");
        }

        contentStream.endText();

        contentStream.setStrokingColor(Color.BLACK);
        contentStream.moveTo(strokePosition, 172);
        contentStream.lineTo(strokePosition + nameWidthStroked + 6, 172);
        contentStream.stroke();

        if (logoObject != null && !logoObject.isEmpty()) {
            contentStream.drawImage(logoObject, 451, 320, 130, 65);
        }
        if (firmaObject != null && !firmaObject.isEmpty()) {
            contentStream.drawImage(firmaObject, 452, 62, 110, 42);

            contentStream.beginText();
            contentStream.setFont(calibri, 10);
            contentStream.setStrokingColor(Color.BLACK);
            nameWidth = calibri.getStringWidth(instructor) / 1000 * 10;

            xPosition = 505 - nameWidth / 2;

            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, xPosition, 67));

            contentStream.showText(instructor);
            contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, 485, 57));
            contentStream.showText("Instructor");
            contentStream.endText();
        }
        // Make sure that the content stream is closed:
        contentStream.close();

        // Save the results and ensure that the document is properly closed:
        //document.save( "DiplomaSoloTest.pdf");
        //document.close();
    }

From source file:com.esri.geoportal.commons.pdf.PdfUtils.java

License:Apache License

/**
 * Reads metadata values from a PDF file.
 * /* w  ww  .  j a v  a 2  s. c o  m*/
 * @param rawBytes the PDF to read
 * @param defaultTitle title to be used if the PDF metadata doesn't have one
 * @param geometryServiceUrl url of a <a href="https://developers.arcgis.com/rest/services-reference/geometry-service.htm">geometry service</a> for reprojecting coordinates. 
 * 
 * @return metadata properties or null if the PDF cannot be read.
 * 
 * @throws IOException on parsing error
 */
public static Properties readMetadata(byte[] rawBytes, String defaultTitle, String geometryServiceUrl)
        throws IOException {
    Properties ret = new Properties();

    // Attempt to read in the PDF file
    try (PDDocument document = PDDocument.load(rawBytes)) {

        // See if we can read the PDF
        if (!document.isEncrypted()) {
            // Get document metadata
            PDDocumentInformation info = document.getDocumentInformation();

            if (info != null) {

                if (info.getTitle() != null) {
                    ret.put(PROP_TITLE, info.getTitle());
                } else {
                    ret.put(PROP_TITLE, defaultTitle);
                }

                if (info.getSubject() != null) {
                    ret.put(PROP_SUBJECT, info.getSubject());
                } else {

                    StringBuilder psudoSubject = new StringBuilder("");
                    psudoSubject.append("\nAuthor: " + info.getAuthor());
                    psudoSubject.append("\nCreator: " + info.getCreator());
                    psudoSubject.append("\nProducer: " + info.getProducer());

                    ret.put(PROP_SUBJECT, psudoSubject.toString());
                }

                if (info.getModificationDate() != null) {
                    ret.put(PROP_MODIFICATION_DATE, info.getModificationDate().getTime());
                } else {
                    ret.put(PROP_MODIFICATION_DATE, info.getCreationDate().getTime());
                }
            } else {
                LOG.warn("Got null metadata for PDF file");
                return null;
            }

            // Attempt to read in geospatial PDF data
            COSObject measure = document.getDocument().getObjectByType(COSName.getPDFName("Measure"));
            String bBox = null;
            if (measure != null) {
                // This is a Geospatial PDF (i.e. Adobe's standard)
                COSDictionary dictionary = (COSDictionary) measure.getObject();

                float[] coords = ((COSArray) dictionary.getItem("GPTS")).toFloatArray();

                bBox = generateBbox(coords);
            } else {
                PDPage page = document.getPage(0);
                if (page.getCOSObject().containsKey(COSName.getPDFName("LGIDict"))) {
                    // This is a GeoPDF (i.e. TerraGo's standard)
                    bBox = extractGeoPDFProps(page, geometryServiceUrl);
                }
            }

            if (bBox != null) {
                ret.put(PROP_BBOX, bBox);
            }

        } else {
            LOG.warn("Cannot read encrypted PDF file");
            return null;
        }

    } catch (IOException ex) {
        LOG.error("Exception reading PDF", ex);
        throw ex;
    }

    return ret;
}

From source file:com.esri.geoportal.commons.pdf.PdfUtils.java

License:Apache License

/**
 * Extracts the geospatial metadata from a GeoPDF
 * //from w ww.  j a va  2  s  . c o  m
 * @param page the PDF page to read geospatial metadata from
 * @param geometryServiceUrl url of a <a href="https://developers.arcgis.com/rest/services-reference/geometry-service.htm">geometry service</a> for reprojecting coordinates. 
 * 
 * @see <a href="https://www.loc.gov/preservation/digital/formats/fdd/fdd000312.shtml">Library of Congress information on GeoPDF</a>
 * @see <a href="https://www.adobe.com/content/dam/acom/en/devnet/pdf/pdfs/PDF32000_2008.pdf">The PDF specification</a>, section 8, for instructions for translating coordinates.
 * 
 * @returns the bounding box of the GeoPDF as "yMin xMin, yMax xMax"
 */
private static String extractGeoPDFProps(PDPage page, String geometryServiceUrl) {

    // The LGI dictionary is an array, we'll loop through all entries and pull the first one for a bounding box
    COSArray lgi = (COSArray) page.getCOSObject().getDictionaryObject("LGIDict");

    List<String> bBoxes = new ArrayList<>();

    lgi.iterator().forEachRemaining(item -> {

        String currentBbox = null;

        // Set up the Coordinate Transformation Matrix (used to translate PDF coords to geo coords)
        Double[][] ctmValues = null;

        COSDictionary dictionary = (COSDictionary) item;
        if (dictionary.containsKey("CTM")) {
            ctmValues = new Double[3][3];

            // The last column in the matrix is always constant
            ctmValues[0][2] = 0.0;
            ctmValues[1][2] = 0.0;
            ctmValues[2][2] = 1.0;

            COSArray ctm = (COSArray) dictionary.getDictionaryObject("CTM");
            for (int i = 0; i < ctm.toList().size(); i += 2) {
                int ctmRow = i / 2;
                ctmValues[ctmRow][0] = Double.parseDouble(((COSString) ctm.get(i)).getString());
                ctmValues[ctmRow][1] = Double.parseDouble(((COSString) ctm.get(i + 1)).getString());
            }
        }

        // Get the neatline (i.e. the bounding box in *PDF* coordinates)
        Double[][] neatLineValues = null;
        int neatLineLength = 0;
        if (dictionary.containsKey("Neatline")) {

            COSArray neatline = (COSArray) dictionary.getDictionaryObject("Neatline");
            neatLineLength = neatline.toList().size();
            neatLineValues = new Double[neatLineLength / 2][3];

            for (int i = 0; i < neatline.toList().size(); i += 2) {
                int neatLineRow = i / 2;
                neatLineValues[neatLineRow][0] = Double.parseDouble(((COSString) neatline.get(i)).getString());
                neatLineValues[neatLineRow][1] = Double
                        .parseDouble(((COSString) neatline.get(i + 1)).getString());
                neatLineValues[neatLineRow][2] = 1.0;
            }
        }

        // Translate the PDF coordinates to Geospatial coordintates by multiplying the two matricies
        MultiPoint mp = new MultiPoint();
        if (ctmValues != null && neatLineValues != null) {
            Double[][] resultCoords = new Double[neatLineLength / 2][3];
            for (int z = 0; z < neatLineLength / 2; z++) {
                for (int i = 0; i < 3; i++) {
                    resultCoords[z][i] = neatLineValues[z][0] * ctmValues[0][i]
                            + neatLineValues[z][1] * ctmValues[1][i] + neatLineValues[z][2] * ctmValues[2][i];
                }
                mp.add(resultCoords[z][0], resultCoords[z][1]);
            }
        }

        // Project the geospatial coordinates to WGS84 for the Dublin-Core metadata
        if (dictionary.containsKey("Projection")) {
            COSDictionary projectionDictionary = (COSDictionary) dictionary.getDictionaryObject("Projection");
            String projectionType = projectionDictionary.getString("ProjectionType");

            try (GeometryService svc = new GeometryService(HttpClients.custom().useSystemProperties().build(),
                    new URL(geometryServiceUrl));) {

                // UTM projections require slightly different processing
                if ("UT".equals(projectionType)) {
                    String zone = Integer.toString(projectionDictionary.getInt("Zone"));
                    String hemisphere = projectionDictionary.getString("Hemisphere");

                    // Get the wkt for the geospatial coordinate system
                    String wkt = datumTranslation(projectionDictionary.getItem("Datum"));

                    if (zone != null && hemisphere != null && wkt != null) {
                        // Generate a list of UTM strings
                        List<String> utmCoords = new ArrayList<>();
                        for (Point2D pt : mp.getCoordinates2D()) {
                            String coord = String.format("%s%s %s %s", zone, hemisphere, Math.round(pt.x),
                                    Math.round(pt.y));
                            utmCoords.add(coord);
                        }

                        MultiPoint reproj = svc.fromGeoCoordinateString(utmCoords, WGS84_WKID);

                        currentBbox = generateBbox(reproj);

                    } else {
                        LOG.warn("Missing UTM argument: zone: {}, hemisphere: {}, datum: {}", zone, hemisphere,
                                wkt);
                        LOG.debug("Projection dictionary {}", projectionDictionary);
                    }
                } else {
                    // Generate Well Known Text for projection and re-projects the points to WGS 84
                    String wkt = getProjectionWKT(projectionDictionary, projectionType);

                    if (wkt != null) {
                        MultiPoint reproj = svc.project(mp, wkt, WGS84_WKID);

                        currentBbox = generateBbox(reproj);

                    } else if (LOG.isDebugEnabled()) {
                        // Print out translated coordinates for debugging purposes
                        LOG.debug("Translated Coordinates");
                        for (Point2D pt : mp.getCoordinates2D()) {
                            LOG.debug(String.format("\t%s, %s", pt.x, pt.y));
                        }
                    }
                }
            } catch (Exception e) {
                // If something goes wrong, just try the next set of coordinates
                LOG.error("Exception reprojecting geometry, skipping this geopdf dictionary instance...", e);
            }
        }

        if (currentBbox != null) {
            bBoxes.add(currentBbox);
        }

    });

    return bBoxes.get(0);
}

From source file:ddf.catalog.transformer.input.pdf.GeoPdfDocumentGenerator.java

License:Open Source License

private static PDPage generateGeoPdfPage(int numberOfFramesPerPage, String projectionType) {
    PDPage pdPage = new PDPage();
    COSDictionary cosDictionary = pdPage.getCOSObject();
    cosDictionary.setItem(GeoPdfParserImpl.LGIDICT,
            generateLGIDictArray(numberOfFramesPerPage, projectionType));
    return pdPage;
}

From source file:ddf.catalog.transformer.input.pdf.GeoPdfDocumentGenerator.java

License:Open Source License

private static PDPage generateGeoPdfPage(String projectionType, boolean generateNeatLine) {
    PDPage pdPage = new PDPage();
    COSDictionary cosDictionary = pdPage.getCOSObject();
    cosDictionary.setItem(GeoPdfParserImpl.LGIDICT,
            generateMapFrameDictionary(projectionType, generateNeatLine));
    return pdPage;
}