pvginkel / PdfiumViewer

PDF viewer based on Google's PDFium.
Apache License 2.0
967 stars 418 forks source link

pdf rendered with incorrect size #114

Closed ColinYhap closed 7 years ago

ColinYhap commented 7 years ago

Good Day,

Thank you very much for making your work freely available. I have been able to use in small personal projects of mine. The issue I am experiencing is that I am trying to render a pdf (8 1/2"x14") to an image. The code is as follows:

C# PdfiumViewer.PdfDocument r = PdfiumViewer.PdfDocument.Load(pdf); r.Render(pc, (int)r.PageSizes[0].Width / 72 * 300, (int)r.PageSizes[0].Height / 72 * 300, 300, 300, true));

However, an image with dimensions 4200x2400 is returned as opposed to the correct size of 4200x2550. Can you point me in the right direction?

Thank you.

n.b. pdf size is in points, 1008x612

tiesont commented 7 years ago

Shouldn't need to do this. Did you see #79?

tiesont commented 7 years ago

Seems worth mentioning that you're doing integer division, so what you're seeing is probably the result of truncating the result of 300 / 72. Instead of 4 1/6 (or ~4.16666666666666666666666666666667), you're simply multiplying by 4.

612 * 300 / 72 = 2550
612 * 4 = 2448

I assume the dimensions you're giving aren't exactly what PageSizes is reporting, but there is definitely some truncation somewhere in the process. You probably want something along these lines:

// load the PDF
var doc = PdfiumViewer.PdfDocument.Load(pdf);

// Define our scaling value
var scale = 72 * 300f;

// cast the result of the expression, not the width/height values
var width = (int)(r.PageSizes[0].Width / scale);
var height = (int)(r.PageSizes[0].Height / scale);

// Render the image. Don't forget to dispose the image after saving
var img = doc.Render(pc, width, height, 300, 300, true));
pvginkel commented 7 years ago

It's better to first multiply by the target DPI and divide by the source DPI. As mentioned in #79, the Render method can do this for you. However, this also had the exact same problem, which is now fixed through #121.