Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
May 20, 1998

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.
Tom Yarker
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap