ITextRenderer:调整内容的页面高度 [英] ITextRenderer: Adjust page height to content
问题描述
我正在使用ITextRenderer从HTML生成PDF,我需要做的是收银机收据. 此收据具有动态宽度,当然还有动态内容.就是说,内容的高度总是不同的,现在我正在努力寻找一种调整PDF页面的高度以适应内容的方法. 如果收据太大,则收据的末尾会有一个长长的白色部分;如果要缩短,则将PDF分页,我只需要一页即可.
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.
我正在使用@page {size: Wpx Hpx;}
设置页面大小,但是几乎不可能(非常痛苦)根据宽度和数据来计算内容高度.
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.
这是生成PDF的代码:
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();
我也尝试过renderer.getSharedContext().setPrint(false);
,但这会引发NPE.
I've also tried renderer.getSharedContext().setPrint(false);
, but this throws a NPE.
@page {-fs-page-sequence: "none";}
也没有运气.
推荐答案
我发现的解决方案甚至还不完美,但是可行!
The solution I found is not even close to perfect, but works!
@page {
size: Wpx 1px;
}
* {
page-break-inside: always;
}
这将为整个内容生成1px页面.然后,我只需要告诉打印机打印所有页面,每页之间的空白为0px.
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.
为什么这种解决方案并不完美?通过3G流式传输时,文件大小从1或2KB到200KB.不是很好.
Why this solution is not perfect? The file size goes from 1 or 2KB to 200KB.. not very good, when streaming through 3G.
这篇关于ITextRenderer:调整内容的页面高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!