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

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

Introduction

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

Prototype

public PDRectangle getCropBox() 

Source Link

Document

A rectangle, expressed in default user space units, defining the visible region of default user space.

Usage

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

License:EUPL

/**
 * Sets the width of the table according to the layout of the document and
 * calculates the y position where the PDFPTable should be placed.
 *
 * @param pdfDataSource//from w w  w .  ja v a2 s  . co m
 *            The PDF document.
 * @param pdf_table
 *            The PDFPTable to be placed.
 * @return Returns the position where the PDFPTable should be placed.
 * @throws PdfAsException
 *             F.e.
 */
public static PositioningInstruction adjustSignatureTableandCalculatePosition(final PDDocument pdfDataSource,
        IPDFVisualObject pdf_table, TablePos pos, boolean legacy32, boolean legacy40) throws PdfAsException {

    PdfBoxUtils.checkPDFPermissions(pdfDataSource);
    // get pages of currentdocument

    int doc_pages = pdfDataSource.getNumberOfPages();
    int page = doc_pages;
    boolean make_new_page = pos.isNewPage();
    if (!(pos.isNewPage() || pos.isPauto())) {
        // we should posit signaturtable on this page

        page = pos.getPage();
        // System.out.println("XXXXPAGE="+page+" doc_pages="+doc_pages);
        if (page > doc_pages) {
            make_new_page = true;
            page = doc_pages;
            // throw new PDFDocumentException(227, "Page number is to big(="
            // + page+
            // ") cannot be parsed.");
        }
    }

    PDPage pdPage = (PDPage) pdfDataSource.getDocumentCatalog().getAllPages().get(page - 1);
    PDRectangle cropBox = pdPage.getCropBox();

    // fallback to MediaBox if Cropbox not available!

    if (cropBox == null) {
        cropBox = pdPage.findCropBox();
    }

    if (cropBox == null) {
        cropBox = pdPage.findMediaBox();
    }

    // getPagedimensions
    // Rectangle psize = reader.getPageSizeWithRotation(page);
    // int page_rotation = reader.getPageRotation(page);

    // Integer rotation = pdPage.getRotation();
    // int page_rotation = rotation.intValue();

    int rotation = pdPage.findRotation();

    logger.debug("Original CropBox: " + cropBox.toString());

    cropBox = rotateBox(cropBox, rotation);

    logger.debug("Rotated CropBox: " + cropBox.toString());

    float page_width = cropBox.getWidth();
    float page_height = cropBox.getHeight();

    logger.debug("CropBox width: " + page_width);
    logger.debug("CropBox heigth: " + page_height);

    // now we can calculate x-position
    float pre_pos_x = SIGNATURE_MARGIN_HORIZONTAL;
    if (!pos.isXauto()) {
        // we do have absolute x
        pre_pos_x = pos.getPosX();
    }
    // calculate width
    // center
    float pre_width = page_width - 2 * pre_pos_x;
    if (!pos.isWauto()) {
        // we do have absolute width
        pre_width = pos.getWidth();
        if (pos.isXauto()) { // center x
            pre_pos_x = (page_width - pre_width) / 2;
        }
    }
    final float pos_x = pre_pos_x;
    final float width = pre_width;
    // Signatur table dimensions are complete
    pdf_table.setWidth(width);
    pdf_table.fixWidth();
    // pdf_table.setTotalWidth(width);
    // pdf_table.setLockedWidth(true);

    final float table_height = pdf_table.getHeight();
    // now check pos_y
    float pos_y = pos.getPosY();

    // in case an absolute y position is already given OR
    // if the table is related to an invisible signature
    // there is no need for further calculations
    // (fixed adding new page in case of invisible signatures)
    if (!pos.isYauto() || table_height == 0) {
        // we do have y-position too --> all parameters but page ok
        if (make_new_page) {
            page++;
        }
        return new PositioningInstruction(make_new_page, page, pos_x, pos_y, pos.rotation);
    }
    // pos_y is auto
    if (make_new_page) {
        // ignore footer in new page
        page++;
        pos_y = page_height - SIGNATURE_MARGIN_VERTICAL;
        return new PositioningInstruction(make_new_page, page, pos_x, pos_y, pos.rotation);
    }
    // up to here no checks have to be made if Tablesize and Pagesize are
    // fit
    // Now we have to getfreespace in page and reguard footerline
    float footer_line = pos.getFooterLine();

    float pre_page_length = PDFUtilities.calculatePageLength(pdfDataSource, page - 1,
            page_height - footer_line, /* page_rotation, */
            legacy32, legacy40);

    if (pre_page_length == Float.NEGATIVE_INFINITY) {
        // we do have an empty page or nothing in area above footerline
        pre_page_length = page_height;
        // no text --> SIGNATURE_BORDER
        pos_y = page_height - SIGNATURE_MARGIN_VERTICAL;
        if (pos_y - footer_line <= table_height) {
            make_new_page = true;
            if (!pos.isPauto()) {
                // we have to correct pagenumber
                page = pdfDataSource.getNumberOfPages();
            }
            page++;
            // no text --> SIGNATURE_BORDER
            pos_y = page_height - SIGNATURE_MARGIN_VERTICAL;
        }
        return new PositioningInstruction(make_new_page, page, pos_x, pos_y, pos.rotation);
    }
    final float page_length = pre_page_length;
    // we do have text take SIGNATURE_MARGIN
    pos_y = page_height - page_length - SIGNATURE_MARGIN_VERTICAL;
    if (pos_y - footer_line <= table_height) {
        make_new_page = true;
        if (!pos.isPauto()) {
            // we have to correct pagenumber in case of absolute page and
            // not enough
            // space
            page = pdfDataSource.getNumberOfPages();
        }
        page++;
        // no text --> SIGNATURE_BORDER
        pos_y = page_height - SIGNATURE_MARGIN_VERTICAL;
    }
    return new PositioningInstruction(make_new_page, page, pos_x, pos_y, pos.rotation);

}

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

License:EUPL

@Override
protected void processOperator(Operator operator, List<COSBase> arguments) throws IOException {
    String operation = operator.getName();
    if (operation.equals("Do")) {
        COSName objectName = (COSName) arguments.get(0);
        PDXObject xobject = (PDXObject) getResources().getXObject(objectName);
        if (xobject instanceof PDImageXObject) {
            try {
                PDImageXObject image = (PDImageXObject) xobject;
                SignaturePlaceholderData data = checkImage(image);
                if (data != null) {
                    PDPage page = getCurrentPage();
                    Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
                    int pageRotation = page.getRotation();
                    pageRotation = pageRotation % 360;
                    double rotationInRadians = Math.toRadians(pageRotation);//(page.findRotation() * Math.PI) / 180;

                    AffineTransform rotation = new AffineTransform();
                    rotation.setToRotation(rotationInRadians);
                    AffineTransform rotationInverse = rotation.createInverse();
                    Matrix rotationInverseMatrix = new Matrix();
                    rotationInverseMatrix.setFromAffineTransform(rotationInverse);
                    Matrix rotationMatrix = new Matrix();
                    rotationMatrix.setFromAffineTransform(rotation);

                    Matrix unrotatedCTM = ctm.multiply(rotationInverseMatrix);

                    float x = unrotatedCTM.getXPosition();
                    float yPos = unrotatedCTM.getYPosition();
                    float yScale = unrotatedCTM.getScaleY();
                    float y = yPos + yScale;
                    float w = unrotatedCTM.getScaleX();
                    ;//from   w  ww  . jav a2s.c  o m

                    logger.debug("Page height: {}", page.getCropBox().getHeight());
                    logger.debug("Page width: {}", page.getCropBox().getWidth());

                    if (pageRotation == 90) {
                        y = page.getCropBox().getWidth() - (y * (-1));
                    } else if (pageRotation == 180) {
                        x = page.getCropBox().getWidth() + x;
                        y = page.getCropBox().getHeight() - (y * (-1));
                    } else if (pageRotation == 270) {
                        x = page.getCropBox().getHeight() + x;
                    }

                    String posString = "p:" + currentPage + ";x:" + x + ";y:" + y + ";w:" + w;

                    logger.debug("Found Placeholder at: {}", posString);
                    try {
                        data.setTablePos(new TablePos(posString));
                        data.setPlaceholderName(objectName.getName());
                        placeholders.add(data);
                    } catch (PdfAsException e) {
                        throw new IOException();
                    }
                }
            } catch (NoninvertibleTransformException e) {
                throw new IOException(e);
            }
        }
    } else {
        super.processOperator(operator, arguments);
    }
}

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

License:EUPL

/**
 * Sets the width of the table according to the layout of the document and
 * calculates the y position where the PDFPTable should be placed.
 *
 * @param pdfDataSource//  w  w  w. ja  va 2  s . c o m
 *            The PDF document.
 * @param pdf_table
 *            The PDFPTable to be placed.
 * @param settings 
 * @return Returns the position where the PDFPTable should be placed.
 * @throws PdfAsException
 *             F.e.
 */
public static PositioningInstruction adjustSignatureTableandCalculatePosition(final PDDocument pdfDataSource,
        IPDFVisualObject pdf_table, TablePos pos, ISettings settings) throws PdfAsException {

    PdfBoxUtils.checkPDFPermissions(pdfDataSource);
    // get pages of currentdocument

    int doc_pages = pdfDataSource.getNumberOfPages();
    int page = doc_pages;
    boolean make_new_page = pos.isNewPage();
    if (!(pos.isNewPage() || pos.isPauto())) {
        // we should posit signaturtable on this page

        page = pos.getPage();
        // System.out.println("XXXXPAGE="+page+" doc_pages="+doc_pages);
        if (page > doc_pages) {
            make_new_page = true;
            page = doc_pages;
            // throw new PDFDocumentException(227, "Page number is to big(="
            // + page+
            // ") cannot be parsed.");
        }
    }

    PDPage pdPage = pdfDataSource.getPage(page - 1);

    PDRectangle cropBox = pdPage.getCropBox();

    // fallback to MediaBox if Cropbox not available!

    if (cropBox == null) {
        cropBox = pdPage.getCropBox();
    }

    if (cropBox == null) {
        cropBox = pdPage.getCropBox();
    }

    // getPagedimensions
    // Rectangle psize = reader.getPageSizeWithRotation(page);
    // int page_rotation = reader.getPageRotation(page);

    // Integer rotation = pdPage.getRotation();
    // int page_rotation = rotation.intValue();

    int rotation = pdPage.getRotation();

    logger.debug("Original CropBox: " + cropBox.toString());

    cropBox = rotateBox(cropBox, rotation);

    logger.debug("Rotated CropBox: " + cropBox.toString());

    float page_width = cropBox.getWidth();
    float page_height = cropBox.getHeight();

    logger.debug("CropBox width: " + page_width);
    logger.debug("CropBox heigth: " + page_height);

    // now we can calculate x-position
    float pre_pos_x = SIGNATURE_MARGIN_HORIZONTAL;
    if (!pos.isXauto()) {
        // we do have absolute x
        pre_pos_x = pos.getPosX();
    }
    // calculate width
    // center
    float pre_width = page_width - 2 * pre_pos_x;
    if (!pos.isWauto()) {
        // we do have absolute width
        pre_width = pos.getWidth();
        if (pos.isXauto()) { // center x
            pre_pos_x = (page_width - pre_width) / 2;
        }
    }
    final float pos_x = pre_pos_x;
    final float width = pre_width;
    // Signatur table dimensions are complete
    pdf_table.setWidth(width);
    pdf_table.fixWidth();
    // pdf_table.setTotalWidth(width);
    // pdf_table.setLockedWidth(true);

    final float table_height = pdf_table.getHeight();
    // now check pos_y
    float pos_y = pos.getPosY();

    // in case an absolute y position is already given OR
    // if the table is related to an invisible signature
    // there is no need for further calculations
    // (fixed adding new page in case of invisible signatures)
    if (!pos.isYauto() || table_height == 0) {
        // we do have y-position too --> all parameters but page ok
        if (make_new_page) {
            page++;
        }
        return new PositioningInstruction(make_new_page, page, pos_x, pos_y, pos.rotation);
    }
    // pos_y is auto
    if (make_new_page) {
        // ignore footer in new page
        page++;
        pos_y = page_height - SIGNATURE_MARGIN_VERTICAL;
        return new PositioningInstruction(make_new_page, page, pos_x, pos_y, pos.rotation);
    }
    // up to here no checks have to be made if Tablesize and Pagesize are
    // fit
    // Now we have to getfreespace in page and reguard footerline
    float footer_line = pos.getFooterLine();

    //      float pre_page_length = PDFUtilities.calculatePageLength(pdfDataSource,
    //            page - 1, page_height - footer_line, /* page_rotation, */
    //            legacy32, legacy40);

    float pre_page_length = Float.NEGATIVE_INFINITY;
    try {
        pre_page_length = PDFUtilities.getMaxYPosition(pdfDataSource, page - 1, pdf_table,
                SIGNATURE_MARGIN_VERTICAL, footer_line, settings);
        //pre_page_length = PDFUtilities.getFreeTablePosition(pdfDataSource, page-1, pdf_table,SIGNATURE_MARGIN_VERTICAL);
    } catch (IOException e) {
        logger.warn("Could not determine page length, using -INFINITY");
    }

    if (pre_page_length == Float.NEGATIVE_INFINITY) {
        // we do have an empty page or nothing in area above footerline
        pre_page_length = page_height;
        // no text --> SIGNATURE_BORDER
        pos_y = page_height - SIGNATURE_MARGIN_VERTICAL;
        if (pos_y - footer_line <= table_height) {
            make_new_page = true;
            if (!pos.isPauto()) {
                // we have to correct pagenumber
                page = pdfDataSource.getNumberOfPages();
            }
            page++;
            // no text --> SIGNATURE_BORDER
            pos_y = page_height - SIGNATURE_MARGIN_VERTICAL;
        }
        return new PositioningInstruction(make_new_page, page, pos_x, pos_y, pos.rotation);
    }
    final float page_length = pre_page_length;
    // we do have text take SIGNATURE_MARGIN
    pos_y = page_height - page_length - SIGNATURE_MARGIN_VERTICAL;
    if (pos_y - footer_line <= table_height) {
        make_new_page = true;
        if (!pos.isPauto()) {
            // we have to correct pagenumber in case of absolute page and
            // not enough
            // space
            page = pdfDataSource.getNumberOfPages();
        }
        page++;
        // no text --> SIGNATURE_BORDER
        pos_y = page_height - SIGNATURE_MARGIN_VERTICAL;
    }
    return new PositioningInstruction(make_new_page, page, pos_x, pos_y, pos.rotation);

}

From source file:com.repeatability.pdf.PDFTextStreamEngine.java

License:Apache License

/**
 * This will initialise and process the contents of the stream.
 *
 * @param page the page to process//  w  w  w  .  j av a  2 s .c o m
 * @throws java.io.IOException if there is an error accessing the stream.
 */
@Override
public void processPage(PDPage page) throws IOException {
    this.pageRotation = page.getRotation();
    this.pageSize = page.getCropBox();

    if (pageSize.getLowerLeftX() == 0 && pageSize.getLowerLeftY() == 0) {
        translateMatrix = null;
    } else {
        // translation matrix for cropbox
        translateMatrix = Matrix.getTranslateInstance(-pageSize.getLowerLeftX(), -pageSize.getLowerLeftY());
    }
    super.processPage(page);
}

From source file:com.repeatability.pdf.PDFTextStripper.java

License:Apache License

private void fillBeadRectangles(PDPage page) {
    beadRectangles = new ArrayList<PDRectangle>();
    for (PDThreadBead bead : page.getThreadBeads()) {
        if (bead == null) {
            // can't skip, because of null entry handling in processTextPosition()
            beadRectangles.add(null);/*from  w ww  .  ja v  a  2 s .c o m*/
            continue;
        }

        PDRectangle rect = bead.getRectangle();

        // bead rectangle is in PDF coordinates (y=0 is bottom),
        // glyphs are in image coordinates (y=0 is top),
        // so we must flip
        PDRectangle mediaBox = page.getMediaBox();
        float upperRightY = mediaBox.getUpperRightY() - rect.getLowerLeftY();
        float lowerLeftY = mediaBox.getUpperRightY() - rect.getUpperRightY();
        rect.setLowerLeftY(lowerLeftY);
        rect.setUpperRightY(upperRightY);

        // adjust for cropbox
        PDRectangle cropBox = page.getCropBox();
        if (cropBox.getLowerLeftX() != 0 || cropBox.getLowerLeftY() != 0) {
            rect.setLowerLeftX(rect.getLowerLeftX() - cropBox.getLowerLeftX());
            rect.setLowerLeftY(rect.getLowerLeftY() - cropBox.getLowerLeftY());
            rect.setUpperRightX(rect.getUpperRightX() - cropBox.getLowerLeftX());
            rect.setUpperRightY(rect.getUpperRightY() - cropBox.getLowerLeftY());
        }

        beadRectangles.add(rect);
    }
}

From source file:com.tekstosense.segmenter.TextExtractor.java

License:Open Source License

@Override
protected void writeString(String string, List<TextPosition> pos) throws IOException {

    PDPage page = this.getCurrentPage();

    if (!pagesList.contains(page)) {
        currentPage = new Page(page.getCropBox(), ++pageCount);
        pagesList.add(page);/*  w ww. j a  v  a 2  s  .  c o m*/
    }

    if (!previousPages.contains(currentPage))
        previousPages.add(currentPage);

    PDGraphicsState gs = this.getGraphicsState();
    for (TextPosition tp : pos) {
        this.processTextPositionNew(tp, gs, string);
    }

    coalesceRows(currentPage, string);
    removeDuplicates(currentPage);

}

From source file:com.trollworks.gcs.pdfview.PdfPanel.java

License:Open Source License

private void markPageForLoading() {
    int numberOfPages = mPdf.getNumberOfPages();
    if (mPageIndex >= 0 && mPageIndex == numberOfPages) {
        mPageIndex = numberOfPages - 1;//w  w  w  .ja v  a  2s . c o  m
    }
    if (mPageIndex >= 0 && mPageIndex < numberOfPages) {
        PDPage page = mPdf.getPage(mPageIndex);
        PDRectangle cropBox = page.getCropBox();
        float scale = SCALES[mScaleIndex] * Toolkit.getDefaultToolkit().getScreenResolution();
        mWidth = (int) Math.ceil(cropBox.getWidth() / 72 * scale);
        mHeight = (int) Math.ceil(cropBox.getHeight() / 72 * scale);
        mImg = null;
        mNeedLoad = true;
        Dimension size = new Dimension(mWidth, mHeight);
        UIUtilities.setOnlySize(this, size);
        setSize(size);
        repaint();
        mIgnorePageChange = true;
        mOwner.updateStatus(mPageIndex, numberOfPages, SCALES[mScaleIndex]);
        mIgnorePageChange = false;
    }
}

From source file:com.yiyihealth.tools.test.DrawPrintTextLocations.java

License:Apache License

private void stripPage(int page) throws IOException {
    PDFRenderer pdfRenderer = new PDFRenderer(document);
    image = pdfRenderer.renderImage(page, SCALE);

    PDPage pdPage = document.getPage(page);
    PDRectangle cropBox = pdPage.getCropBox();

    // flip y-axis
    flipAT = new AffineTransform();
    flipAT.translate(0, pdPage.getBBox().getHeight());
    flipAT.scale(1, -1);//w  ww. jav a2s . c o  m

    // page may be rotated
    rotateAT = new AffineTransform();
    int rotation = pdPage.getRotation();
    if (rotation != 0) {
        PDRectangle mediaBox = pdPage.getMediaBox();
        switch (rotation) {
        case 90:
            rotateAT.translate(mediaBox.getHeight(), 0);
            break;
        case 270:
            rotateAT.translate(0, mediaBox.getWidth());
            break;
        case 180:
            rotateAT.translate(mediaBox.getWidth(), mediaBox.getHeight());
            break;
        default:
            break;
        }
        rotateAT.rotate(Math.toRadians(rotation));
    }

    g2d = image.createGraphics();
    g2d.setStroke(new BasicStroke(0.1f));
    g2d.scale(SCALE, SCALE);

    setStartPage(page + 1);
    setEndPage(page + 1);

    Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());
    writeText(document, dummy);

    // beads in green
    g2d.setStroke(new BasicStroke(0.4f));
    List<PDThreadBead> pageArticles = pdPage.getThreadBeads();
    for (PDThreadBead bead : pageArticles) {
        PDRectangle r = bead.getRectangle();
        GeneralPath p = r
                .transform(Matrix.getTranslateInstance(-cropBox.getLowerLeftX(), cropBox.getLowerLeftY()));

        Shape s = flipAT.createTransformedShape(p);
        s = rotateAT.createTransformedShape(s);
        g2d.setColor(Color.green);
        g2d.draw(s);
    }

    g2d.dispose();

    String imageFilename = filename;
    int pt = imageFilename.lastIndexOf('.');
    imageFilename = imageFilename.substring(0, pt) + "-marked-" + (page + 1) + ".png";
    ImageIO.write(image, "png", new File(imageFilename));
}

From source file:de.redsix.pdfcompare.CompareResult.java

License:Apache License

protected void addPageToDocument(final PDDocument document, final ImageWithDimension diffImage)
        throws IOException {
    PDPage page = new PDPage(new PDRectangle(diffImage.width, diffImage.height));
    document.addPage(page);/*from   www  . j  av a 2  s.com*/
    final PDImageXObject diffXImage = LosslessFactory.createFromImage(document, diffImage.bufferedImage);
    /*      final PDImageXObject actualXObject = LosslessFactory.createFromImage(document, actualImage.bufferedImage);
            final PDImageXObject expectedXObject = LosslessFactory.createFromImage(document, expectedImage.bufferedImage);
    */ try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
        int x = (int) page.getCropBox().getWidth();
        //System.out.println("X value "+x);
        int y = (int) page.getCropBox().getHeight();
        //System.out.println("Y value "+y);
        contentStream.drawImage(diffXImage, 0, 0, x, y);
        /*         contentStream.setLineWidth(0.5F); 
                     contentStream.moveTo(x, 2);
                    contentStream.lineTo(x, y);
                     contentStream.drawImage(expectedXObject, x+2, 0, x, y);
                 contentStream.moveTo(x+x, 2);
                   contentStream.lineTo(x+x, y+y);
                   contentStream.drawImage(expectedXObject, x+x+2, 0, x, y);
                    contentStream.stroke();*/
    }
}

From source file:de.redsix.pdfcompare.CompareResult.java

License:Apache License

protected void addPageToDocument(final PDDocument document, final ImageWithDimension actualImage,
        final ImageWithDimension expectedImage) throws IOException {
    PDPage page = new PDPage(new PDRectangle(actualImage.width, actualImage.height));
    document.addPage(page);/*www .  j a  va  2s.c  o m*/
    //final PDImageXObject diffXImage = LosslessFactory.createFromImage(document, diffImage.bufferedImage);
    final PDImageXObject actualXObject = LosslessFactory.createFromImage(document, actualImage.bufferedImage);
    final PDImageXObject expectedXObject = LosslessFactory.createFromImage(document,
            expectedImage.bufferedImage);
    try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
        int x = (int) page.getCropBox().getWidth() / 2;
        //System.out.println("X value "+x);
        int y = (int) page.getCropBox().getHeight();
        //System.out.println("Y value "+y);
        contentStream.drawImage(actualXObject, 0, 0, x, y);
        contentStream.setLineWidth(0.5F);
        contentStream.moveTo(x, 2);
        contentStream.lineTo(x, y);
        contentStream.drawImage(expectedXObject, x + 2, 0, x, y);
        /*contentStream.moveTo(x+x, 2);
        contentStream.lineTo(x+x, y+y);
        contentStream.drawImage(expectedXObject, x+x+2, 0, x, y);*/
        contentStream.stroke();
    }
}