Java: Printing program output to a physical printer

后端 未结 3 742
时光说笑
时光说笑 2020-12-09 12:21

I am a relatively new programmer so this may be a really simple question to answer but its got me a bit stumped..

I\'m trying to print my Java GUI\'s final output t

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 13:00

    instead of generating a Doc you could print your graphics of a JFrame/JPanel directly. This code should work:

    PrinterJob pj = PrinterJob.getPrinterJob();
                  pj.setJobName("name");
    
                    PageFormat format = pj.getPageFormat(null);
    
                    pj.setPrintable (new Printable() {
    
                    @Override
                    public int print(Graphics pg, PageFormat pf, int pageNum) throws PrinterException {
                        if (pageNum > 0){
                              return Printable.NO_SUCH_PAGE;
                              }
    
                              Graphics2D g2 = (Graphics2D) pg;
    
                              this.paint(g2);
                              return Printable.PAGE_EXISTS;
                    }
    
                  }, format);
                  if (pj.printDialog() == false)
                  return;
    
    
                  pj.print();
                  } catch (PrinterException ex) {
                        // handle exception
                  }
                }
    

提交回复
热议问题