I study printing to Java2D. There are two questions for connoisseurs: 1. Is it possible to format text in the g.drawString () method using html tags, like when creating JButton and JLabel? 2. In addition to printing to the printer, I need to organize the document saving. For a start, at least just in the txt-format or in the format of jpg-pictures. Where to start digging the implementation of this task? Thank you in advance!

    2 answers 2

    Java 2D has quite modest features in this regard. With regards to formatting, it is possible to change the font and style:

    int style = Font.BOLD | Font.ITALIC; Font font = new Font ("Arial", style , 11); graphics.setFont(font); graphics.drawString("Hello world!", 100, 100); 

    As for saving the document, you can take a screenshot of the program and save the resulting image to a file, for example:

     private static void saveToFile(JFrame frame) { BufferedImage bImg = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D graphics = bImg.createGraphics(); frame.paintAll(graphics); try { ImageIO.write(bImg, "png", new File(FILE_NAME)); } catch (IOException e) { e.printStackTrace(); } } 

    Or create a Graphics2D object from BufferedImage, draw elements on it and save.

    • About using setFont (), setColor (), etc. I know. I wanted to make my life easier :) It’s just the task of printing a tabular document. With HTML, everything would be much easier. And about saving the screenshot, it's interesting. It is necessary to smoke. Thank. - Artik
    • Why java 2d? I think you can find a third-party solution with great formatting capabilities. - Artem Konovalov
    • I heard about third-party solutions. But I want to try it myself. In the end, the main task is learning java. - Artik

    In general, I dug up one article on javatalks: http://javatalks.ru/topics/22127?page=1#155982 . I leave here, can someone come in handy. So far this is the best solution I have found. I will smoke in this direction.