0

I have struggled with this problem for long time and couldn't find any answer. My problem is, that I have some text, which I would like to print using java's PrinterJob, but I want to be able to show the user how many pages will be printed in the print dialog (if I do not specify the number, 9999 will show up as the number of pages).

It's OK with images, custom shapes, etc. because I can simply calculate the number of pages for the content using given PageFormat. BUT! with text content I can't calculate the size of the text without the Graphics object or the FontRenderContext!

So in practice that means I can calculate the text size only in the print method of the Printable interface using given Graphics and getFontMetrics method. Am I right?

One way would be to create Images from my content and then printing the images, but I don't want that, because for my purposes I need to draw the text directly into Graphics object in my print method.

So tell me guys am I stupid or is this not doable in Java? I suppose the first option is correct.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
ghoust
  • 1
  • Maybe you should use the extended javax.printer API therefore. – isnot2bad Dec 10 '13 at 08:56
  • You fudge this a little. Basically, the API works on the assumption that the printing is done at 72 dpi (this goes WAY back to the original API). If required, you can convert page width and height to pixels using this information. You can then "guess" how many lines of text will fit within the given page. Remember, you will need a valid `PageFormat` and `Paper` to do this. For more ideas try checking out [this example](http://stackoverflow.com/questions/18975595/how-to-design-an-image-in-java-to-be-printed-on-a-300-dpi-printer/18975822#18975822) – MadProgrammer Dec 10 '13 at 09:10
  • Thanks guys. I'll try to look into javax.printer API, it may have some more possibilities than the old API. Thank you isnot2bad ;). – ghoust Dec 10 '13 at 11:48
  • OK @MadProgrammer. That may be the solution, but it looks like the very last option. I do not want to guess anything. I don't see why it shouldn't be possible to precalculate the text height and width, which will be used when printing. Ie. what if I want to allow the user to choose the font and font size, which will be used to print the text? Then I need to calculate the text size in pixels anyway. So guessing is not an option (at least not yet). Thanks anyway man – ghoust Dec 10 '13 at 12:13
  • I looked into the javax.print API a bit, but it looks like I can't print using the Graphics object like the old way. Am I right? – ghoust Dec 10 '13 at 12:17
  • You can't print with a reference to the `Graphics` context of the printer and there's no way to get that until a print job has being started. Generating a `BufferedImage` in this manner is also a way to generate a print preview. – MadProgrammer Dec 10 '13 at 19:13

0 Answers0