2017-08-08 152 views
0
private void cmdprintActionPerformed(java.awt.event.ActionEvent evt) {           

     PrinterJob job = PrinterJob.getPrinterJob(); 
     job.setJobName("Outside Processing System"); 

       job.setPrintable (new Printable() { 

       @Override 
       public int print(Graphics pg, PageFormat pf, int pageNum){ 

       if (pageNum > 0){ 
       return Printable.NO_SUCH_PAGE; 
       } 

       OPSPrintPanel panel = new OPSPrintPanel(); 
       Graphics2D g2 =(Graphics2D)pg; 
       g2.translate(pf.getImageableX(), pf.getImageableY()); 
       panel.paint(pg); 
       return Printable.PAGE_EXISTS; 

       } 

       }); 
       boolean ok = job.printDialog(); 
       if (ok) { 
       try { 

       job.print(); 

       } catch (PrinterException ex) { 
       JOptionPane.showMessageDialog(null, ex); 
       } 

       } 


      }  

我试图打印一个面板和代码似乎没关系,但是当我点击打印和查看它的pdf只有一个空白页。我尝试了很多可以打印面板但不打印的代码。即使我重新安装了我的NetBeans并安装了更新后的jdk,它也不起作用。Java Jpanel打印空页面

Blank page

回答

0

你没有处置对象G2和使用尝试捕捉块,当你打印成PDF。首先,您必须按原样打印图像,然后尝试翻译它。

试试这个,我希望它能起作用。

 OPSPrintPanel panel = new OPSPrintPanel(); 
     //print the panel to pdf 
     Document document = new Document(); 
     try { 
      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\temp\\test.pdf")); 
      document.open(); 
    // PdfContentByte is an object containing the user positioned text and 
    // graphic contents of a page. It knows how to apply the proper font encoding. 
      PdfContentByte contentByte = writer.getDirectContent(); 
      PdfTemplate template = contentByte.createTemplate(500, 500); 
      Graphics2D g2 = template.createGraphics(500, 500); 
     // First print the panel as it is and then try to translate it by removing comments 
     // g2.translate(pf.getImageableX(), pf.getImageableY()); 
      panel.print(g2); 
      g2.dispose(); 
     // Adds a template to this content. 
      contentByte.addTemplate(template, 30, 300); 
     } catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 
     finally 
     { 
      if(document.isOpen()) 
     { 
       document.close(); 
      } 
     } 
+0

我的目标是打印在打印机上,我使用pdf来查看代码的工作原理。我的代码工作,如果我打电话给我的MainFrame,但当我想调用一个JPanel或其他面板,框架结果是空白的。我想要打印的Jpanel由标签和jtable组成。 – Ryuizano