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

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

Introduction

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

Prototype

public float getLowerLeftY() 

Source Link

Document

This will get the lower left y coordinate.

Usage

From source file:airviewer.AnnotationGenerator.java

/**
 *
 * @param a/*from   w  w w .  j a  v a 2 s.co m*/
 * @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/*from   w  w w. jav a2  s. c o m*/
 * @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   ww  w .  ja va2  s . c  o 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: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   ww  w  .j  av a  2  s .c o  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);//from w  w  w . j a  va 2  s  . c  om
        }
        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//from w  w  w .  j a  v  a2s .  c  o 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  .ja  va2  s .c om*/
        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.formkiq.core.service.generator.pdfbox.PdfEditorServiceImpl.java

License:Apache License

/**
 * Find Header for {@link PdfFieldMatch}.
 * @param headers {@link List} of {@link PdfTextField}
 * @param pdfield {@link PdfFieldMatch}//  www  . ja v a 2 s .com
 * @param fontSize float
 * @return {@link PdfTextField}
 */
private PdfTextField findClosestHeader(final List<PdfTextField> headers, final PdfFieldMatch pdfield,
        final float fontSize) {

    PdfTextField match = null;
    PDRectangle rect = pdfield.getWidgets().get(0).getWidget().getRectangle();

    for (PdfTextField tf : headers) {

        if (fontSize == -1 || tf.getFontSize() >= fontSize) {
            if (tf.getRectangle().getLowerLeftY() > rect.getLowerLeftY()) {
                match = tf;
            } else {
                break;
            }
        }
    }

    return match;
}

From source file:com.formkiq.core.service.generator.pdfbox.PdfTextFieldTextGroupComparator.java

License:Apache License

@Override
public int compare(final PdfTextField o1, final PdfTextField o2) {

    PDRectangle r1 = o1.getRectangle();
    PDRectangle r2 = o2.getRectangle();/* w  ww  .j  a va2s  . c  o m*/

    int v1 = Math.round(r1.getLowerLeftX());
    int v2 = Math.round(r2.getLowerLeftX());
    int r = Integer.compare(v1, v2);

    if (r == 0) {
        r = Float.compare(o1.getFontSize(), o2.getFontSize());
    }

    if (r == 0) {
        r = o1.getFontName().compareTo(o2.getFontName());
    }

    // check if lower position if within Y location + font size away from
    // text above
    if (r == 0) {
        float diff0 = Math.abs(r1.getLowerLeftY() - r2.getUpperRightY());
        float diff1 = Math.abs(r1.getUpperRightY() - r2.getLowerLeftY());
        r = diff0 <= o2.getFontSize() || diff1 <= o2.getFontSize() ? 0 : -1;
    }

    return r;
}

From source file:com.formkiq.core.service.generator.pdfbox.PdfTextFieldTextXYComparator.java

License:Apache License

@Override
public int compare(final PdfTextField o1, final PdfTextField o2) {

    PDRectangle r1 = o1.getRectangle();
    PDRectangle r2 = o2.getRectangle();/* ww  w .  java2  s. c o m*/

    int v1 = Math.round(r1.getLowerLeftX());
    int v2 = Math.round(r2.getLowerLeftX());
    int r = Integer.compare(v1, v2);

    if (r == 0) {
        v1 = Math.round(r1.getLowerLeftY());
        v2 = Math.round(r2.getLowerLeftY());
        r = Integer.compare(v2, v1);
    }

    return r;
}