Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PDFBox, how to change the origin (0,0) point of a PDRectangle object?

Tags:

java

pdf

pdfbox

The Situation:
In PDFBox, PDRectangle objects' default origin (0,0) seems to be the lower-left corner of a page.

For example, the following code gives you a square at the lower-left corner of a page, and each side is 100 units long.

PDRectangle rectangle = new PDRectangle(0, 0, 100, 100);

The Question:
Is it possible to change the origin to the UPPER-LEFT corner, so that, for example, the code above will give you the same square at the UPPER-LEFT corner of the page instead?

The reason I ask:
I was using PDFTextStripper to get the coordinates of the text (by using the getX() and getY() methods of the extracted TextPosition objects). The coordinates retrieved from TextPosition objects seem have an origin (0,0) at the UPPER-LEFT CORNER. I want the coordinates of my PDRectangle objects have the same origin as the coordinates of my TextPosition objects.

I have tried to adjust the Y-coordinates of my PDRectangle by "page height minus Y-coordinate". This gives me the desired result, but it's not elegant. I want an elegant solution.

Note: Someone has asked a similar question. The answer is what I tried, which is not the most elegant. how to change the coordiantes of a text in a pdf page from lower left to upper left

like image 587
Brian Avatar asked Jan 22 '15 16:01

Brian


People also ask

What is PDRectangle?

public class PDRectangle extends Object implements COSObjectable. A rectangle in a PDF document.


2 Answers

You can change coordinate systems somewhat but most likely things won't get more elegant in the end.

To start with...

First of all let's clear up some misconception:

You assume

In PDFBox, PDRectangle objects' default origin (0,0) seems to be the lower-left corner of a page.

This is not true for all cases, merely often.

The area containing the displayed page area (on paper or on screen) usually is defined by the CropBox entry of the page in question:

CropBox rectangle (Optional; inheritable) A rectangle, expressed in default user space units, that shall define the visible region of default user space. When the page is displayed or printed, its contents shall be clipped (cropped) to this rectangle and then shall be imposed on the output medium in some implementation-defined manner.

... The positive x axis extends horizontally to the right and the positive y axis vertically upward, as in standard mathematical practice (subject to alteration by the Rotate entry in the page dictionary).

... In PostScript, the origin of default user space always corresponds to the lower-left corner of the output medium. While this convention is common in PDF documents as well, it is not required; the page dictionary’s CropBox entry can specify any rectangle of default user space to be made visible on the medium.

Thus, the origin (0,0) can literally be anywhere, it may be at the lower left, at the upper left, in the middle of the page or even far outside the displayed page area.

And by means of the Rotate entry, that area can even be rotated (by 90°, 180°, or 270°).

Putting the origin (as you seem to have observed) in the lower left merely is done by convention.

Furthermore you seem to think that the coordinate system is constant. This also is not the case, there are operations by which you can transform the user space coordinate system drastically, you can translate, rotate, mirror, skew, and/or scale it!

Thus, even if at the beginning the coordinate system is the usual one, origin in lower left, x-axis going right, y-axis going up, it may be changed to something weird some way into the page content description. Drawing your rectangle new PDRectangle(0, 0, 100, 100) there might produce some rhomboid form just right of the page center.

What you can do...

As you see coordinates in PDF user space are a very dynamic matter. what you can do to tame the situation, depends on the context you use your rectangle in.

Unfortunately you were quite vague in the description of what you do. Thus, this will be somewhat vague, too.

Coordinates in the page content

If you want to draw some rectangle on an existing page, you first of all need a page content stream to write to, i.e. a PDPageContentStream instance, and it should be prepared in a manner guaranteeing that the original user space coordinate system has not been disturbed. You get such an instance by using the constructor with three boolean arguments setting all them to true:

PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true, true);

Then you can apply a transformation to the coordinate system. You want the top left to be the origin and the y-value increasing downwards. If the crop box of the page tells you the top left has coordinates (xtl, ytl), therefore, you apply

contentStream.concatenate2CTM(new AffineTransform(1, 0, 0, -1, xtl, ytl));

and from here on you have a coordinate system you wanted, origin top left and y coordinates mirrored.

Be aware of one thing, though: If you are going to draw text, too, not only the text insertion point y coordinate is mirrored but also the text itself unless you counteract that by adding an also mirroring text matrix! If you want to add much text, therefore, this may not be as elegant as you want.

Coordinates for annotations

If you don't want to use the rectangle in the content stream but instead for adding annotations, you are not subject to the transformations mentioned above but you can not make use of it, either.

Thus, in this context you have to take the crop box as it is and transform your rectangle accordingly.

Why PDFBox text extraction coordinates are as they are

Essentially for putting lines of text together in the right order and sorting the lines correctly, you don't want such a weird situation but instead a simple stable coordinate system. Some PDFBox developers chose the top-left-origin, y-increasing-downwards variant for that, and so the TextPosition coordinates have been normalized to that scheme.

In my opinion a better choice would have been to use the default user space coordinates for easier re-use of the coordinates. You might, therefore, want to try working with textPosition.getTextMatrix().getTranslateX(), textPosition.getTextMatrix().getTranslateY() for a TextPosition textPosition

like image 121
mkl Avatar answered Sep 16 '22 12:09

mkl


The accepted answer created some problems for me. Also, text being mirrored and adjusting for that just didn't seem like the right solution for me. So here's what I came up with and so far, this has worked pretty smoothly.

Solution (example available below):

  • Call the getAdjustedPoints(...) method with your original points as you are drawing on paper where x=0 and y=0 is top left corner.
  • This method will return float array (length 4) that can be used to draw rect
  • Array order is x, y, width and height. Just pass that addRect(...) method

private float[] getAdjustedPoints(PDPage page, float x, float y, float width, float height) {
    float resizedWidth = getSizeFromInches(width);
    float resizedHeight = getSizeFromInches(height);
    return new float[] {
            getAdjustedX(page, getSizeFromInches(x)),
            getAdjustedY(page, getSizeFromInches(y)) - resizedHeight,
            resizedWidth, resizedHeight
    };
}

private float getSizeFromInches(float inches) {
    // 72 is POINTS_PER_INCH - it's defined in the PDRectangle class
    return inches * 72f;
}

private float getAdjustedX(PDPage page, float x) {
    return x + page.getCropBox().getLowerLeftX();
}

private float getAdjustedY(PDPage page, float y) {
    return -y + page.getCropBox().getUpperRightY();
}

Example:

private PDPage drawPage1(PDDocument document) {
    PDPage page = new PDPage(PDRectangle.LETTER);

    try {
        // Gray Color Box
        PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, false, false);
        contentStream.setNonStrokingColor(Color.decode(MyColors.Gallery));
        float [] p1 = getAdjustedPoints(page, 0f, 0f, 8.5f, 1f);
        contentStream.addRect(p1[0], p1[1], p1[2], p1[3]);
        contentStream.fill();

        // Disco Color Box
        contentStream.setNonStrokingColor(Color.decode(MyColors.Disco));
        p1 = getAdjustedPoints(page, 4.5f, 1f, 4, 0.25f);
        contentStream.addRect(p1[0], p1[1], p1[2], p1[3]);
        contentStream.fill();

        contentStream.close();
    } catch (Exception e) { }

    return page;
}

As you can see, I've drawn 2 rectangle boxes.
To draw this, I used the the following coordinates which assumes that x=0 and y=0 is top left.

Gray Color Box: x=0, y=0, w=8.5, h=1
Disco Color Box: x=4.5 y=1, w=4, h=0.25

Here's an image of my result. enter image description here

like image 23
ᴛʜᴇᴘᴀᴛᴇʟ Avatar answered Sep 20 '22 12:09

ᴛʜᴇᴘᴀᴛᴇʟ