itext 7 html to pdf with page size detection

2019-08-19 01:23发布

问题:

I am using itext 7 to render HTML templates (Velocity) to PDF, then to PNG (Apache PdfBox), for thermal printer printing.

My template is rendered as :

<html>
<head>
    <style>...</style>
</head>
<body>
    <div id="container">...</div>
</body>
</html>

My container has a fixed width to 512px. I would like to measure the rendered height of the html, and then render it as a single page PDF with page height = measured height.

But the rendered size is not the expected size. I expect to have a rendered width of 512px, but the layoutResult returns a width of 385 (instead of the expected 512).

Which parameter have I missed ? Thanks.

回答1:

Please take a look at the FAQ entry How do the measurement systems in HTML relate to the measurement system in PDF? You'll discover that:

1 inch = 96 px

1 inch = 72 user units = 72 pt

Looking at the numbers you have, it looks as if you are confusing pixels and points.

96 px = 72 pt
512 px = 512 / 96 * 72 pt
512 px = 384 pt

I guess you expect 512 px and get 384 pt, but that's not an error, because 512 px equals 384 pt. Hence there is no problem. The main problem with your question is that you forget to mention the measurement system.