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

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

Introduction

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

Prototype

@Override
public PDResources getResources() 

Source Link

Document

A dictionary containing any resources required by the page.

Usage

From source file:airviewer.AnnotationGenerator.java

/**
 *
 * @param a//from  w  w w . j av a  2  s.  c  om
 * @param d
 * @param p
 * @param shouldResize
 * @return
 */
public static PDAppearanceStream generateSquareAppearance(PDAnnotation a, PDDocument d, PDPage p,
        boolean shouldResize) {
    assert null != a;
    assert null != d;
    assert null != p;

    PDAppearanceStream annotationAppearanceStream = null;

    try {
        if (shouldResize) {
            resizeAnnotationToContent(a);
        }

        final String contents = a.getContents();
        final boolean hasContents = null != contents && 0 < contents.length();
        float borderWidth = 0;
        if (a instanceof PDAnnotationMarkup) {
            final PDBorderStyleDictionary borderStyle = ((PDAnnotationMarkup) a).getBorderStyle();
            if (null != a.getColor() && null != borderStyle) {
                borderWidth = Math.abs(borderStyle.getWidth());
            }
        }
        final float fontSize = FONT_SIZE_PDF_POINTS;
        final float textHeight = fontSize;
        final float margin = MARGIN_SIZE_PDF_POINTS;

        PDRectangle position = a.getRectangle();
        final float lowerLeftX = position.getLowerLeftX();
        final float lowerLeftY = position.getLowerLeftY();
        float width = position.getWidth();
        float height = position.getHeight();

        annotationAppearanceStream = new PDAppearanceStream(d);

        annotationAppearanceStream.setBBox(position);
        annotationAppearanceStream.setMatrix(new AffineTransform());
        annotationAppearanceStream.setResources(p.getResources());

        try (PDPageContentStream appearanceContent = new PDPageContentStream(d, annotationAppearanceStream)) {
            appearanceContent.transform(new Matrix()); // Identity transform

            // Rect is inset by half border width to prevent border leaking
            // outside bounding box
            final float insetLowerLeftX = lowerLeftX + borderWidth * 0.5f;
            final float insetLowerLeftY = lowerLeftY + borderWidth * 0.5f;
            final float insetWidth = width - borderWidth;
            final float insetheight = height - borderWidth;
            appearanceContent.addRect(insetLowerLeftX, insetLowerLeftY, insetWidth, insetheight);
            appearanceContent.setLineWidth(borderWidth);
            appearanceContent.setNonStrokingColor(GRAY);

            if (null != a.getColor() && 0 < borderWidth) {
                appearanceContent.setStrokingColor(a.getColor());
                appearanceContent.fillAndStroke();
            } else {
                appearanceContent.fill();

            }

            if (hasContents) {
                appearanceContent.moveTo(0, 0);
                appearanceContent.beginText();

                // Center vertically, left justified inside border with margin
                appearanceContent.newLineAtOffset(lowerLeftX + borderWidth + margin,
                        lowerLeftY + (height + LINE_SPACE_SIZE_PDF_POINTS) * 0.5f - textHeight * 0.5f);
                appearanceContent.setFont(FONT, fontSize);
                if (null != a.getColor()) {
                    appearanceContent.setNonStrokingColor(a.getColor()); // Sets color of text
                } else {
                    appearanceContent.setNonStrokingColor(BLACK); // Sets color of text

                }
                appearanceContent.showText(a.getContents());
                appearanceContent.endText();
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(AnnotationGenerator.class.getName()).log(Level.SEVERE, null, ex);
    }

    return annotationAppearanceStream;
}

From source file:airviewer.AnnotationGenerator.java

/**
 *
 * @param a/*from w w w . jav a  2s  .  c  om*/
 * @param d
 * @param p
 * @param shouldResize
 * @return
 */
public static PDAppearanceStream generateCircleAppearance(PDAnnotation a, PDDocument d, PDPage p,
        boolean shouldResize) {
    assert null != a;
    assert null != d;
    assert null != p;

    PDAppearanceStream annotationAppearanceStream = null;

    try {
        if (shouldResize) {
            resizeAnnotationToContent(a);
        }

        final String contents = a.getContents();
        final boolean hasContents = null != contents && 0 < contents.length();
        float borderWidth = 0;
        if (a instanceof PDAnnotationMarkup) {
            final PDBorderStyleDictionary borderStyle = ((PDAnnotationMarkup) a).getBorderStyle();
            if (null != a.getColor() && null != borderStyle) {
                borderWidth = Math.abs(borderStyle.getWidth());
            }
        }
        final float fontSize = FONT_SIZE_PDF_POINTS;
        final float textHeight = fontSize;
        final float margin = MARGIN_SIZE_PDF_POINTS;

        PDRectangle position = a.getRectangle();
        final float lowerLeftX = position.getLowerLeftX();
        final float lowerLeftY = position.getLowerLeftY();
        float width = position.getWidth();
        float height = position.getHeight();

        annotationAppearanceStream = new PDAppearanceStream(d);

        annotationAppearanceStream.setBBox(position);
        annotationAppearanceStream.setMatrix(new AffineTransform());
        annotationAppearanceStream.setResources(p.getResources());

        try (PDPageContentStream appearanceContent = new PDPageContentStream(d, annotationAppearanceStream)) {
            appearanceContent.transform(new Matrix()); // Identity transform

            // Rect is inset by half border width to prevent border leaking
            // outside bounding box
            final float insetLowerLeftX = lowerLeftX + borderWidth * 0.5f;
            final float insetLowerLeftY = lowerLeftY + borderWidth * 0.5f;
            final float insetWidth = width - borderWidth;
            final float insetheight = height - borderWidth;

            if (null != a.getColor()) {
                appearanceContent.setLineWidth(borderWidth);
                appearanceContent.moveTo(insetLowerLeftX, insetLowerLeftY + insetheight * 0.5f);
                appearanceContent.curveTo(insetLowerLeftX, insetLowerLeftY + insetheight * 0.75f,
                        insetLowerLeftX + insetWidth * 0.25f, insetLowerLeftY + insetheight,
                        insetLowerLeftX + insetWidth * 0.5f, insetLowerLeftY + insetheight);
                appearanceContent.curveTo(insetLowerLeftX + insetWidth * 0.75f, insetLowerLeftY + insetheight,
                        insetLowerLeftX + insetWidth, insetLowerLeftY + insetheight * 0.75f,
                        insetLowerLeftX + insetWidth, insetLowerLeftY + insetheight * 0.5f);
                appearanceContent.curveTo(insetLowerLeftX + insetWidth, insetLowerLeftY + insetheight * 0.25f,
                        insetLowerLeftX + insetWidth * 0.75f, insetLowerLeftY,
                        insetLowerLeftX + insetWidth * 0.5f, insetLowerLeftY);
                appearanceContent.curveTo(insetLowerLeftX + insetWidth * 0.25f, insetLowerLeftY,
                        insetLowerLeftX, insetLowerLeftY + insetheight * 0.25f, insetLowerLeftX,
                        insetLowerLeftY + insetheight * 0.5f);
            }
            appearanceContent.setNonStrokingColor(GRAY);

            if (null != a.getColor() && 0 < borderWidth) {
                appearanceContent.setStrokingColor(a.getColor());
                appearanceContent.fillAndStroke();
            } else {
                appearanceContent.fill();

            }

            if (hasContents) {
                appearanceContent.moveTo(0, 0);
                appearanceContent.beginText();

                // Center text vertically, left justified inside border with margin
                appearanceContent.newLineAtOffset(lowerLeftX + borderWidth + margin,
                        lowerLeftY + (height + LINE_SPACE_SIZE_PDF_POINTS) * 0.5f - textHeight * 0.5f);
                appearanceContent.setFont(FONT, fontSize);
                appearanceContent.setNonStrokingColor(BLACK); // Sets color of text
                appearanceContent.showText(a.getContents());
                appearanceContent.endText();
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(AnnotationGenerator.class.getName()).log(Level.SEVERE, null, ex);
    }

    return annotationAppearanceStream;
}

From source file:airviewer.BoxAnnotationMaker.java

License:Apache License

/**
 *
 * @param document/*w  w w  .j  ava 2 s .  co m*/
 * @param arguments(lowerLeftX, lowerLeftY, width, height)
 * @return
 */
public static List<PDAnnotation> make(PDDocument document, ArrayList<String> arguments) {
    assert null != arguments && arguments.size() == 5;
    assert null != document;

    List<PDAnnotation> result;

    try {
        int pageNumber = parseInt(arguments.get(0));
        float lowerLeftX = parseFloat(arguments.get(1));
        float lowerLeftY = parseFloat(arguments.get(2));
        float width = parseFloat(arguments.get(3));
        float height = parseFloat(arguments.get(4));
        String contents = "";
        PDFont font = PDType1Font.HELVETICA_OBLIQUE;
        float fontSize = 16; // Or whatever font size you want.
        //float textWidth = font.getStringWidth(contents) * fontSize / 1000.0f;
        //float textHeight = 32;

        try {
            PDPage page = document.getPage(pageNumber);
            PDColor red = new PDColor(new float[] { 1, 0, 0 }, PDDeviceRGB.INSTANCE);
            PDBorderStyleDictionary borderThick = new PDBorderStyleDictionary();
            borderThick.setWidth(72 / 12); // 12th inch
            PDRectangle position = new PDRectangle();
            position.setLowerLeftX(lowerLeftX);
            position.setLowerLeftY(lowerLeftY);
            position.setUpperRightX(lowerLeftX + width);
            position.setUpperRightY(lowerLeftY + height);

            PDAnnotationSquareCircle aSquare = new PDAnnotationSquareCircle(
                    PDAnnotationSquareCircle.SUB_TYPE_SQUARE);
            aSquare.setAnnotationName(new UID().toString());
            aSquare.setContents(contents);
            aSquare.setColor(red); // Outline in red, not setting a fill
            PDColor fillColor = new PDColor(new float[] { .8f, .8f, .8f }, PDDeviceRGB.INSTANCE);
            aSquare.setInteriorColor(fillColor);
            aSquare.setBorderStyle(borderThick);
            aSquare.setRectangle(position);
            result = new ArrayList<>(page.getAnnotations()); // copy
            page.getAnnotations().add(aSquare);

            // The following lines are needed for PDFRenderer to render 
            // annotations. Preview and Acrobat don't seem to need these.
            if (null == aSquare.getAppearance()) {
                aSquare.setAppearance(new PDAppearanceDictionary());
                PDAppearanceStream annotationAppearanceStream = new PDAppearanceStream(document);
                position.setLowerLeftX(lowerLeftX - borderThick.getWidth() * 0.5f);
                position.setLowerLeftY(lowerLeftY - borderThick.getWidth() * 0.5f);
                position.setUpperRightX(lowerLeftX + width + borderThick.getWidth() * 0.5f);
                position.setUpperRightY(lowerLeftY + height + borderThick.getWidth() * 0.5f);
                annotationAppearanceStream.setBBox(position);
                annotationAppearanceStream.setMatrix(new AffineTransform());
                annotationAppearanceStream.setResources(page.getResources());

                try (PDPageContentStream appearanceContent = new PDPageContentStream(document,
                        annotationAppearanceStream)) {
                    Matrix transform = new Matrix();
                    appearanceContent.transform(transform);
                    appearanceContent.addRect(lowerLeftX, lowerLeftY, width, height);
                    appearanceContent.setLineWidth(borderThick.getWidth());
                    appearanceContent.setNonStrokingColor(fillColor);
                    appearanceContent.setStrokingColor(red);
                    appearanceContent.fillAndStroke();
                    appearanceContent.beginText();

                    // Center text vertically, left justified
                    appearanceContent.newLineAtOffset(lowerLeftX, lowerLeftY + height * 0.5f - fontSize * 0.5f);
                    appearanceContent.setFont(font, fontSize);
                    appearanceContent.setNonStrokingColor(red);
                    appearanceContent.showText(contents);
                    appearanceContent.endText();
                }
                aSquare.getAppearance().setNormalAppearance(annotationAppearanceStream);
            }
            //System.out.println(page.getAnnotations().toString());

        } catch (IOException ex) {
            Logger.getLogger(DocumentCommandWrapper.class.getName()).log(Level.SEVERE, null, ex);
            result = null;
        }
    } catch (NumberFormatException | NullPointerException ex) {
        System.err.println("\tNon number encountered where floating point number expected.");
        result = null;
    }

    return result;
}

From source file:airviewer.EllipseAnnotationMaker.java

License:Apache License

/**
 * /*from  w  w  w  .  jav a 2  s .com*/
 * @param document
 * @param arguments(pageNumber, lowerLeftX, lowerLeftY, width, height, contents)
 * @return 
 */
public static List<PDAnnotation> make(PDDocument document, ArrayList<String> arguments) {
    assert null != arguments && arguments.size() == 6;
    assert null != document;

    List<PDAnnotation> result;

    try {
        int pageNumber = parseInt(arguments.get(0));
        float lowerLeftX = parseFloat(arguments.get(1));
        float lowerLeftY = parseFloat(arguments.get(2));
        float width = parseFloat(arguments.get(3));
        float height = parseFloat(arguments.get(4));
        String contents = arguments.get(5);

        PDFont font = PDType1Font.HELVETICA_OBLIQUE;
        final float fontSize = 16.0f; // Or whatever font size you want.
        //final float lineSpacing = 4.0f;
        width = max(width, font.getStringWidth(contents) * fontSize / 1000.0f);
        //final float textHeight = fontSize + lineSpacing;

        try {
            PDPage page = document.getPage(pageNumber);
            PDColor red = new PDColor(new float[] { 1, 0, 0 }, PDDeviceRGB.INSTANCE);
            PDColor black = new PDColor(new float[] { 0, 0, 0 }, PDDeviceRGB.INSTANCE);
            PDBorderStyleDictionary borderThick = new PDBorderStyleDictionary();
            borderThick.setWidth(72 / 12); // 12th inch
            PDRectangle position = new PDRectangle();
            position.setLowerLeftX(lowerLeftX);
            position.setLowerLeftY(lowerLeftY);
            position.setUpperRightX(lowerLeftX + width);
            position.setUpperRightY(lowerLeftY + height);

            PDAnnotationSquareCircle aCircle = new PDAnnotationSquareCircle(
                    PDAnnotationSquareCircle.SUB_TYPE_CIRCLE);
            aCircle.setAnnotationName(new UID().toString());
            aCircle.setContents(contents);
            PDColor fillColor = new PDColor(new float[] { .8f, .8f, .8f }, PDDeviceRGB.INSTANCE);
            aCircle.setInteriorColor(fillColor);
            aCircle.setColor(red);
            aCircle.setBorderStyle(borderThick);
            aCircle.setRectangle(position);

            result = new ArrayList<>(page.getAnnotations()); // Copy
            page.getAnnotations().add(aCircle);

            // The following lines are needed for PDFRenderer to render 
            // annotations. Preview and Acrobat don't seem to need these.
            if (null == aCircle.getAppearance()) {
                aCircle.setAppearance(new PDAppearanceDictionary());
                PDAppearanceStream annotationAppearanceStream = new PDAppearanceStream(document);
                position.setLowerLeftX(lowerLeftX - borderThick.getWidth() * 0.5f);
                position.setLowerLeftY(lowerLeftY - borderThick.getWidth() * 0.5f);
                position.setUpperRightX(lowerLeftX + width + borderThick.getWidth() * 0.5f);
                position.setUpperRightY(lowerLeftY + height + borderThick.getWidth() * 0.5f);
                annotationAppearanceStream.setBBox(position);
                annotationAppearanceStream.setMatrix(new AffineTransform());
                annotationAppearanceStream.setResources(page.getResources());

                try (PDPageContentStream appearanceContent = new PDPageContentStream(document,
                        annotationAppearanceStream)) {
                    Matrix transform = new Matrix();
                    appearanceContent.transform(transform);
                    appearanceContent.moveTo(lowerLeftX, lowerLeftY + height * 0.5f);
                    appearanceContent.curveTo(lowerLeftX, lowerLeftY + height * 0.75f,
                            lowerLeftX + width * 0.25f, lowerLeftY + height, lowerLeftX + width * 0.5f,
                            lowerLeftY + height);
                    appearanceContent.curveTo(lowerLeftX + width * 0.75f, lowerLeftY + height,
                            lowerLeftX + width, lowerLeftY + height * 0.75f, lowerLeftX + width,
                            lowerLeftY + height * 0.5f);
                    appearanceContent.curveTo(lowerLeftX + width, lowerLeftY + height * 0.25f,
                            lowerLeftX + width * 0.75f, lowerLeftY, lowerLeftX + width * 0.5f, lowerLeftY);
                    appearanceContent.curveTo(lowerLeftX + width * 0.25f, lowerLeftY, lowerLeftX,
                            lowerLeftY + height * 0.25f, lowerLeftX, lowerLeftY + height * 0.5f);
                    appearanceContent.setLineWidth(borderThick.getWidth());
                    appearanceContent.setNonStrokingColor(fillColor);
                    appearanceContent.setStrokingColor(red);
                    appearanceContent.fillAndStroke();
                    appearanceContent.moveTo(0, 0);

                    appearanceContent.beginText();
                    appearanceContent.setNonStrokingColor(black);
                    // Center text vertically, left justified
                    appearanceContent.newLineAtOffset(lowerLeftX + borderThick.getWidth(),
                            lowerLeftY + height * 0.5f - fontSize * 0.5f);
                    appearanceContent.setFont(font, fontSize);
                    appearanceContent.showText(contents);
                    appearanceContent.endText();
                }
                aCircle.getAppearance().setNormalAppearance(annotationAppearanceStream);
            }

        } catch (IOException ex) {
            Logger.getLogger(DocumentCommandWrapper.class.getName()).log(Level.SEVERE, null, ex);
            result = null;
        }
    } catch (NumberFormatException | NullPointerException ex) {
        System.err.println("Non number encountered where floating point number expected.");
        result = null;
    } catch (IOException ex) {
        Logger.getLogger(EllipseAnnotationMaker.class.getName()).log(Level.SEVERE, null, ex);
        result = null;
    }

    return result;
}

From source file:airviewer.TextAnnotationMaker.java

License:Apache License

/**
 * //from   w  w w  .ja  va  2 s.  com
 * @param document
 * @param arguments(pageNumber, lowerLeftX, lowerLeftY);
        
    String contents 
 * @return 
 */
public static List<PDAnnotation> make(PDDocument document, ArrayList<String> arguments) {
    assert null != arguments && arguments.size() == 4;
    assert null != document;

    List<PDAnnotation> result;

    try {
        int pageNumber = parseInt(arguments.get(0));
        float lowerLeftX = parseFloat(arguments.get(1));
        float lowerLeftY = parseFloat(arguments.get(2));

        String contents = arguments.get(3);
        PDFont font = PDType1Font.HELVETICA_OBLIQUE;
        final float fontSize = 16.0f; // Or whatever font size you want.
        final float lineSpacing = 4.0f;
        float width = font.getStringWidth(contents) * fontSize / 1000.0f; // font.getStringWidth(contents) returns thousanths of PS point
        final float textHeight = fontSize + lineSpacing;

        try {
            PDPage page = document.getPage(pageNumber);
            PDColor red = new PDColor(new float[] { 1, 0, 0 }, PDDeviceRGB.INSTANCE);
            PDBorderStyleDictionary borderThick = new PDBorderStyleDictionary();
            borderThick.setWidth(72 / 12); // 12th inch
            PDRectangle position = new PDRectangle();
            position.setLowerLeftX(lowerLeftX);
            position.setLowerLeftY(lowerLeftY);
            position.setUpperRightX(lowerLeftX + width);
            position.setUpperRightY(lowerLeftY + textHeight);

            PDAnnotationSquareCircle aSquare = new PDAnnotationSquareCircle(
                    PDAnnotationSquareCircle.SUB_TYPE_SQUARE);
            aSquare.setAnnotationName(new UID().toString());
            aSquare.setContents(contents);
            PDColor fillColor = new PDColor(new float[] { .8f, .8f, .8f }, PDDeviceRGB.INSTANCE);
            aSquare.setInteriorColor(fillColor);
            aSquare.setRectangle(position);
            result = new ArrayList<>(page.getAnnotations()); // copy
            page.getAnnotations().add(aSquare);

            // The following lines are needed for PDFRenderer to render 
            // annotations. Preview and Acrobat don't seem to need these.
            if (null == aSquare.getAppearance()) {
                aSquare.setAppearance(new PDAppearanceDictionary());
                PDAppearanceStream annotationAppearanceStream = new PDAppearanceStream(document);
                position.setLowerLeftX(lowerLeftX - borderThick.getWidth() * 0.5f);
                position.setLowerLeftY(lowerLeftY - borderThick.getWidth() * 0.5f);
                position.setUpperRightX(lowerLeftX + width + borderThick.getWidth() * 0.5f);
                position.setUpperRightY(lowerLeftY + textHeight + borderThick.getWidth() * 0.5f);
                annotationAppearanceStream.setBBox(position);
                annotationAppearanceStream.setMatrix(new AffineTransform());
                annotationAppearanceStream.setResources(page.getResources());

                try (PDPageContentStream appearanceContent = new PDPageContentStream(document,
                        annotationAppearanceStream)) {
                    Matrix transform = new Matrix();
                    appearanceContent.transform(transform);
                    appearanceContent.addRect(lowerLeftX, lowerLeftY, width, textHeight);
                    appearanceContent.setNonStrokingColor(fillColor);
                    appearanceContent.fill();
                    appearanceContent.beginText();

                    // Center text vertically, left justified
                    appearanceContent.newLineAtOffset(lowerLeftX,
                            lowerLeftY + textHeight * 0.5f - fontSize * 0.5f);
                    appearanceContent.setFont(font, fontSize);
                    appearanceContent.setNonStrokingColor(red);
                    appearanceContent.showText(contents);
                    appearanceContent.endText();
                }
                aSquare.getAppearance().setNormalAppearance(annotationAppearanceStream);
            }
            //System.out.println(page.getAnnotations().toString());

        } catch (IOException ex) {
            Logger.getLogger(DocumentCommandWrapper.class.getName()).log(Level.SEVERE, null, ex);
            result = null;
        }
    } catch (NumberFormatException | NullPointerException ex) {
        System.err.println("Non number encountered where floating point number expected.");
        result = null;
    } catch (IOException ex) {
        Logger.getLogger(TextAnnotationMaker.class.getName()).log(Level.SEVERE, null, ex);
        result = null;
    }

    return result;
}

From source file:at.gv.egiz.pdfas.lib.impl.pdfbox2.placeholder.SignaturePlaceholderExtractor.java

License:EUPL

/**
 * Search the document for placeholder images and possibly included
 * additional info.<br/>//  w w  w  .j  a  va 2  s.  c om
 * Searches only for the first placeholder page after page from top.
 *
 * @param inputStream
 * @return all available info from the first found placeholder.
 * @throws PDFDocumentException
 *             if the document could not be read.
 * @throws PlaceholderExtractionException
 *             if STRICT matching mode was requested and no suitable
 *             placeholder could be found.
 */
public static SignaturePlaceholderData extract(PDDocument doc, String placeholderId, int matchMode)
        throws PdfAsException {
    SignaturePlaceholderContext.setSignaturePlaceholderData(null);

    SignaturePlaceholderExtractor extractor;
    try {
        extractor = new SignaturePlaceholderExtractor(placeholderId, matchMode, doc);
    } catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException e2) {
        throw new PDFIOException("error.pdf.io.04", e2);
    }

    int pageNr = 0;
    for (PDPage page : doc.getPages()) {
        pageNr++;

        try {
            extractor.setCurrentPage(pageNr);
            if (page.getContents() != null && page.getResources() != null && page.getContentStreams() != null) {
                extractor.processPage(page); //TODO: pdfbox2 - right?

            }
            SignaturePlaceholderData ret = matchPlaceholderPage(extractor.placeholders, placeholderId,
                    matchMode);
            if (ret != null) {
                SignaturePlaceholderContext.setSignaturePlaceholderData(ret);
                return ret;
            }
        } catch (IOException e1) {
            throw new PDFIOException("error.pdf.io.04", e1);
        } catch (Throwable e) {
            throw new PDFIOException("error.pdf.io.04", e);
        }
    }
    if (extractor.placeholders.size() > 0) {
        SignaturePlaceholderData ret = matchPlaceholderDocument(extractor.placeholders, placeholderId,
                matchMode);
        SignaturePlaceholderContext.setSignaturePlaceholderData(ret);
        return ret;
    }
    // no placeholders found, apply strict mode if set
    if (matchMode == PLACEHOLDER_MATCH_MODE_STRICT) {
        throw new PlaceholderExtractionException("error.pdf.stamp.09");
    }

    return null;
}

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  w  w . j a v a 2 s.co 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:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox2.PDFAsVisualSignatureBuilder.java

License:EUPL

public void removeCidSet(PDDocument document) throws IOException {

    PDDocumentCatalog catalog = document.getDocumentCatalog();

    COSName cidSet = COSName.getPDFName("CIDSet");

    Iterator<PDPage> pdPageIterator = catalog.getPages().iterator();
    while (pdPageIterator.hasNext()) {

        PDPage page = pdPageIterator.next();

        Iterator<COSName> cosNameIterator = page.getResources().getFontNames().iterator();
        while (cosNameIterator.hasNext()) {
            COSName fontName = cosNameIterator.next();
            PDFont pdFont = page.getResources().getFont(fontName);

            if (pdFont instanceof PDType0Font) {
                PDType0Font typedFont = (PDType0Font) pdFont;

                if (typedFont.getDescendantFont() != null) {
                    if (typedFont.getDescendantFont().getFontDescriptor() != null) {
                        typedFont.getDescendantFont().getFontDescriptor().getCOSObject().removeItem(cidSet);
                    }//from ww  w . ja  v a 2s  .com
                }
            }
        }
    }
}

From source file:com.fileOperations.StampPDF.java

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

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

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

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

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

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

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

From source file:com.jaeksoft.searchlib.util.pdfbox.PDFBoxUtils.java

License:Open Source License

public static final int countCheckImage(PDPage page) throws IOException {
    PDResources resources = page.getResources();
    Map<String, PDXObject> objects = resources.getXObjects();
    if (objects == null)
        return 0;
    int count = 0;
    for (PDXObject object : objects.values())
        if (object instanceof PDXObjectImage)
            count++;/*  ww w .j  ava2  s .  c  o m*/
    return count;
}