Example usage for org.apache.pdfbox.pdmodel.common PDRectangle getLowerLeftX

List of usage examples for org.apache.pdfbox.pdmodel.common PDRectangle getLowerLeftX

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel.common PDRectangle getLowerLeftX.

Prototype

public float getLowerLeftX() 

Source Link

Document

This will get the lower left x coordinate.

Usage

From source file:airviewer.AnnotationGenerator.java

/**
 *
 * @param a/*from   ww w  . j  a  va 2  s  . c  om*/
 * @throws IOException
 */
public static void resizeAnnotationToContent(PDAnnotation a) throws IOException {
    assert null != a;

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

        float width = FONT.getStringWidth(contents) * fontSize / SIZE_UNITS_PER_PDF_POINT;
        float height = textHeight;

        // Reserve enough width for border and margin at start and end
        width += (borderWidth + MARGIN_SIZE_PDF_POINTS) * 2.0f;
        height += (borderWidth + MARGIN_SIZE_PDF_POINTS) * 2.0f;

        // Replace the annotations existing rectangle
        a.setRectangle(new PDRectangle(lowerLeftX, lowerLeftY, width, height));
    }

}

From source file:airviewer.AnnotationGenerator.java

/**
 *
 * @param a/*  w w  w . j av  a  2s.  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 ww.  j  a va  2s  . co  m*/
 * @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.AnnotationGenerator.java

/**
 * // w  w  w  .  jav  a 2s  .com
 * @param document
 * @param page
 * @param subtype
 * @param position
 * @param borderColor
 * @param fillColor
 * @param borderWidth
 * @param contents
 * @return 
 */
public static PDAnnotationMarkup makeAnnotation(PDDocument document, PDPage page, String subtype,
        PDRectangle position, PDColor borderColor, PDColor fillColor, float borderWidth, String contents) {
    assert null != document;
    assert null != page;
    assert null != subtype;
    assert null != position;

    PDAnnotationMarkup result = null;

    try {
        if (null != contents && 0 < contents.length()) {
            PDFont font = FONT;
            final float fontSize = FONT_SIZE_PDF_POINTS;
            final float lineSpacing = LINE_SPACE_SIZE_PDF_POINTS;
            float width = max(position.getWidth(),
                    font.getStringWidth(contents) * fontSize / AnnotationGenerator.SIZE_UNITS_PER_PDF_POINT);
            position.setUpperRightX(position.getLowerLeftX() + width);
        }

        PDAnnotationSquareCircle a = new PDAnnotationSquareCircle(subtype);
        a.setAnnotationName(new UID().toString());
        a.setContents(contents);
        a.setRectangle(position);

        if (null != fillColor) {
            a.setInteriorColor(fillColor);
        }

        if (0 < borderWidth) {
            PDBorderStyleDictionary borderStyle = new PDBorderStyleDictionary();
            borderStyle.setWidth(borderWidth);
            a.setBorderStyle(borderStyle);
            if (null != borderColor) {
                a.setColor(borderColor);

            }
        }

        // The following lines are needed for PDFRenderer to render 
        // annotations. Preview and Acrobat don't seem to need these.
        if (null == a.getAppearance()) {
            a.setAppearance(new PDAppearanceDictionary());
            PDAppearanceStream annotationAppearanceStream = AnnotationGenerator.generateAppearanceStream(a,
                    document, page, true);
            a.getAppearance().setNormalAppearance(annotationAppearanceStream);
        }

        result = a;

    } catch (IOException | NullPointerException ex) {
        Logger.getLogger(EllipseAnnotationMaker.class.getName()).log(Level.SEVERE, null, ex);
    }

    return result;
}

From source file:aplicacion.sistema.indexer.test.PDFTextStripperOrg.java

License:Apache License

/**
 * This will process a TextPosition object and add the
 * text to the list of characters on a page.  It takes care of
 * overlapping text./*from   ww  w. j a  v a  2 s .co  m*/
 *
 * @param text The text to process.
 */
protected void processTextPosition(TextPosition text) {
    boolean showCharacter = true;
    if (suppressDuplicateOverlappingText) {
        showCharacter = false;
        String textCharacter = text.getCharacter();
        float textX = text.getX();
        float textY = text.getY();
        List sameTextCharacters = (List) characterListMapping.get(textCharacter);
        if (sameTextCharacters == null) {
            sameTextCharacters = new ArrayList();
            characterListMapping.put(textCharacter, sameTextCharacters);
        }

        // RDD - Here we compute the value that represents the end of the rendered
        // text.  This value is used to determine whether subsequent text rendered
        // on the same line overwrites the current text.
        //
        // We subtract any positive padding to handle cases where extreme amounts
        // of padding are applied, then backed off (not sure why this is done, but there
        // are cases where the padding is on the order of 10x the character width, and
        // the TJ just backs up to compensate after each character).  Also, we subtract
        // an amount to allow for kerning (a percentage of the width of the last
        // character).
        //
        boolean suppressCharacter = false;
        float tolerance = (text.getWidth() / textCharacter.length()) / 3.0f;
        for (int i = 0; i < sameTextCharacters.size() && textCharacter != null; i++) {
            TextPosition character = (TextPosition) sameTextCharacters.get(i);
            String charCharacter = character.getCharacter();
            float charX = character.getX();
            float charY = character.getY();
            //only want to suppress

            if (charCharacter != null &&
            //charCharacter.equals( textCharacter ) &&
                    within(charX, textX, tolerance) && within(charY, textY, tolerance)) {
                suppressCharacter = true;
            }
        }
        if (!suppressCharacter) {
            sameTextCharacters.add(text);
            showCharacter = true;
        }
    }

    if (showCharacter) {
        //if we are showing the character then we need to determine which
        //article it belongs to.
        int foundArticleDivisionIndex = -1;
        int notFoundButFirstLeftAndAboveArticleDivisionIndex = -1;
        int notFoundButFirstLeftArticleDivisionIndex = -1;
        int notFoundButFirstAboveArticleDivisionIndex = -1;
        float x = text.getX();
        float y = text.getY();
        if (shouldSeparateByBeads) {
            for (int i = 0; i < pageArticles.size() && foundArticleDivisionIndex == -1; i++) {
                PDThreadBead bead = (PDThreadBead) pageArticles.get(i);
                if (bead != null) {
                    PDRectangle rect = bead.getRectangle();
                    if (rect.contains(x, y)) {
                        foundArticleDivisionIndex = i * 2 + 1;
                    } else if ((x < rect.getLowerLeftX() || y < rect.getUpperRightY())
                            && notFoundButFirstLeftAndAboveArticleDivisionIndex == -1) {
                        notFoundButFirstLeftAndAboveArticleDivisionIndex = i * 2;
                    } else if (x < rect.getLowerLeftX() && notFoundButFirstLeftArticleDivisionIndex == -1) {
                        notFoundButFirstLeftArticleDivisionIndex = i * 2;
                    } else if (y < rect.getUpperRightY() && notFoundButFirstAboveArticleDivisionIndex == -1) {
                        notFoundButFirstAboveArticleDivisionIndex = i * 2;
                    }
                } else {
                    foundArticleDivisionIndex = 0;
                }
            }
        } else {
            foundArticleDivisionIndex = 0;
        }
        int articleDivisionIndex = -1;
        if (foundArticleDivisionIndex != -1) {
            articleDivisionIndex = foundArticleDivisionIndex;
        } else if (notFoundButFirstLeftAndAboveArticleDivisionIndex != -1) {
            articleDivisionIndex = notFoundButFirstLeftAndAboveArticleDivisionIndex;
        } else if (notFoundButFirstLeftArticleDivisionIndex != -1) {
            articleDivisionIndex = notFoundButFirstLeftArticleDivisionIndex;
        } else if (notFoundButFirstAboveArticleDivisionIndex != -1) {
            articleDivisionIndex = notFoundButFirstAboveArticleDivisionIndex;
        } else {
            articleDivisionIndex = charactersByArticle.size() - 1;
        }

        List textList = (List) charactersByArticle.get(articleDivisionIndex);

        /* In the wild, some PDF encoded documents put diacritics (accents on
         * top of characters) into a separate Tj element.  When displaying them
         * graphically, the two chunks get overlayed.  With text output though,
         * we need to do the overlay. This code recombines the diacritic with
         * its associated character if the two are consecutive.
         */
        if (textList.isEmpty()) {
            textList.add(text);
        } else {
            /* test if we overlap the previous entry.  
             * Note that we are making an assumption that we need to only look back
             * one TextPosition to find what we are overlapping.  
             * This may not always be true. */
            TextPosition previousTextPosition = (TextPosition) textList.get(textList.size() - 1);
            if (text.isDiacritic() && previousTextPosition.contains(text)) {
                previousTextPosition.mergeDiacritic(text, normalize);
            }
            /* If the previous TextPosition was the diacritic, merge it into this
             * one and remove it from the list. */
            else if (previousTextPosition.isDiacritic() && text.contains(previousTextPosition)) {
                text.mergeDiacritic(previousTextPosition, normalize);
                textList.remove(textList.size() - 1);
                textList.add(text);
            } else {
                textList.add(text);
            }
        }
    }
}

From source file:at.gv.egiz.pdfas.lib.impl.pdfbox.positioning.Positioning.java

License:EUPL

private static PDRectangle rotateBox(PDRectangle cropBox, int rotation) {
    if (rotation != 0) {
        Point2D upSrc = new Point2D.Float();

        upSrc.setLocation(cropBox.getUpperRightX(), cropBox.getUpperRightY());

        Point2D llSrc = new Point2D.Float();
        llSrc.setLocation(cropBox.getLowerLeftX(), cropBox.getLowerLeftY());
        AffineTransform transform = new AffineTransform();
        transform.setToIdentity();//from  www. j  a  v a 2 s.  co m
        if (rotation % 360 != 0) {
            transform.setToRotation(Math.toRadians(rotation * -1), llSrc.getX(), llSrc.getY());
        }
        Point2D upDst = new Point2D.Float();
        transform.transform(upSrc, upDst);

        Point2D llDst = new Point2D.Float();
        transform.transform(llSrc, llDst);

        float y1 = (float) upDst.getY();
        float y2 = (float) llDst.getY();

        if (y1 > y2) {
            float t = y1;
            y1 = y2;
            y2 = t;
        }

        if (y1 < 0) {
            y2 = y2 + -1 * y1;
            y1 = 0;
        }

        float x1 = (float) upDst.getX();
        float x2 = (float) llDst.getX();

        if (x1 > x2) {
            float t = x1;
            x1 = x2;
            x2 = t;
        }

        if (x1 < 0) {
            x2 = x2 + -1 * x1;
            x1 = 0;
        }

        cropBox.setUpperRightX(x2);
        cropBox.setUpperRightY(y2);
        cropBox.setLowerLeftY(y1);
        cropBox.setLowerLeftX(x1);
    }
    return cropBox;
}

From source file:ch.uzh.ifi.pdeboer.pdfpreprocessing.pdf.TextHighlight.java

License:Apache License

private boolean markupMatch(Color color, PDPageContentStream contentStream, Match markingMatch)
        throws IOException {
    final List<PDRectangle> textBoundingBoxes = getTextBoundingBoxes(markingMatch.positions);

    if (textBoundingBoxes.size() > 0) {
        contentStream.appendRawCommands("/highlights gs\n");
        contentStream.setNonStrokingColor(color);
        for (PDRectangle textBoundingBox : textBoundingBoxes) {
            contentStream.fillRect(textBoundingBox.getLowerLeftX(), textBoundingBox.getLowerLeftY(),
                    Math.max(Math.abs(textBoundingBox.getUpperRightX() - textBoundingBox.getLowerLeftX()), 10),
                    10);/* ww w  . j  a v  a 2  s.co m*/
        }
        return true;
    }
    return false;
}

From source file:chiliad.parser.pdf.extractor.vectorgraphics.operator.Invoke.java

License:Apache License

/**
 * process : Do : Paint the specified XObject (section 4.7).
 *
 * @param operator The operator that is being executed.
 * @param arguments List//  w w  w  . j  ava 2s  . co  m
 * @throws IOException If there is an error invoking the sub object.
 */
@Override
public void process(PDFOperator operator, List<COSBase> arguments) throws IOException {
    VectorGraphicsExtractor extractor = (VectorGraphicsExtractor) context;

    PDPage page = extractor.getPage();
    COSName objectName = (COSName) arguments.get(0);
    Map<String, PDXObject> xobjects = extractor.getResources().getXObjects();
    PDXObject xobject = (PDXObject) xobjects.get(objectName.getName());
    if (xobject == null) {
        LOG.warn("Can't find the XObject for '" + objectName.getName() + "'");
    } else if (xobject instanceof PDXObjectImage) {
        PDXObjectImage image = (PDXObjectImage) xobject;
        try {
            if (image.getImageMask()) {
                // set the current non stroking colorstate, so that it can
                // be used to create a stencil masked image
                image.setStencilColor(extractor.getGraphicsState().getNonStrokingColor());
            }
            BufferedImage awtImage = image.getRGBImage();
            if (awtImage == null) {
                LOG.warn("getRGBImage returned NULL");
                return;//TODO PKOCH
            }
            int imageWidth = awtImage.getWidth();
            int imageHeight = awtImage.getHeight();
            double pageHeight = extractor.getPageSize().getHeight();

            LOG.debug("imageWidth: " + imageWidth + "\t\timageHeight: " + imageHeight);

            Matrix ctm = extractor.getGraphicsState().getCurrentTransformationMatrix();
            float yScaling = ctm.getYScale();
            float angle = (float) Math.acos(ctm.getValue(0, 0) / ctm.getXScale());
            if (ctm.getValue(0, 1) < 0 && ctm.getValue(1, 0) > 0) {
                angle = (-1) * angle;
            }
            ctm.setValue(2, 1, (float) (pageHeight - ctm.getYPosition() - Math.cos(angle) * yScaling));
            ctm.setValue(2, 0, (float) (ctm.getXPosition() - Math.sin(angle) * yScaling));
            // because of the moved 0,0-reference, we have to shear in the opposite direction
            ctm.setValue(0, 1, (-1) * ctm.getValue(0, 1));
            ctm.setValue(1, 0, (-1) * ctm.getValue(1, 0));
            AffineTransform ctmAT = ctm.createAffineTransform();
            ctmAT.scale(1f / imageWidth, 1f / imageHeight);
            extractor.drawImage(awtImage, ctmAT);
        } catch (Exception e) {
            LOG.error(e, e);
        }
    } else if (xobject instanceof PDXObjectForm) {
        // save the graphics state
        context.getGraphicsStack().push((PDGraphicsState) context.getGraphicsState().clone());

        PDXObjectForm form = (PDXObjectForm) xobject;
        COSStream formContentstream = form.getCOSStream();
        // find some optional resources, instead of using the current resources
        PDResources pdResources = form.getResources();
        // if there is an optional form matrix, we have to map the form space to the user space
        Matrix matrix = form.getMatrix();
        if (matrix != null) {
            Matrix xobjectCTM = matrix.multiply(context.getGraphicsState().getCurrentTransformationMatrix());
            context.getGraphicsState().setCurrentTransformationMatrix(xobjectCTM);
        }
        if (form.getBBox() != null) {
            PDGraphicsState graphicsState = context.getGraphicsState();
            PDRectangle bBox = form.getBBox();

            float x1 = bBox.getLowerLeftX();
            float y1 = bBox.getLowerLeftY();
            float x2 = bBox.getUpperRightX();
            float y2 = bBox.getUpperRightY();

            Point2D p0 = extractor.transformedPoint(x1, y1);
            Point2D p1 = extractor.transformedPoint(x2, y1);
            Point2D p2 = extractor.transformedPoint(x2, y2);
            Point2D p3 = extractor.transformedPoint(x1, y2);

            GeneralPath bboxPath = new GeneralPath();
            bboxPath.moveTo((float) p0.getX(), (float) p0.getY());
            bboxPath.lineTo((float) p1.getX(), (float) p1.getY());
            bboxPath.lineTo((float) p2.getX(), (float) p2.getY());
            bboxPath.lineTo((float) p3.getX(), (float) p3.getY());
            bboxPath.closePath();

            Area resultClippingArea = new Area(graphicsState.getCurrentClippingPath());
            Area newArea = new Area(bboxPath);
            resultClippingArea.intersect(newArea);

            graphicsState.setCurrentClippingPath(resultClippingArea);
        }
        getContext().processSubStream(page, pdResources, formContentstream);

        // restore the graphics state
        context.setGraphicsState((PDGraphicsState) context.getGraphicsStack().pop());
    }
}

From source file:chiliad.parser.pdf.extractor.vectorgraphics.VectorGraphicsExtractor.java

License:Apache License

@Override
public MPage extract(PDPage pageToExtract, MPage pageContent) {
    try {/*from  w  w  w  .j  a v  a  2s  .c  o  m*/
        if (pageToExtract.getContents() == null) {
            throw new ExtractorException("Contents is null.");
        }

        pageSize = pageToExtract.findMediaBox().createDimension();
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
                RenderingHints.VALUE_FRACTIONALMETRICS_ON);
        // initialize the used stroke with CAP_BUTT instead of CAP_SQUARE
        graphics.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
        // Only if there is some content, we have to process it.
        // Otherwise we are done here and we will produce an empty page

        PDResources resources = pageToExtract.findResources();
        processStream(pageToExtract, resources, pageToExtract.getContents().getStream());

        List<PDAnnotation> annotations = pageToExtract.getAnnotations();
        for (PDAnnotation annotation : annotations) {
            PDAnnotation annot = (PDAnnotation) annotation;
            PDRectangle rect = annot.getRectangle();
            String appearanceName = annot.getAppearanceStream();
            PDAppearanceDictionary appearDictionary = annot.getAppearance();
            if (appearDictionary != null) {
                if (appearanceName == null) {
                    appearanceName = "default";
                }
                Map<String, PDAppearanceStream> appearanceMap = appearDictionary.getNormalAppearance();
                if (appearanceMap != null) {
                    PDAppearanceStream appearance = (PDAppearanceStream) appearanceMap.get(appearanceName);
                    if (appearance != null) {
                        Point2D point = new Point2D.Float(rect.getLowerLeftX(), rect.getLowerLeftY());
                        Matrix matrix = appearance.getMatrix();
                        if (matrix != null) {
                            // transform the rectangle using the given matrix
                            AffineTransform at = matrix.createAffineTransform();
                            at.transform(point, point);
                        }
                        graphics.translate((int) point.getX(), -(int) point.getY());
                        processSubStream(pageToExtract, appearance.getResources(), appearance.getStream());
                        graphics.translate(-(int) point.getX(), (int) point.getY());
                    }
                }
            }
        }
        return handleResult(graphics, pageContent);
    } catch (IOException ex) {
        throw new ExtractorException("Failed to extract vector graphics.", ex);
    }
}

From source file:com.devnexus.ting.web.controller.PdfUtils.java

License:Apache License

public PdfUtils(float margin, String title) throws IOException {
    this.margin = margin;
    doc = new PDDocument();
    baseFont = PDType0Font.load(doc, PdfUtils.class.getResourceAsStream("/fonts/Arial.ttf"));
    headerFont = PDType1Font.HELVETICA_BOLD;
    subHeaderFont = PDType1Font.HELVETICA_BOLD;
    devnexusLogo = PDDocument.load(PdfUtils.class.getResourceAsStream("/fonts/devnexus-logo.pdf"));

    this.currentPage = new PDPage();
    this.pages.add(currentPage);
    this.doc.addPage(currentPage);

    final PDRectangle mediabox = currentPage.getMediaBox();
    this.width = mediabox.getWidth() - 2 * margin;

    float startX = mediabox.getLowerLeftX() + margin;
    float startY = mediabox.getUpperRightY() - margin;

    this.initialHeightCounter = startY;
    this.heightCounter = startY;

    LOGGER.info(String.format(//  w w w . j av  a2s .  c  o  m
            "Margin: %s, width: %s, startX: %s, "
                    + "startY: %s, heightCounter: %s, baseFontSize: %s, headerFontSize: %s",
            margin, width, startX, startY, heightCounter, baseFont, headerFont));

    contents = new PDPageContentStream(doc, currentPage);

    // Add Logo

    final LayerUtility layerUtility = new LayerUtility(doc);
    final PDFormXObject logo = layerUtility.importPageAsForm(devnexusLogo, 0);
    final AffineTransform affineTransform = AffineTransform.getTranslateInstance(100, startY - 50);
    affineTransform.scale(2d, 2d);
    layerUtility.appendFormAsLayer(currentPage, logo, affineTransform, "devnexus-logo");
    this.heightCounter -= 100;

    this.contents.beginText();

    this.contents.setFont(headerFont, headerFontSize);
    this.currentLeading = this.lineSpacing * baseFontSize;
    this.contents.setLeading(this.currentLeading);

    contents.newLineAtOffset(50, heightCounter);

    println(title);

    this.contents.setFont(baseFont, baseFontSize);
    this.currentLeading = this.lineSpacing * baseFontSize;
    this.contents.setLeading(this.currentLeading);

    println();

}