8

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.

4

1 に答える 1

0

私が見つけた解決策は完璧にはほど遠いですが、うまくいきます!

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

これにより、コンテンツ全体に対して 1 ピクセルのページが生成されます。次に、すべてのページをページ間の余白 0px で印刷するようにプリンタに指示するだけです。

このソリューションが完璧でないのはなぜですか? ファイルサイズは 1 または 2KB から 200KB になります.. 3G 経由でストリーミングする場合、あまり良くありません。

于 2019-07-02T17:50:44.353 に答える