Android: PDF created using PrintedPdfDocument looks different on different devices

310 views Asked by At

I am trying to render a view to a PrintedPdfDocument. The size of the page, as expected, is in units 1/72nd of an inch. So, for an A0 size page (width = 33.11 in), document.getPageWidth() returns 2384 (33.11 * 72). The page canvas width equates one pixel to one 1/72nd of an inch unit - so, pageCanvas.getWidth() returns 2384. This is true on different devices. So far so good.

The problem I am facing is that on different devices, the generated PDF document for the same view looks different. On some devices it is stretched on the PDF page, and on somes devices it renders as it should.

What could be the issue here? Isn't the generation of the PDF supposed to be device independent? I noticed that pageCanvas.getDensity() is different on different phones. Why does the phone screen density impact the density of the PDF page canvas?

Given that the numerically document.getPageWidth() in 1/72nd of an inch == pageCanvas.getWidth() in pixels, shouldn't pageCanvas.getDensity() always be 72 DPI? On some phones it is 320 (where it shows correctly) and on others it is 420 (where the view is rendered stretched).

A bit stuck here, so would really appreciate any pointers. Thanks in advance!

1

There are 1 answers

0
Vijayendra Vasu On

I found a way to work around this problem.

I still don't know why pageCanvas.getDensity() is set to the display density instead of the density of the PDF Page (72dpi). My guess is that it may be because some views may incorrectly use display metrics of the screen when drawing to a canvas, even when the canvas is not the screen - but this is just my guess.

Regardless of why pageCanvas.getDensity() is set to screen density, the way I worked around it was by computing the page dimensions (which is in dp) using the screen density. So, if I want to draw to an A0 page (which is 33.11 inches wide), I set the width of the page (when creating the PrintedPdfDocument) to 33.11 * 420 = 13906 dp, instead of the recommended 33.11 * 72 = 2384 dp. This way, when the views draw to the canvas that has 420 dpi density, the resultant page is the required 33.11 inches wide.

This is working perfectly and the created PDF page now looks the same regardless of the device where it was created. The only side effect is that Adobe Acrobat thinks the pages are 33.11 * 420 / 72 inches wide instead of 33.11 inches wide. But this doesn't really matter practically, since we can shrink the pages to fit an A0 paper while printing.