I'm trying to add print functionality to our swing UI. I tried the following:
protected void print() {
PrinterJob job = PrinterJob.getPrinterJob();
if(job.printDialog()){
try {
job.setPrintable(new Printable() {
@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
if(pageIndex == 0){
Graphics2D g2d = (Graphics2D)graphics;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
// BufferedImage snapshot = AnimUtilities.createSnapshotOfFrame(ApplicationFrame.this, Transparency.TRANSLUCENT);
// double scaleX = pageFormat.getWidth()/snapshot.getWidth();
// double scaleY = pageFormat.getHeight()/snapshot.getHeight();
//
// double scaleValue = Math.min(scaleX, scaleY);
// g2d.scale(scaleValue, scaleValue);
// g2d.drawImage(snapshot, 0, 0, snapshot.getWidth(), snapshot.getHeight(), ApplicationFrame.this);
// ApplicationFrame.this.print(g2d);
ApplicationFrame.this.printAll(g2d);
return PAGE_EXISTS;
}
return NO_SUCH_PAGE;
}
});
job.print();
} catch (PrinterException e) {
e.printStackTrace();
}
} else {
System.err.println("Error printing");
}
}
The code that is not commented out works really well in that what is printed looks very nice on the paper. However, the JFrame is bigger than the paper so it just cuts it off. I also tried the commented out code which creates an image of the JFrame, scales the image appropriately so that it fits on the page and keeps the same aspect ratio, but the scaling makes the text on the screen look horrible. I found this advanced tutorial from Oracle, but that tells how to break up the screen into multiple pages. I just want to print a nice screenshot of the JFrame. How can I print the JFrame without cutting it off or causing artifacts from scaling?
You may get some benefit from RenderingHints
. I'd look at KEY_ANTIALIASING
, KEY_TEXT_ANTIALIASING
and KEY_FRACTIONALMETRICS
in particular.
Edit:
RenderingHints.KEY_INTERPOLATION
also helps, and AffineTransformOp.TYPE_BICUBIC
is another alternative.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With