ITextRenderer: adjust page height for content

I use ITextRenderer to create PDF from HTML, and I need to get a cash register receipt. This check has dynamic width and, of course, dynamic content. At the same time, the height of the content will always be different, and now I'm struggling to find a way to fit the height of the PDF page to the content. If the receipt is too large, at the end there is a long white section, and if it is shortened, the PDF is paginated, and I need it to be on only one page.

I use @page {size: Wpx Hpx;} to set the page size, but it is almost impossible (it would be very painful) to calculate the height of the content based on the width and data.

This is the code that the PDF generates:

 ITextRenderer renderer = new ITextRenderer(); byte[] bytes = htmlDocumentString.toString().getBytes("UTF-8"); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(bais); Document doc = builder.parse(is); renderer.setDocument(doc, null); renderer.layout(); renderer.createPDF(outputStream); outputStream.flush(); outputStream.close(); 

I also tried renderer.getSharedContext().setPrint(false); but it throws NPE.

Also @page {-fs-page-sequence: "none";} without any luck.

+8
source share
2 answers

The solution I found is not even near perfect, but it works!

 @page { size: Wpx 1px; } * { page-break-inside: always; } 

This will create 1px pages for all content. Then I just have to tell the printer to print all pages with a 0px field between pages.

Why is this solution not perfect? File sizes range from 1 or 2 KB to 200 KB. Not very good when streaming over 3G.

0
source

Publication on behalf of the OP

The solution I found is not even near perfect, but it works!

 @page { size: Wpx 1px; } * { page-break-inside: always; } 

This will create 1px pages for all content. Then I just have to tell the printer to print all pages with a 0px margin between pages.

Why is this solution not perfect? File sizes range from 1 or 2 KB to 200 KB. Not very good when streaming over 3G.

0
source

All Articles