Example usage for org.apache.pdfbox.pdmodel.graphics.color PDOutputIntent setInfo

List of usage examples for org.apache.pdfbox.pdmodel.graphics.color PDOutputIntent setInfo

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel.graphics.color PDOutputIntent setInfo.

Prototype

public void setInfo(String value) 

Source Link

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;/*from   w ww .  ja  v  a 2  s.  co 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://from   w  w  w . ja v  a  2  s. c  o  m
        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:com.github.gujou.deerbelling.sonarqube.service.PdfApplicationGenerator.java

License:Open Source License

public static File generateFile(Project sonarProject, FileSystem sonarFileSystem, String sonarUrl,
        String sonarLogin, String sonarPassword, Map<String, Measure> sonarMeasures) {

    Resources sonarResources = ResourceGateway.getOpenIssues(sonarProject.getKey(), sonarUrl, sonarLogin,
            sonarPassword);/* w  w  w .j av a2 s .  c o  m*/

    // Only one resource => call with sonarProject.getKey()
    Resource projectResource = sonarResources.getResource().get(0);

    for (Measure measure : projectResource.getMsr()) {

        System.out.println(measure.getKey() + " " + measure.getVal());

        sonarMeasures.put(measure.getKey(), measure);
    }

    String projectName = sonarProject.getName().replaceAll("[^A-Za-z0-9 ]", " ").trim().replaceAll(" +", " ");

    String filePath = sonarFileSystem.workDir().getAbsolutePath() + File.separator + "application_report_"
            + sonarProject.getEffectiveKey().replace(':', '-') + "."
            + ReportsKeys.APPLICATION_REPORT_TYPE_PDF_EXTENSION;

    File file = new File(filePath);

    String fontfile = "font/OpenSans-Regular.ttf";

    PDDocument doc = new PDDocument();
    try {

        initNewPage(doc);

        PDSimpleFont font = PDType1Font.TIMES_BOLD;
        PDSimpleFont fontItalic = PDType1Font.TIMES_BOLD_ITALIC;

        PDImageXObject smileLogo = createFromFile("/images/Logo_Smile.png", doc);

        leftImage(smileLogo, page, doc, 80, 166);

        positionHeight = (int) (page.getMediaBox().getHeight() / 2) - 65;

        centerText("Indicateurs du projet", font, 45, page, doc);

        int heightProjectName = maximizeText(projectName, font, page, doc);

        positionHeight = (int) (page.getMediaBox().getHeight()) - 280 + heightProjectName;

        positionLogoWidth = (int) (page.getMediaBox().getWidth() / 2) - 100;
        positionTitleWidth = (int) (page.getMediaBox().getWidth() / 2) - 100;

        PDImageXObject icon_lines = createFromFile("/images/Lines-50.png", doc);

        PDImageXObject icon_author = createFromFile("/images/Typewriter_With_Paper-50.png", doc);

        PDImageXObject icon_version = createFromFile("/images/Versions-50.png", doc);

        PDImageXObject icon_date = createFromFile("/images/Date_To-50.png", doc);

        PDImageXObject icon_ncloc = createFromFile("/images/CodeLines-52.png", doc);

        PDImageXObject icon_folders = createFromFile("/images/Folder-50.png", doc);

        PDImageXObject icon_packages = createFromFile("/images/Box-52.png", doc);

        PDImageXObject icon_classes = createFromFile("/images/CodeFile-50.png", doc);

        PDImageXObject icon_files = createFromFile("/images/File-50.png", doc);

        PDImageXObject icon_methods = createFromFile("/images/Settings_3-50.png", doc);

        PDImageXObject icon_accessors = createFromFile("/images/Accessors-50.png", doc);

        PDImageXObject icon_api = createFromFile("/images/API_Settings-50.png", doc);

        PDImageXObject icon_keyring = createFromFile("/images/Keys.png", doc);

        PDImageXObject icon_bug = createFromFile("/images/Bug-50.png", doc);

        PDImageXObject icon_balance = createFromFile("/images/Scales-50.png", doc);

        PDImageXObject icon_wightBugs = createFromFile("/images/Weight-Bug-50.png", doc);

        PDImageXObject icon_poison = createFromFile("/images/Poison-50.png", doc);

        PDImageXObject icon_fire = createFromFile("/images/Campfire-50.png", doc);

        PDImageXObject icon_major = createFromFile("/images/Error-50.png", doc);

        PDImageXObject icon_minor = createFromFile("/images/Attention-51.png", doc);

        PDImageXObject icon_info = createFromFile("/images/Info-50.png", doc);

        PDImageXObject icon_ok = createFromFile("/images/Ok-50.png", doc);

        PDImageXObject icon_open = createFromFile("/images/Open_Sign-50.png", doc);

        PDImageXObject icon_confirmed = createFromFile("/images/Law-50.png", doc);

        PDImageXObject icon_debt = createFromFile("/images/Banknotes-52.png", doc);

        PDImageXObject icon_codeGenerated = createFromFile("/images/CodeFactory-50.png", doc);

        PDImageXObject icon_linesGenerated = createFromFile("/images/LineFactory-50.png", doc);

        PDImageXObject icon_screen = createFromFile("/images/Screen_TV-52.png", doc);

        PDImageXObject icon_screenSimple = createFromFile("/images/Screen_Pion-52.png", doc);

        PDImageXObject icon_screenMedium = createFromFile("/images/Screen_Cheval-52.png", doc);

        PDImageXObject icon_screenComplex = createFromFile("/images/Screen_Queen-52.png", doc);

        PDImageXObject icon_xmlTotal = createFromFile("/images/Conf_File-50.png", doc);

        PDImageXObject icon_xmlSimple = createFromFile("/images/Conf_File_simple-50.png", doc);

        PDImageXObject icon_xmlMedium = createFromFile("/images/Conf_File_medium-50.png", doc);

        PDImageXObject icon_xmlComplex = createFromFile("/images/Conf_File_complex-50.png", doc);

        PDImageXObject icon_mulesoftOut = createFromFile("/images/icon-mulesoftm-out.png", doc);
        PDImageXObject icon_mulesoftIn = createFromFile("/images/icon-mulesoftm-in.png", doc);

        PDImageXObject icon_mulesoftFlow = createFromFile("/images/icon-mulesoftm-flow.png", doc);

        PDImageXObject icon_complexity = createFromFile("/images/Frankensteins_Monster-48.png", doc);

        PDImageXObject icon_complexityClass = createFromFile("/images/ComplexCodeFile-50.png", doc);

        PDImageXObject icon_complexityMethod = createFromFile("/images/WolfSettings-50.png", doc);

        PDImageXObject icon_complexityFile = createFromFile("/images/FreddyFile-50.png", doc);

        PDImageXObject icon_comments = createFromFile("/images/Quote-50.png", doc);

        PDImageXObject icon_javadoc = createFromFile("/images/Comments-API.png", doc);

        PDImageXObject icon_tests_fail = createFromFile("/images/Dizzy_Person_Filled-50.png", doc);

        PDImageXObject icon_tests_skip = createFromFile("/images/Fast_Forward-50.png", doc);

        PDImageXObject icon_tests_error = createFromFile("/images/Explosion-50.png", doc);

        PDImageXObject icon_tests = createFromFile("/images/Search-52.png", doc);

        PDImageXObject icon_tests_success = createFromFile("/images/Goal-50.png", doc);

        PDImageXObject icon_conditions_cover = createFromFile("/images/Waning_Gibbous-52.png", doc);

        PDImageXObject icon_tests_cover = createFromFile("/images/Checklist-50.png", doc);

        PDImageXObject icon_vulnerability_high = createFromFile("/images/Shark-52.png", doc);

        PDImageXObject icon_vulnerability_medium = createFromFile("/images/Bee-50.png", doc);

        PDImageXObject icon_vulnerability_low = createFromFile("/images/Black_Cat-50.png", doc);

        PDImageXObject icon_declared = createFromFile("/images/Sugar_Cubes-64.png", doc);

        PDImageXObject icon_unused = createFromFile("/images/Litter_Disposal-50.png", doc);

        PDImageXObject icon_undeclared = createFromFile("/images/Move_by_Trolley-50.png", doc);

        PDImageXObject icon_filecycle = createFromFile("/images/FileCycle.png", doc);

        PDImageXObject icon_packagecycle = createFromFile("/images/PackageCycle.png", doc);

        PDImageXObject icon_cut_files = createFromFile("/images/Cut-50.png", doc);

        PDImageXObject icon_chain = createFromFile("/images/Link-52.png", doc);

        PDImageXObject icon_cut_directories = createFromFile("/images/Chainsaw-52.png", doc);

        PDImageXObject icon_duplicate = createFromFile("/images/Feed_Paper-50.png", doc);

        PDImageXObject icon_duplicate_lines = createFromFile("/images/Line-Spacing-icon.png", doc);

        PDImageXObject icon_duplicate_packages = createFromFile("/images/DuplicateBlocks2.png", doc);

        PDImageXObject icon_dev_count = createFromFile("/images/Workers_Male-50.png", doc);
        PDImageXObject icon_dev_best = createFromFile("/images/Weightlifting_Filled-50.png", doc);
        PDImageXObject icon_dev_issues = createFromFile("/images/Full_of_Shit-50.png", doc);

        attribute(icon_author, 22, 22, " Guillaume Jourdan", fontItalic, 15, doc, DEFAULT_TEXT_COLOR);
        attribute(icon_version, 22, 22, " Version 1.0", fontItalic, 15, doc, DEFAULT_TEXT_COLOR); // TODO
        // switch
        // field
        // &
        // value
        // :
        // resource
        // =>
        // version

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.FRENCH);
        attribute(icon_date, 22, 22, simpleDateFormat.format(new Date()), fontItalic, 15, doc,
                DEFAULT_TEXT_COLOR); // TODO
        // switch
        // field
        // &
        // value
        // :
        // resource
        // =>
        // date

        initNewPage(doc);

        title("Project Sizing", font, 26, doc);

        attribute(icon_ncloc, 22, 22, sonarMeasures.get("ncloc"), true, " lines of code", font, 15, doc); // ncloc
        attribute(icon_lines, 22, 22, sonarMeasures.get("lines"), true, " lines", font, 15, doc); // lines
        // =>
        // TODO
        attribute(icon_classes, 22, 22, sonarMeasures.get("classes"), true, " classes", font, 15, doc); // classes
        attribute(icon_files, 22, 22, sonarMeasures.get("files"), true, " files", font, 15, doc); // files
        // =>
        // TODO
        attribute(icon_folders, 22, 22, sonarMeasures.get("directories"), true, " directories", font, 15, doc); // directories
        attribute(icon_packages, 22, 22, sonarMeasures.get("projects"), true, " modules", font, 15, doc); // projects
        attribute(icon_methods, 22, 22, sonarMeasures.get("functions"), true, " methods", font, 15, doc); // functions
        attribute(icon_accessors, 22, 22, sonarMeasures.get("accessors"), true, " getters and setters", font,
                15, doc); // accessors
        attribute(icon_api, 22, 22, sonarMeasures.get("public_api"), true, "  public API", font, 15, doc); // public_api
        attribute(icon_keyring, 22, 22, sonarMeasures.get("statements"), true, " statements", font, 15, doc); // statements
        attribute(icon_codeGenerated, 22, 22, sonarMeasures.get("generated_ncloc"), true,
                " generated code lines", font, 15, doc); // generated_ncloc
        attribute(icon_linesGenerated, 22, 22, sonarMeasures.get("generated_lines"), true, " generated lines",
                font, 15, doc); // generated_lines

        Measure totalPages = sonarMeasures.get("total_pages");
        Measure simplePages = sonarMeasures.get("simple_pages");
        Measure mediumPages = sonarMeasures.get("medium_pages");
        Measure complexPages = sonarMeasures.get("complex_pages");

        if (totalPages != null) {
            attribute(icon_screen, 22, 22, totalPages, true, totalPages.getLabel(), font, 15, doc);
        }
        if (simplePages != null) {
            attribute(icon_screenSimple, 22, 22, simplePages, true, simplePages.getLabel(), font, 15, doc);
        }
        if (mediumPages != null) {
            attribute(icon_screenMedium, 22, 22, mediumPages, true, mediumPages.getLabel(), font, 15, doc);
        }
        if (complexPages != null) {
            attribute(icon_screenComplex, 22, 22, complexPages, true, complexPages.getLabel(), font, 15, doc);
        }

        Measure xmlNbTotal = sonarMeasures.get("xmlNbTotal");
        Measure xmlSimpleNbTotal = sonarMeasures.get("xmlSimpleNbTotal");
        Measure xmlMediumNbTotal = sonarMeasures.get("xmlMediumNbTotal");
        Measure xmlComplexNbTotal = sonarMeasures.get("xmlComplexNbTotal");
        Measure muleOutputField = sonarMeasures.get("muleOutputField");
        Measure muleNbRequestField = sonarMeasures.get("muleNbRequestField");
        Measure muleNbFlow = sonarMeasures.get("muleNbFlow");
        Measure muleNbSubFlow = sonarMeasures.get("muleNbSubFlow");

        if (xmlNbTotal != null) {
            attribute(icon_xmlTotal, 22, 22, xmlNbTotal, true, xmlNbTotal.getLabel(), font, 15, doc);
        }
        if (xmlSimpleNbTotal != null) {
            attribute(icon_xmlSimple, 22, 22, xmlSimpleNbTotal, true, xmlSimpleNbTotal.getLabel(), font, 15,
                    doc);
        }
        if (xmlMediumNbTotal != null) {
            attribute(icon_xmlMedium, 22, 22, xmlMediumNbTotal, true, xmlMediumNbTotal.getLabel(), font, 15,
                    doc);
        }
        if (xmlComplexNbTotal != null) {
            attribute(icon_xmlComplex, 22, 22, xmlComplexNbTotal, true, xmlComplexNbTotal.getLabel(), font, 15,
                    doc);
        }
        if (muleOutputField != null) {
            attribute(icon_mulesoftOut, 22, 22, muleOutputField, true, muleOutputField.getLabel(), font, 15,
                    doc);
        }
        if (muleNbRequestField != null) {
            attribute(icon_mulesoftIn, 22, 22, muleNbRequestField, true, muleNbRequestField.getLabel(), font,
                    15, doc);
        }
        if (muleNbFlow != null) {
            attribute(icon_mulesoftFlow, 22, 22, muleNbFlow, true, muleNbFlow.getLabel(), font, 15, doc);
        }
        if (muleNbSubFlow != null) {
            attribute(icon_mulesoftFlow, 22, 22, muleNbSubFlow, true, muleNbSubFlow.getLabel(), font, 15, doc);
        }

        title("Design", font, 26, doc);
        attribute(icon_packagecycle, 22, 22, sonarMeasures.get("package_cycles"), true,
                " package cycles detected", font, 15, doc); // package_cycles
        attribute(icon_cut_files, 22, 22, sonarMeasures.get("package_tangles"), true,
                " file dep. to cut cycles ", font, 15, doc, sonarMeasures.get("package_tangle_index"), true); // package_tangles
        // +
        // TODO
        // package_tangle_index
        // X
        attribute(icon_cut_directories, 22, 22, sonarMeasures.get("package_feedback_edges"), true,
                " package dep. to cut cycles", font, 15, doc); // package_feedback_edges
        attribute(icon_chain, 22, 22, sonarMeasures.get("package_edges_weight"), true,
                " file dep. betw. packages", font, 15, doc); // package_edges_weight X

        title("Complexity", font, 26, doc);
        attribute(icon_complexity, 22, 22, sonarMeasures.get("complexity"), true, " complexity index", font, 15,
                doc); // complexity
        attribute(icon_complexityClass, 22, 22, sonarMeasures.get("class_complexity"), true,
                " complexity index by class", font, 15, doc); // class_complexity
        attribute(icon_complexityFile, 22, 22, sonarMeasures.get("file_complexity"), true,
                " complexity index by file", font, 15, doc); // file_complexity
        attribute(icon_complexityMethod, 22, 22, sonarMeasures.get("function_complexity"), true,
                " complexity index by method", font, 15, doc); // function_complexity

        title("Duplications", font, 26, doc);
        attribute(icon_duplicate_lines, 22, 22, sonarMeasures.get("duplicated_lines"), true,
                " duplicated lines", font, 15, doc, sonarMeasures.get("duplicated_lines_density"), true); // duplicated_lines
        // +
        // duplicated_lines_density
        attribute(icon_duplicate, 22, 22, sonarMeasures.get("duplicated_files"), true, " involved files", font,
                15, doc); // duplicated_files
        attribute(icon_duplicate_packages, 22, 22, sonarMeasures.get("duplicated_blocks"), true,
                " duplicated blocks", font, 15, doc); // duplicated_blocks

        title("Sonarqube Issues", font, 26, doc);

        attribute(icon_bug, 22, 22, sonarMeasures.get("violations"), true, " issues", font, 15, doc); // violations
        // +
        // new
        // method
        // for
        // new_violations
        attribute(icon_poison, 22, 22, sonarMeasures.get("blocker_violations"), true, " blocker issues", font,
                15, doc); // blocker_violations + new method for
                                                                                                                                 // new_blocker_violations
        attribute(icon_fire, 22, 22, sonarMeasures.get("critical_violations"), true, " critical issues", font,
                15, doc); // critical_violations + new method for
                                                                                                                                 // new_critical_violations
        attribute(icon_major, 22, 22, sonarMeasures.get("major_violations"), true, " major issues", font, 15,
                doc); // major_violations
        // +
        // new
        // method
        // for
        // new_major_violations
        attribute(icon_minor, 22, 22, sonarMeasures.get("minor_violations"), true, " minor issues", font, 15,
                doc); // minor_violations
        // +
        // new
        // method
        // for
        // new_minor_violations
        // attribute(icon_info, 22, 22, "533", " info issues", font, 15,
        // doc); // info_violations + new method for new_info_violations
        // attribute(icon_ok, 22, 22, "533", " false positive issues", font,
        // 15, doc); // false_positive_issues
        // attribute(icon_open, 22, 22, "533", " open issues", font, 15,
        // doc); // open_issues
        // attribute(icon_confirmed, 22, 22, "533", " confirmed issues",
        // font, 15, doc); // confirmed_issues
        // attribute(icon_open, 22, 22, "533", " reopened issues", font, 15,
        // doc); // reopened_issues
        // attribute(icon_wightBugs, 22, 22, "533", " weighted issues",
        // font, 15, doc); // weighted_violations
        // attribute(icon_balance, 22, 22, "533", " rules compliance index",
        // font, 15, doc); // violations_density

        Measure squaleIndexMeasure = sonarMeasures.get("sqale_index");
        if (squaleIndexMeasure != null) {
            attribute(icon_debt, 22, 22, squaleIndexMeasure.getFrmt_val(), " Sqale technical debt", font, 15,
                    doc, null, false, SMILE_ORANGE_COLOR); // sqale_index
        }

        title("Documentation", font, 26, doc);

        attribute(icon_comments, 22, 22, sonarMeasures.get("comment_lines"), true, " comment lines", font, 15,
                doc, sonarMeasures.get("comment_lines_density"), true); // comment_lines
        // +
        // comment_lines_density

        Measure publicApiUndocMeasure = sonarMeasures.get("public_undocumented_api");

        if (publicApiUndocMeasure != null) {
            String publicApiUndocDensity = "100";
            Measure publicApiDocDensityMeasure = sonarMeasures.get("public_documented_api_density");
            if (publicApiDocDensityMeasure != null) {
                publicApiUndocDensity = decimalFormat.format(
                        100.0 - Float.parseFloat(sonarMeasures.get("public_documented_api_density").getVal()));
            }

            attribute(icon_javadoc, 22, 22, publicApiUndocMeasure, true, " public undoc. API", font, 15, doc,
                    new Measure(publicApiUndocDensity), true); // public_undocumented_api
            // + (1
            // -
            // public_documented_api_density
            // %)
        }
        title("OWASP plugin", font, 26, doc);

        attribute(icon_vulnerability_high, 22, 22, sonarMeasures.get("high_severity_vulns"), true,
                " high dep. vulnerabilities", font, 15, doc);
        attribute(icon_vulnerability_medium, 22, 22, sonarMeasures.get("medium_severity_vulns"), true,
                " medium dep. vulnerabilities", font, 15, doc);
        attribute(icon_vulnerability_low, 22, 22, sonarMeasures.get("low_severity_vulns"), true,
                " low dep. vulnerabilities", font, 15, doc);

        title("Unit Test", font, 26, doc);

        Measure testsMeasure = sonarMeasures.get("tests");

        if (testsMeasure == null) {
            attribute(icon_tests, 22, 22, "0", " unit tests", font, 15, doc, null, false, SMILE_ORANGE_COLOR);
            attribute(icon_tests_cover, 22, 22, "0", " covered lines", font, 15, doc, "0", true,
                    SMILE_ORANGE_COLOR);
        } else {
            attribute(icon_tests, 22, 22, testsMeasure, true, " unit tests", font, 15, doc);
            try {
                int nbTests = (int) Double.parseDouble(testsMeasure.getVal());
                Measure failureTestsMeasure = sonarMeasures.get("test_failures");
                Measure errorTestsMeasure = sonarMeasures.get("test_errors");
                int failureTests = failureTestsMeasure != null
                        ? (int) Double.parseDouble(failureTestsMeasure.getVal())
                        : 0;
                int errorTests = errorTestsMeasure != null
                        ? (int) Double.parseDouble(errorTestsMeasure.getVal())
                        : 0;
                int successTests = nbTests - failureTests - errorTests;
                float errorPercent = (errorTests * 100f) / nbTests;
                float failurePercent = (failureTests * 100f) / nbTests;

                Measure successPercentMeasure = sonarMeasures.get("test_success_density");
                String successPercent = successPercentMeasure != null ? successPercentMeasure.getVal()
                        : decimalFormat.format((successTests * 100) / nbTests);

                attribute(icon_tests_success, 22, 22, Integer.valueOf(successTests).toString(),
                        " tests in success", font, 15, doc, successPercent, true, SMILE_ORANGE_COLOR);
                attribute(icon_tests_fail, 22, 22, Integer.valueOf(failureTests).toString(),
                        " tests in failure", font, 15, doc, decimalFormat.format(failurePercent), true,
                        SMILE_ORANGE_COLOR);
                attribute(icon_tests_error, 22, 22, Integer.valueOf(errorTests).toString(), " tests in error",
                        font, 15, doc, decimalFormat.format(errorPercent), true, SMILE_ORANGE_COLOR);

                Measure coveragePercentMeasure = sonarMeasures.get("line_coverage");
                Measure uncoverMeasure = sonarMeasures.get("uncovered_lines");
                Measure totalLineToCoverMeasure = sonarMeasures.get("lines_to_cover");
                int uncover = uncoverMeasure != null ? (int) Double.parseDouble(uncoverMeasure.getVal()) : 0;
                int totalLineToCover = totalLineToCoverMeasure != null
                        ? (int) Double.parseDouble(totalLineToCoverMeasure.getVal())
                        : 0;
                if (coveragePercentMeasure != null) {
                    attribute(icon_tests_cover, 22, 22, Integer.valueOf(totalLineToCover - uncover).toString(),
                            " covered lines", font, 15, doc, coveragePercentMeasure.getVal(), true,
                            SMILE_ORANGE_COLOR);
                } else {
                    attribute(icon_tests_cover, 22, 22, "0", " covered lines", font, 15, doc, "0", true,
                            SMILE_ORANGE_COLOR);
                }

            } catch (NumberFormatException nfe) {
                System.err.println(nfe);
                nfe.printStackTrace();
            }
        }

        // attribute(icon_tests, 22, 22, sonarMeasures.get("tests"), " unit
        // tests", font, 15, doc); //tests + TODO test_execution_time
        // attribute(icon_tests_success, 22, 22, "0", " tests in success",
        // font, 15, doc, sonarMeasures.get("test_success_density"), true);
        // // calcul success + test_success_density
        // attribute(icon_tests_fail, 22, 22, "0", " tests in failure",
        // font, 15, doc); // test_failures + calcul fail density
        // attribute(icon_tests_error, 22, 22, "0", " tests in error", font,
        // 15, doc); // test_errors + calcul error density
        // attribute(icon_tests_skip, 22, 22, "0", " tests skipped", font,
        // 15, doc); // skipped_tests
        // attribute(icon_tests_cover, 22, 22,
        // sonarMeasures.get("line_coverage"), " covered lines", font, 15,
        // doc, sonarMeasures.get("lines_to_cover"), true); // line_coverage
        // => lines_to_cover
        // attribute(icon_conditions_cover, 22, 22, "4450", " uncovered
        // conditions", font, 15, doc, "85", true); // uncovered_conditions
        // + (100 - branch_coverage)

        // add XMP metadata
        XMPMetadata xmp = XMPMetadata.createXMPMetadata();

        try {
            DublinCoreSchema dc = xmp.createAndAddDublinCoreSchema();
            dc.setTitle(filePath);

            PDFAIdentificationSchema id = xmp.createAndAddPFAIdentificationSchema();
            id.setPart(1);
            id.setConformance("B");

            XmpSerializer serializer = new XmpSerializer();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            serializer.serialize(xmp, baos, true);

            PDMetadata metadata = new PDMetadata(doc);
            metadata.importXMPMetadata(baos.toByteArray());
            doc.getDocumentCatalog().setMetadata(metadata);
        } catch (BadFieldValueException e) {

            e.printStackTrace();
            // // won't happen here, as the provided value is valid
            // throw new IllegalArgumentException(e);
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // sRGB output intent
        // InputStream colorProfile =
        // CreatePDFA.class.getResourceAsStream("/usr/share/color/icc/colord/BestRGB.icc");
        // // /usr/share/color/icc/colord/sRGB.icc

        FileInputStream iccFile = new FileInputStream(new File("/usr/share/color/icc/colord/BestRGB.icc"));
        // PDOutputIntent intent = new PDOutputIntent(doc, colorProfile);
        PDOutputIntent intent = new PDOutputIntent(doc, iccFile);
        intent.setInfo("sRGB IEC61966-2.1");
        intent.setOutputCondition("sRGB IEC61966-2.1");
        intent.setOutputConditionIdentifier("sRGB IEC61966-2.1");
        intent.setRegistryName("http://www.color.org");
        doc.getDocumentCatalog().addOutputIntent(intent);

        doc.save(file);
    } catch (IOException e1) {

        // TODO Auto-generated catch block
        e1.printStackTrace();
    } finally {

        IOUtils.closeQuietly(doc);
    }
    return file;
}

From source file:pdfbox.PDFA3File.java

License:Apache License

/**
 * Create a simple PDF/A-3 document./*from   w w w  . j a  va  2s  .  c  o  m*/
 * This example is based on HelloWorld example.
 * As it is a simple case, to conform the PDF/A norm, are added : - the font
 * used in the document - the sRGB color profile - a light xmp block with only
 * PDF identification schema (the only mandatory) - an output intent To
 * conform to A/3 - the mandatory MarkInfo dictionary displays tagged PDF
 * support - and optional producer and - optional creator info is added
 * 
 * @param file
 *          The file to write the PDF to.
 * @param message
 *          The message to write in the file.
 * @throws Exception
 *           If something bad occurs
 */
public void doIt(String file, String message) throws Exception {
    // the document
    PDDocument doc = null;
    try {
        doc = new PDDocument();

        // now create the page and add content
        PDPage page = new PDPage();

        doc.addPage(page);

        InputStream fontStream = PDFA3File.class.getResourceAsStream("/Ubuntu-R.ttf");
        PDFont font = PDTrueTypeFont.loadTTF(doc, fontStream);

        // create a page with the message where needed
        PDPageContentStream contentStream = new PDPageContentStream(doc, page);
        contentStream.beginText();
        contentStream.setFont(font, 12);
        contentStream.moveTextPositionByAmount(100, 700);
        contentStream.drawString(message);
        contentStream.endText();
        contentStream.saveGraphicsState();
        contentStream.close();

        PDDocumentCatalog cat = makeA3compliant(doc);

        InputStream colorProfile = PDFA3File.class.getResourceAsStream("/sRGB Color Space Profile.icm");

        // create output intent
        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");
        cat.addOutputIntent(oi);

        doc.save(file);

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

From source file:pdfbox.PDFA3FileAttachment.java

License:Apache License

/**
 * Create a simple PDF/A-3 document.//from  w  ww.  j  a v  a  2  s  .  co m
 * This example is based on HelloWorld example.
 * As it is a simple case, to conform the PDF/A norm, are added : - the font
 * used in the document - the sRGB color profile - a light xmp block with only
 * PDF identification schema (the only mandatory) - an output intent To
 * conform to A/3 - the mandatory MarkInfo dictionary displays tagged PDF
 * support - and optional producer and - optional creator info is added
 * 
 * @param file
 *          The file to write the PDF to.
 * @param message
 *          The message to write in the file.
 * @throws Exception
 *           If something bad occurs
 */
public void doIt(String file, String message) throws Exception {
    // the document
    PDDocument doc = null;
    try {
        doc = new PDDocument();

        // now create the page and add content
        PDPage page = new PDPage();

        doc.addPage(page);

        InputStream fontStream = PDFA3FileAttachment.class.getResourceAsStream("/Ubuntu-R.ttf");
        PDFont font = PDTrueTypeFont.loadTTF(doc, fontStream);

        // create a page with the message where needed
        PDPageContentStream contentStream = new PDPageContentStream(doc, page);
        contentStream.beginText();
        contentStream.setFont(font, 12);
        contentStream.moveTextPositionByAmount(100, 700);
        contentStream.drawString(message);
        contentStream.endText();
        contentStream.saveGraphicsState();
        contentStream.close();

        PDDocumentCatalog cat = makeA3compliant(doc);
        attachSampleFile(doc);

        InputStream colorProfile = PDFA3FileAttachment.class
                .getResourceAsStream("/sRGB Color Space Profile.icm");
        // create output intent
        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");
        cat.addOutputIntent(oi);

        doc.save(file);

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

From source file:pdfbox.PDFAFile.java

License:Apache License

/**
 * Create a simple PDF/A document./*from w w w  .j ava 2s .c  om*/
 * This example is based on HelloWorld example.
 * As it is a simple case, to conform the PDF/A norm, are added : - the font
 * used in the document - a light xmp block with only PDF identification
 * schema (the only mandatory) - an output intent
 * 
 * @param file
 *          The file to write the PDF to.
 * @param message
 *          The message to write in the file.
 * @throws Exception
 *           If something bad occurs
 */
public void doIt(String file, String message) throws Exception {
    // the document
    PDDocument doc = null;
    try {
        doc = new PDDocument();

        PDPage page = new PDPage();
        doc.addPage(page);

        InputStream fontStream = PDFA3File.class.getResourceAsStream("/Ubuntu-R.ttf");
        PDFont font = PDTrueTypeFont.loadTTF(doc, fontStream);

        // create a page with the message where needed
        PDPageContentStream contentStream = new PDPageContentStream(doc, page);
        contentStream.beginText();
        contentStream.setFont(font, 12);
        contentStream.moveTextPositionByAmount(100, 700);
        contentStream.drawString(message);
        contentStream.endText();
        contentStream.saveGraphicsState();
        contentStream.close();

        PDDocumentCatalog cat = doc.getDocumentCatalog();
        PDMetadata metadata = new PDMetadata(doc);
        cat.setMetadata(metadata);

        // jempbox version
        XMPMetadata xmp = new XMPMetadata();
        XMPSchemaPDFAId pdfaid = new XMPSchemaPDFAId(xmp);
        xmp.addSchema(pdfaid);
        pdfaid.setConformance("B");
        pdfaid.setPart(1);
        pdfaid.setAbout("");
        metadata.importXMPMetadata(xmp.asByteArray());

        InputStream colorProfile = PDFA3File.class.getResourceAsStream("/sRGB Color Space Profile.icm");
        // create output intent
        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");
        cat.addOutputIntent(oi);

        doc.save(file);

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