java如何打印JTextPane页脚中的总页数?
我到处寻找这个答案,结果一无所获
我需要打印JTextPane的内容,页脚上写着“第<;n>;页,共<;m>;页”。在Java中似乎不可能实现这个简单的功能
我可以设置页脚,以便在获得可打印页面时打印页码,例如
String header = "whatever"; String footer = " Page - {0}"; printText(textPane.getPrintable(new MessageFormat(header), new MessageFormat(footer)));
但在发送打印机对话框之前,似乎无法找到要打印的总页数。我认为这是因为该对话框用于在页面发送到打印机之前格式化页面。“打印机”对话框始终显示只有一(1)页
因此,我开始编写一个例程,它将遍历JTextPane文档,并通过print()方法中的PageFormat获取可视区域来计算页面数 然后使用每行的高度(fontsize)来计算每页中的行数,然后计算页数。e、 g
int maxh = (int) pf.getImageableHeight (); Element section = doc.getDefaultRootElement(); for (int i=0; i<paraCount; i++) { Element e = section.getElement(i); // Get the attributeSet for this paragraph (Element) // The attributeSet contains the Styles, which contain // the fonts etc. AttributeSet attrs = e.getAttributes(); int fontsize = StyleConstants.getFontSize(attrs); // .... add up the lines and count filled pages ... }
但是,在系统调用print()方法之前,PageFormat不可用,当它返回到print()方法时,似乎无法修改页脚,因为页眉和页脚在方法调用中都定义为“final”:
public Printable getPrintable(final MessageFormat headerFormat, final MessageFormat footerFormat)
肯定有人找到了一个简单的方法来实现这个基本功能
提前感谢任何能提供帮助的人
# 1 楼答案
似乎没有“直接”的方法来实现这一点。报告说:
# 2 楼答案
我不确定下面关于JEditorPane/JTextPane分页和打印的文章的链接是否能为您带来好处,但它们确实为我带来了很多好处: