I have searched high and low for this answer and have come up blank.
I have a requirement to print the contents of a JTextPane with a footer that says "Page <n> of <m> pages". It appears to impossible to do this simple function in Java.
I can set the footer to print the page numbers when I get the Printable, e.g.
String header = "whatever"; String footer = " Page - {0}"; printText(textPane.getPrintable(new MessageFormat(header), new MessageFormat(footer)));
But there appears to be no way to find the total number of pages that will be printed until after the printer dialog box is dispatched. I assume that is because that dialog is used to format the pages before they are sent to the printer. The printer dialog box always says that there is only 1 (one) page.
So, I began to write a routine that will go through the JTextPane document and count the pages by getting the viewable area from the PageFormat in the print() method and then using the height of each line (fontsize) to count the lines in each page, and subsequently count the number of pages.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 ... }
However, the PageFormat is not available until the system calls back into the print() method, and by the time it gets to the print() method, it appears to be impossible to modify the footer since the header and footer are both defined as "final" in the method call:
public Printable getPrintable(final MessageFormat headerFormat, final MessageFormat footerFormat)
Surely somebody has found a simple way to do this basic function.
Thanks in advance for any who can help.