I am experiencing problems with images being larger when drawing onto a PdfDocument.Page. The app is targeted for a device running Android 4.4.4 (API level 19).
I am gen
This is a late answer, but a have been dealing with the same problem, and found the solution, with an explanation.
The explanation:
PdfDocument.Page size units, Postscript points which are 1/72 inch.
This means, that the PdfDocument uses points that measure 1/72th of an inch when physically printed, which is equal to say that in the printed document, there will be 72 points in 1 inch. This is also known as 72 DPI (Dots Per Inch).
So, with 72 DPI, if you wanted to see the document in your screen at the same exact size of the document printed (with no zoom ofc), you would need 72 pixels per inch (PPI)
Unlike pictures, PDF files have physical size, so the Canvas of the PdfDocument.Page can be understood as the "screen" where you are printing your document. This "screen" MUST have a density of 72 PPI for the content to be represented as the original.
The solution:
There is no need for logo.setDensity(DisplayMetrics.DENSITY_XHIGH);
because you dont want to change the scale of the image, you need to specify the density of the canvas.
Solution is canvas.setDensity(72);
As requested, the solution I found was to set the density to a value higher than what it should be. Setting the bitmap density to DENSITY_XHIGH instead of DENSITY_HIGH improved the rendered bitmap considerably for me. The bitmap is closer to the size I would expect when the pdf is generated.
[I copied your solution to an answer. If you have found a solution please create an answer and accept it yourself]
I have tried setting the bitmap density to a value higher than what I think it should be: logo.setDensity(DisplayMetrics.DENSITY_XHIGH);
And this did the trick. (I originally set it to DENSITY_HIGH, but it was still scaling the image up slightly, so changed it to DENSITY_XHIGH
.)
The exact solution is to set the Canvas' density to 72 (But why?)
logo.setDensity(dpi);
(calc dpi from desired image dimensions in pt and bitmap size)canvas.setDensity(72);
canvas.drawBitmap(logo, ....);