ITextRenderer: Adjust page height to content
Asked Answered
P

1

9

I'm using ITextRenderer to generate a PDF from HTML and what I need to do is a cash register receipt. This receipt has dynamic width and, of course, dynamic content. This said, the height of content will always be different and right now I'm struggling to find a way of adjusting the height of the PDF page to the content. If it's too big the receipt has a long white section in the end and if it's to short the PDF get's paginated and I need it to be in one page only.

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

This is the code that generates the PDF:

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've also tried renderer.getSharedContext().setPrint(false);, but this throws a NPE.

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

Pembrook answered 7/3, 2013 at 20:23 Comment(3)
I am also facing the same issue.Did u find solution?Journal
Yeah, it's under "Solution".Pembrook
please post the solution as an answer (not in the question itself), you can answer your own question. thanksSpoof
P
2

The solution I found is not even close to perfect, but works!

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

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

Why this solution is not perfect? The file size goes from 1 or 2KB to 200KB.. not very good, when streaming through 3G.

Pembrook answered 2/7, 2019 at 17:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.