Printing a Report

Printing a Report

Printing a simple report from Java is far from being as simple as you might expect. You use the Toolkit class to create a PrintJob, but the method requires a Properties object, which appears to have no subsequent value. Each line of text has to be positioned graphically, so you need to decide upon a font and obtain some details of the character sizes.

 Properties prop = new Properties();Toolkit tkit = Toolkit.getDefaultToolkit();PrintJob pjob = tkit.getPrintJob(yourFrame, "Print ...", prop);Font mono = new Font("Monospaced", Font.PLAIN, 12);FontMetrics metrics = tkit.getFontMetrics(mono);int linespace = metrics.getHeight();int descender = metrics.getDescent();Graphics page = null;int pagesize = 0;int location = 0;

The PrintJob will provide a Graphics object for each page of the report, but you need to keep track of the position of each text line so you can determine when it’s time to eject a page and start another. It is essential to set the Graphics object’s Font, as there is no default. You cannot reliably obtain the size of paper until after the Graphics object is created, because it may trigger display of a platform dependent dialog box, prompting the user for a choice of printer, paper and orientation. So the loop which prints lines of your report should contain code with the following sequence;

     location = location + linespace;    if (location > pagesize) {        if (page != null) page.dispose();        page = pjob.getGraphics();        page.setFont(mono);        pagesize = pjob.getPageDimension().height;        location = linespace;    }    page.drawString(yourtext, 0, location - descender);

After the loop you need to eject the last page and terminate the PrintJob;

 if (page != null) page.dispose();pjob.end();

Thankfully, the units of the FontMetrics, PageDimension and String locator are consistent and are typically 1/72nd of an inch. The Java SDK refers to them as pixels. Comparing the width and height returned by the getPageDimension method enables you to determine paper orientation, but if you are interested in the actual size of the paper, you just ran out of luck. The getPageResolution method is supposed to provide the pixels-per-inch, but in most implementations these are not the same pixels! Despite SDK documentation to the contrary, it seems to be the printer’s dots-per-inch which is returned.

See also  5 Benefits of Using Time Tracking Software

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist