Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print a swing window so it fits nicely in one page

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?

like image 801
Jay Askren Avatar asked Oct 11 '22 09:10

Jay Askren


1 Answers

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.

like image 151
trashgod Avatar answered Nov 08 '22 08:11

trashgod