PDF cropping image almost correctly

ساخت وبلاگ

Vote count: 0

I've inherited some code that hand-rolls PDF files. One of the things this code does, is that a large image is inserted into the PDF as a resource, and then pieces of that image are cropped in the PDF command stream and drawn separately.

For example, if the large image is 1000 x 400 pixels, the code draws a chunk extracted from the top left of the large image ((0, 0) to (250, 200)) and then next to that draws another chunk extracted from the top middle of the large image ((250, 0), (500, 200)) (in this post I'm describing the crop coordinates using standard image coordinate system with origin in top-left).

The way the code does this, is to create a secondary XObject that just draws the large image, scaled and offset appropriately. So to extract the image from ((250, 0) to (500, 200)) it defines a new XObject like this:

/Type/XObject /Subtype/Form /FormType 1 /Name/Img4 /BBox [0 0 1 1] /Matrix [1 0 0 1 0 0] /Length 143252 /Resources << /XObject << /img3 23 0 R >> >>
4 0 0 2 1 1 cm
/img3 Do

(obviously I've cut out a lot of PDF, don't worry, it works so the PDF you don't see is basically correct)

Which, if I understand it correctly, takes the XObject of the original image (which is a 1 x 1 square), makes it 4 times bigger in the x-direction and 2 times bigger in the y-direction, offsets it by 1 in both x and y, and now the portion of the image we want appears in the XObject rectangle of ((0, 0), (1, 1)). So the code can just draw this new XObject wherever it wants, and gets the cropped portion of the large image.

This basically works correctly, but of course in the real world the large image is 656 x 656, and the pieces being extracted are 308 x 120 and 40 x 120 so the numbers aren't quite as nice.

If I look at the resulting PDF at high magnification (1600%) in Adobe Acrobat Reader, it's perfect. All the pixels exactly where they should be.

Portion of PDF output at 1600%

The problem I'm running into, is that at lower magnification (200%), I end up with this strange offset where the 2 images abut:

Portion of PDF output at 200%

For this example, the transform matrix that does the cropping is:

2.12987 0 0 5.46667 -0 -4.46667 cm

which seems like it should be enough digits of precision, but even if I increase the precision:

2.1298701 0 0 5.4666667 -0 -4.4666667 cm

the exact same problem happens.

It looks like Adobe Reader is truncating the precision somewhere in its calculations.

Any idea why this is happening, and how I can get around it?

asked 1 min ago

back soft...
ما را در سایت back soft دنبال می کنید

برچسب : pdf crop image,pdf crop image data to frames,pdf crop imagemagick,cropping pdf images in latex,crop pdf image online,crop pdf image mac,crop pdf image linux,crop pdf image in illustrator,crop pdf image free,crop pdf image in word, نویسنده : استخدام کار backsoft بازدید : 430 تاريخ : شنبه 17 مهر 1395 ساعت: 21:15