Java Code Examples for org.apache.pdfbox.pdmodel.PDPage#getCropBox()

The following examples show how to use org.apache.pdfbox.pdmodel.PDPage#getCropBox() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RotatePageContent.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/40611736/rotate-pdf-around-its-center-using-pdfbox-in-java">
 * Rotate PDF around its center using PDFBox in java
 * </a>
 * <p>
 * This test shows how to rotate the page content and then set the crop
 * box and media box to the bounding rectangle of the rotated page area.
 * </p>
 */
@Test
public void testRotateExpandBox() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("IRJET_Copy_Right_form.pdf")  )
    {
        PDDocument document = Loader.loadPDF(resource);
        PDPage page = document.getDocumentCatalog().getPages().get(0);
        PDPageContentStream cs = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.PREPEND, false, false);
        Matrix matrix = Matrix.getRotateInstance(Math.toRadians(45), 0, 0);
        cs.transform(matrix);
        cs.close();

        PDRectangle cropBox = page.getCropBox();
        Rectangle rectangle = cropBox.transform(matrix).getBounds();
        PDRectangle newBox = new PDRectangle((float)rectangle.getX(), (float)rectangle.getY(), (float)rectangle.getWidth(), (float)rectangle.getHeight());
        page.setCropBox(newBox);
        page.setMediaBox(newBox);

        document.save(new File(RESULT_FOLDER, "IRJET_Copy_Right_form-rotated-expand-box.pdf"));
    }
}
 
Example 2
Source File: PdfPanel.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
private void markPageForLoading() {
    int numberOfPages = mPdf.getNumberOfPages();
    if (mPageIndex >= 0 && mPageIndex == numberOfPages) {
        mPageIndex = numberOfPages - 1;
    }
    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;
    }
}
 
Example 3
Source File: RotatePageContent.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/40611736/rotate-pdf-around-its-center-using-pdfbox-in-java">
 * Rotate PDF around its center using PDFBox in java
 * </a>
 * <p>
 * This test shows how to rotate the page content and then move its crop box and
 * media box accordingly to make it appear as if the content was rotated around
 * the center of the crop box.
 * </p>
 */
@Test
public void testRotateMoveBox() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("IRJET_Copy_Right_form.pdf")  )
    {
        PDDocument document = Loader.loadPDF(resource);
        PDPage page = document.getDocumentCatalog().getPages().get(0);
        PDPageContentStream cs = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.PREPEND, false, false);
        Matrix matrix = Matrix.getRotateInstance(Math.toRadians(45), 0, 0);
        cs.transform(matrix);
        cs.close();

        PDRectangle cropBox = page.getCropBox();
        float cx = (cropBox.getLowerLeftX() + cropBox.getUpperRightX()) / 2;
        float cy = (cropBox.getLowerLeftY() + cropBox.getUpperRightY()) / 2;
        Point2D.Float newC = matrix.transformPoint(cx, cy);
        float tx = (float)newC.getX() - cx;
        float ty = (float)newC.getY() - cy;
        page.setCropBox(new PDRectangle(cropBox.getLowerLeftX() + tx, cropBox.getLowerLeftY() + ty, cropBox.getWidth(), cropBox.getHeight()));
        PDRectangle mediaBox = page.getMediaBox();
        page.setMediaBox(new PDRectangle(mediaBox.getLowerLeftX() + tx, mediaBox.getLowerLeftY() + ty, mediaBox.getWidth(), mediaBox.getHeight()));

        document.save(new File(RESULT_FOLDER, "IRJET_Copy_Right_form-rotated-move-box.pdf"));
    }
}
 
Example 4
Source File: RotatePageContent.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/40611736/rotate-pdf-around-its-center-using-pdfbox-in-java">
 * Rotate PDF around its center using PDFBox in java
 * </a>
 * <p>
 * This test shows how to rotate the page content around the center of its crop box
 * and then crop it to make all previously visible content fit.
 * </p>
 */
@Test
public void testRotateCenterScale() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("IRJET_Copy_Right_form.pdf")  )
    {
        PDDocument document = Loader.loadPDF(resource);
        PDPage page = document.getDocumentCatalog().getPages().get(0);
        PDPageContentStream cs = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.PREPEND, false, false);

        Matrix matrix = Matrix.getRotateInstance(Math.toRadians(45), 0, 0);
        PDRectangle cropBox = page.getCropBox();
        float tx = (cropBox.getLowerLeftX() + cropBox.getUpperRightX()) / 2;
        float ty = (cropBox.getLowerLeftY() + cropBox.getUpperRightY()) / 2;

        Rectangle rectangle = cropBox.transform(matrix).getBounds();
        float scale = Math.min(cropBox.getWidth() / (float)rectangle.getWidth(), cropBox.getHeight() / (float)rectangle.getHeight());

        cs.transform(Matrix.getTranslateInstance(tx, ty));
        cs.transform(matrix);
        cs.transform(Matrix.getScaleInstance(scale, scale));
        cs.transform(Matrix.getTranslateInstance(-tx, -ty));
        cs.close();
        document.save(new File(RESULT_FOLDER, "IRJET_Copy_Right_form-rotated-center-scale.pdf"));
    }
}
 
Example 5
Source File: PDFRenderer.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
private void transform(Graphics2D graphics, PDPage page, float scaleX, float scaleY)
{
    graphics.scale(scaleX, scaleY);

    // TODO should we be passing the scale to PageDrawer rather than messing with Graphics?
    int rotationAngle = page.getRotation();
    PDRectangle cropBox = page.getCropBox();

    if (rotationAngle != 0)
    {
        float translateX = 0;
        float translateY = 0;
        switch (rotationAngle)
        {
            case 90:
                translateX = cropBox.getHeight();
                break;
            case 270:
                translateY = cropBox.getWidth();
                break;
            case 180:
                translateX = cropBox.getWidth();
                translateY = cropBox.getHeight();
                break;
            default:
                break;
        }
        graphics.translate(translateX, translateY);
        graphics.rotate(Math.toRadians(rotationAngle));
    }
}
 
Example 6
Source File: RotatePageContent.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/40611736/rotate-pdf-around-its-center-using-pdfbox-in-java">
 * Rotate PDF around its center using PDFBox in java
 * </a>
 * <p>
 * This test shows how to rotate the page content around the center of its crop box.
 * </p>
 */
@Test
public void testRotateCenter() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("IRJET_Copy_Right_form.pdf")  )
    {
        PDDocument document = Loader.loadPDF(resource);
        PDPage page = document.getDocumentCatalog().getPages().get(0);
        PDPageContentStream cs = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.PREPEND, false, false); 
        PDRectangle cropBox = page.getCropBox();
        float tx = (cropBox.getLowerLeftX() + cropBox.getUpperRightX()) / 2;
        float ty = (cropBox.getLowerLeftY() + cropBox.getUpperRightY()) / 2;
        cs.transform(Matrix.getTranslateInstance(tx, ty));
        cs.transform(Matrix.getRotateInstance(Math.toRadians(45), 0, 0));
        cs.transform(Matrix.getTranslateInstance(-tx, -ty));
        cs.close();
        document.save(new File(RESULT_FOLDER, "IRJET_Copy_Right_form-rotated-center.pdf"));
    }
}
 
Example 7
Source File: LegacyPDFStreamEngine.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * This will initialize and process the contents of the stream.
 *
 * @param page the page to process
 * @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);
}
 
Example 8
Source File: LayerUtility.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Places the given form over the existing content of the indicated page (like an overlay).
 * The form is enveloped in a marked content section to indicate that it's part of an
 * optional content group (OCG), here used as a layer. This optional group is returned and
 * can be enabled and disabled through methods on {@link PDOptionalContentProperties}.
 * <p>
 * You may want to call {@link #wrapInSaveRestore(PDPage) wrapInSaveRestore(PDPage)} before calling this method to make
 * sure that the graphics state is reset.
 *
 * @param targetPage the target page
 * @param form the form to place
 * @param transform the transformation matrix that controls the placement of your form. You'll
 * need this if your page has a crop box different than the media box, or if these have negative
 * coordinates, or if you want to scale or adjust your form.
 * @param layerName the name for the layer/OCG to produce
 * @return the optional content group that was generated for the form usage
 * @throws IOException if an I/O error occurs
 */
public PDOptionalContentGroup appendFormAsLayer(PDPage targetPage,
        PDFormXObject form, AffineTransform transform,
        String layerName) throws IOException
{
    PDDocumentCatalog catalog = targetDoc.getDocumentCatalog();
    PDOptionalContentProperties ocprops = catalog.getOCProperties();
    if (ocprops == null)
    {
        ocprops = new PDOptionalContentProperties();
        catalog.setOCProperties(ocprops);
    }
    if (ocprops.hasGroup(layerName))
    {
        throw new IllegalArgumentException("Optional group (layer) already exists: " + layerName);
    }

    PDRectangle cropBox = targetPage.getCropBox();
    if ((cropBox.getLowerLeftX() < 0 || cropBox.getLowerLeftY() < 0) && transform.isIdentity())
    {
        // PDFBOX-4044 
        LOG.warn("Negative cropBox " + cropBox + 
                 " and identity transform may make your form invisible");
    }

    PDOptionalContentGroup layer = new PDOptionalContentGroup(layerName);
    ocprops.addGroup(layer);

    PDPageContentStream contentStream = new PDPageContentStream(
            targetDoc, targetPage, AppendMode.APPEND, !DEBUG);
    contentStream.beginMarkedContent(COSName.OC, layer);
    contentStream.saveGraphicsState();
    contentStream.transform(new Matrix(transform));
    contentStream.drawForm(form);
    contentStream.restoreGraphicsState();
    contentStream.endMarkedContent();
    contentStream.close();

    return layer;
}
 
Example 9
Source File: AddImage.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/50988007/clip-an-image-with-pdfbox">
 * Clip an image with PDFBOX
 * </a>
 * <p>
 * This test demonstrates how to clip an image and frame the clipping area.
 * </p>
 */
@SuppressWarnings("deprecation")
@Test
public void testImageAddClipped() throws IOException {
    try (   InputStream imageResource = getClass().getResourceAsStream("Willi-1.jpg")   )
    {
        PDDocument doc = new PDDocument();
        PDImageXObject pdImage = PDImageXObject.createFromByteArray(doc, ByteStreams.toByteArray(imageResource), "Willi");

        int w = pdImage.getWidth();
        int h = pdImage.getHeight();

        PDPage page = new PDPage();
        doc.addPage(page);
        PDRectangle cropBox = page.getCropBox();
        PDPageContentStream contentStream = new PDPageContentStream(doc, page);

        contentStream.setStrokingColor(25, 200, 25);
        contentStream.setLineWidth(4);
        contentStream.moveTo(cropBox.getLowerLeftX(), cropBox.getLowerLeftY() + h/2);
        contentStream.lineTo(cropBox.getLowerLeftX() + w/3, cropBox.getLowerLeftY() + 2*h/3);
        contentStream.lineTo(cropBox.getLowerLeftX() + w, cropBox.getLowerLeftY() + h/2);
        contentStream.lineTo(cropBox.getLowerLeftX() + w/3, cropBox.getLowerLeftY() + h/3);
        contentStream.closePath();
        //contentStream.clip();
        contentStream.appendRawCommands("W ");
        contentStream.stroke();

        contentStream.drawImage(pdImage, cropBox.getLowerLeftX(), cropBox.getLowerLeftY(), w, h);

        contentStream.close();

        doc.save(new File(RESULT_FOLDER, "image-clipped.pdf"));
        doc.close();
    }
}
 
Example 10
Source File: PDFVisibleTextStripper.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
@Override
public void processPage(PDPage page) throws IOException {
    PDRectangle pageSize = page.getCropBox();

    lowerLeftX = pageSize.getLowerLeftX();
    lowerLeftY = pageSize.getLowerLeftY();

    super.processPage(page);
}
 
Example 11
Source File: PdfToTextInfoConverter.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
@Override
public void processPage(PDPage page) throws IOException {
    PDRectangle pageSize = page.getCropBox();

    lowerLeftX = pageSize.getLowerLeftX();
    lowerLeftY = pageSize.getLowerLeftY();

    super.processPage(page);
}
 
Example 12
Source File: PdfDenseMergeTool.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
void merge(PDDocument sourceDoc, PDPage page) throws IOException
{
    PDRectangle pageSizeToImport = page.getCropBox();
    BoundingBoxFinder boundingBoxFinder = new BoundingBoxFinder(page);
    boundingBoxFinder.processPage(page);
    Rectangle2D boundingBoxToImport = boundingBoxFinder.getBoundingBox();
    double heightToImport = boundingBoxToImport.getHeight();
    float maxHeight = pageSize.getHeight() - topMargin - bottomMargin;
    if (heightToImport > maxHeight)
    {
        throw new IllegalArgumentException(String.format("Page %s content too large; height: %s, limit: %s.", page, heightToImport, maxHeight));
    }

    if (gap + heightToImport > yPosition - (pageSize.getLowerLeftY() + bottomMargin))
    {
        newPage();
    }
    yPosition -= heightToImport + gap;

    LayerUtility layerUtility = new LayerUtility(document);
    PDFormXObject form = layerUtility.importPageAsForm(sourceDoc, page);

    currentContents.saveGraphicsState();
    Matrix matrix = Matrix.getTranslateInstance(0, (float)(yPosition - (boundingBoxToImport.getMinY() - pageSizeToImport.getLowerLeftY())));
    currentContents.transform(matrix);
    currentContents.drawForm(form);
    currentContents.restoreGraphicsState();
}
 
Example 13
Source File: PDFTextStripper.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
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);
            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);
    }
}
 
Example 14
Source File: PDFPrintable.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * This will find the CropBox with rotation applied, for this page by looking up the hierarchy
 * until it finds them.
 *
 * @return The CropBox at this level in the hierarchy.
 */
static PDRectangle getRotatedCropBox(PDPage page)
{
    PDRectangle cropBox = page.getCropBox();
    int rotationAngle = page.getRotation();
    if (rotationAngle == 90 || rotationAngle == 270)
    {
        return new PDRectangle(cropBox.getLowerLeftY(), cropBox.getLowerLeftX(),
                               cropBox.getHeight(), cropBox.getWidth());
    }
    else
    {
        return cropBox;
    }
}
 
Example 15
Source File: PdfVeryDenseMergeTool.java    From testarea-pdfbox2 with Apache License 2.0 4 votes vote down vote up
void merge(PDDocument sourceDoc, PDPage page) throws IOException
{
    PDRectangle pageSizeToImport = page.getCropBox();

    PageVerticalAnalyzer analyzer = new PageVerticalAnalyzer(page);
    analyzer.processPage(page);
    List<Float> verticalFlips = analyzer.getVerticalFlips();
    if (verticalFlips.size() < 2)
        return;

    LayerUtility layerUtility = new LayerUtility(document);
    PDFormXObject form = layerUtility.importPageAsForm(sourceDoc, page);

    int startFlip = verticalFlips.size() - 1;
    boolean first = true;
    while (startFlip > 0)
    {
        if (!first)
            newPage();

        float freeSpace = yPosition - pageSize.getLowerLeftY() - bottomMargin;
        int endFlip = startFlip + 1;
        while ((endFlip > 1) && (verticalFlips.get(startFlip) - verticalFlips.get(endFlip - 2) < freeSpace))
            endFlip -=2;
        if (endFlip < startFlip)
        {
            float height = verticalFlips.get(startFlip) - verticalFlips.get(endFlip);

            currentContents.saveGraphicsState();
            currentContents.addRect(0, yPosition - height, pageSizeToImport.getWidth(), height);
            currentContents.clip();
            Matrix matrix = Matrix.getTranslateInstance(0, (float)(yPosition - (verticalFlips.get(startFlip) - pageSizeToImport.getLowerLeftY())));
            currentContents.transform(matrix);
            currentContents.drawForm(form);
            currentContents.restoreGraphicsState();

            yPosition -= height + gap;
            startFlip = endFlip - 1;
        }
        else if (!first) 
            throw new IllegalArgumentException(String.format("Page %s content sections too large.", page));
        first = false;
    }
}
 
Example 16
Source File: PDFExtractor.java    From inception with Apache License 2.0 4 votes vote down vote up
public PDFExtractor(PDPage page, int pageIndex, Writer output) throws IOException
{
    super(page);
    this.pageIndex = pageIndex;
    this.output = output;
    this.writeGlyphCoords = true;

    String path = "org/apache/pdfbox/resources/glyphlist/additional.txt";
    InputStream input = GlyphList.class.getClassLoader().getResourceAsStream(path);
    this.glyphList = new GlyphList(GlyphList.getAdobeGlyphList(), input);

    this.pageRotation = page.getRotation();
    this.pageSize = page.getCropBox();
    if (this.pageSize.getLowerLeftX() == 0.0F && this.pageSize.getLowerLeftY() == 0.0F) {
        this.translateMatrix = null;
    }
    else {
        this.translateMatrix = Matrix.getTranslateInstance(-this.pageSize.getLowerLeftX(),
            -this.pageSize.getLowerLeftY());
    }

    // taken from DrawPrintTextLocations for setting flipAT, rotateAT and transAT
    PDRectangle cropBox = page.getCropBox();
    // flip y-axis
    flipAT = new AffineTransform();
    flipAT.translate(0, page.getBBox().getHeight());
    flipAT.scale(1, -1);

    // page may be rotated
    rotateAT = new AffineTransform();
    int rotation = page.getRotation();
    if (rotation != 0) {
        PDRectangle mediaBox = page.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));
    }
    // cropbox
    transAT = AffineTransform
        .getTranslateInstance(-cropBox.getLowerLeftX(), cropBox.getLowerLeftY());
}
 
Example 17
Source File: LayerUtility.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Imports a page from some PDF file as a Form XObject so it can be placed on another page
 * in the target document.
 * <p>
 * You may want to call {@link #wrapInSaveRestore(PDPage) wrapInSaveRestore(PDPage)} before invoking the Form XObject to
 * make sure that the graphics state is reset.
 * 
 * @param sourceDoc the source PDF document that contains the page to be copied
 * @param page the page in the source PDF document to be copied
 * @return a Form XObject containing the original page's content
 * @throws IOException if an I/O error occurs
 */
public PDFormXObject importPageAsForm(PDDocument sourceDoc, PDPage page) throws IOException
{
    importOcProperties(sourceDoc);

    PDStream newStream = new PDStream(targetDoc, page.getContents(), COSName.FLATE_DECODE);
    PDFormXObject form = new PDFormXObject(newStream);

    //Copy resources
    PDResources pageRes = page.getResources();
    PDResources formRes = new PDResources();
    cloner.cloneMerge(pageRes, formRes);
    form.setResources(formRes);

    //Transfer some values from page to form
    transferDict(page.getCOSObject(), form.getCOSObject(), PAGE_TO_FORM_FILTER, true);

    Matrix matrix = form.getMatrix();
    AffineTransform at = matrix.createAffineTransform();
    PDRectangle mediaBox = page.getMediaBox();
    PDRectangle cropBox = page.getCropBox();
    PDRectangle viewBox = (cropBox != null ? cropBox : mediaBox);

    //Handle the /Rotation entry on the page dict
    int rotation = page.getRotation();

    //Transform to FOP's user space
    //at.scale(1 / viewBox.getWidth(), 1 / viewBox.getHeight());
    at.translate(mediaBox.getLowerLeftX() - viewBox.getLowerLeftX(),
            mediaBox.getLowerLeftY() - viewBox.getLowerLeftY());
    switch (rotation)
    {
    case 90:
        at.scale(viewBox.getWidth() / viewBox.getHeight(), viewBox.getHeight() / viewBox.getWidth());
        at.translate(0, viewBox.getWidth());
        at.rotate(-Math.PI / 2.0);
        break;
    case 180:
        at.translate(viewBox.getWidth(), viewBox.getHeight());
        at.rotate(-Math.PI);
        break;
    case 270:
        at.scale(viewBox.getWidth() / viewBox.getHeight(), viewBox.getHeight() / viewBox.getWidth());
        at.translate(viewBox.getHeight(), 0);
        at.rotate(-Math.PI * 1.5);
        break;
    default:
        //no additional transformations necessary
    }
    //Compensate for Crop Boxes not starting at 0,0
    at.translate(-viewBox.getLowerLeftX(), -viewBox.getLowerLeftY());
    if (!at.isIdentity())
    {
        form.setMatrix(at);
    }

    BoundingBox bbox = new BoundingBox();
    bbox.setLowerLeftX(viewBox.getLowerLeftX());
    bbox.setLowerLeftY(viewBox.getLowerLeftY());
    bbox.setUpperRightX(viewBox.getUpperRightX());
    bbox.setUpperRightY(viewBox.getUpperRightY());
    form.setBBox(new PDRectangle(bbox));

    return form;
}
 
Example 18
Source File: PDFRenderer.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Renders a given page to an AWT Graphics2D instance.
 * <p>
 * Known problems:
 * <ul>
 * <li>rendering of PDF files with transparencies is not supported on Ubuntu, see
 * <a href="https://issues.apache.org/jira/browse/PDFBOX-4581">PDFBOX-4581</a> and
 * <a href="https://bugs.openjdk.java.net/browse/JDK-6689349">JDK-6689349</a>. Rendering will
 * not abort, but the pages will be rendered incorrectly.</li>
 * <li>Clipping the Graphics2D will not work properly, see
 * <a href="https://issues.apache.org/jira/browse/PDFBOX-4583">PDFBOX-4583</a>.</li>
 * </ul>
 * If you encounter these problems, then you should render into an image by using the
 * {@link #renderImage(int) renderImage} methods.
 * 
 * @param pageIndex the zero-based index of the page to be converted
 * @param graphics the Graphics2D on which to draw the page
 * @param scaleX the scale to draw the page at for the x-axis, where 1 = 72 DPI
 * @param scaleY the scale to draw the page at for the y-axis, where 1 = 72 DPI
 * @param destination controlling visibility of optional content groups
 * @throws IOException if the PDF cannot be read
 */
public void renderPageToGraphics(int pageIndex, Graphics2D graphics, float scaleX, float scaleY, RenderDestination destination)
        throws IOException
{
    PDPage page = document.getPage(pageIndex);
    // TODO need width/wight calculations? should these be in PageDrawer?

    transform(graphics, page, scaleX, scaleY);

    PDRectangle cropBox = page.getCropBox();
    graphics.clearRect(0, 0, (int) cropBox.getWidth(), (int) cropBox.getHeight());

    // the end-user may provide a custom PageDrawer
    RenderingHints actualRenderingHints =
            renderingHints == null ? createDefaultRenderingHints(graphics) : renderingHints;
    PageDrawerParameters parameters = new PageDrawerParameters(this, page, subsamplingAllowed,
                                                               destination, actualRenderingHints);
    PageDrawer drawer = createPageDrawer(parameters);
    drawer.drawPage(graphics, cropBox);
}
 
Example 19
Source File: PdfInformation.java    From MyBox with Apache License 2.0 4 votes vote down vote up
public void loadInformation() {
    try {
        if (doc == null) {
            return;
        }

        PDDocumentInformation docInfo = doc.getDocumentInformation();
        if (docInfo.getCreationDate() != null) {
            createTime = docInfo.getCreationDate().getTimeInMillis();
        }
        if (docInfo.getModificationDate() != null) {
            modifyTime = docInfo.getModificationDate().getTimeInMillis();
        }
        creator = docInfo.getCreator();
        producer = docInfo.getProducer();
        title = docInfo.getTitle();
        subject = docInfo.getSubject();
        author = docInfo.getAuthor();
        numberOfPages = doc.getNumberOfPages();
        keywords = docInfo.getKeywords();
        version = doc.getVersion();
        access = doc.getCurrentAccessPermission();

        PDPage page = doc.getPage(0);
        String size = "";
        PDRectangle box = page.getMediaBox();
        if (box != null) {
            size += "MediaBox: " + PdfTools.pixels2mm(box.getWidth()) + "mm * "
                    + PdfTools.pixels2mm(box.getHeight()) + "mm";
        }
        box = page.getTrimBox();
        if (box != null) {
            size += "  TrimBox: " + PdfTools.pixels2mm(box.getWidth()) + "mm * "
                    + PdfTools.pixels2mm(box.getHeight()) + "mm";
        }
        firstPageSize = size;
        size = "";
        box = page.getCropBox();
        if (box != null) {
            size += "CropBox: " + +PdfTools.pixels2mm(box.getWidth()) + "mm * "
                    + PdfTools.pixels2mm(box.getHeight()) + "mm";
        }
        box = page.getBleedBox();
        if (box != null) {
            size += "  BleedBox: " + +PdfTools.pixels2mm(box.getWidth()) + "mm * "
                    + PdfTools.pixels2mm(box.getHeight()) + "mm";
        }
        firstPageSize2 = size;
        outline = doc.getDocumentCatalog().getDocumentOutline();
        infoLoaded = true;
    } catch (Exception e) {
        logger.error(e.toString());
    }
}