Java Jpanel打印空白页面

时间:2017-08-08 03:07:14

标签: java printing jpanel

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);
                }

                }   


          }    

我试图打印一个面板并且代码似乎没问题但是当我点击打印并查看它时,它只是一个空白页面。我尝试了很多代码,可以打印面板,但它不打印。即使我重新安装我的NetBeans并安装更新的jdk,它也无法工作。

Blank page

1 个答案:

答案 0 :(得分:0)

当您以pdf格式打印时,您没有丢弃对象 g2 并使用 try catch 块。首先,您必须按原样打印图像,然后尝试翻译它。

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

        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();
            }
        }