Graphics2D drawImage无法正确发送到打印机

时间:2017-01-12 21:20:16

标签: java printing graphics2d

我的问题是,我正在尝试使用Java进行打印,并且每次都会给出一个随机结果(看看图片,你会理解)。第一次运行它时,Image打印得很好,但是第二次有一个黑盒子覆盖了屏幕的一半。这是First Run

enter image description here

Second run

enter image description here

以下是代码:

package test;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.ImageObserver;

import javax.swing.*;
import java.awt.print.*;
import java.net.URL;

public class HelloWorldPrinter implements Printable, ActionListener {
    private Image ix = null;

    public int print(Graphics g, PageFormat pf, int page) throws PrinterException {

        if (page > 0) { /* We have only one page, and 'page' is zero-based */
            return NO_SUCH_PAGE;
        }

        /*
         * User (0,0) is typically outside the imageable area, so we must
         * translate by the X and Y values in the PageFormat to avoid clipping
         */
        Graphics2D g2d = (Graphics2D) g;
        g2d.translate(pf.getImageableX(), pf.getImageableY());
        ix = getImage("Capture.JPG");
        g.drawImage(ix, 1, 1, null);

        return PAGE_EXISTS;
    }

    public void actionPerformed(ActionEvent e) {
        PrinterJob job = PrinterJob.getPrinterJob();
        job.setPrintable(this);
        boolean ok = job.printDialog();
        if (ok) {
            try {
                job.print();
            } catch (PrinterException ex) {
                /* The job did not successfully complete */
            }
        }
    }

    public static void main(String args[]) {
        UIManager.put("swing.boldMetal", Boolean.FALSE);
        JFrame f = new JFrame("Hello World Printer");
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        JButton printButton = new JButton("Print Hello World");
        printButton.addActionListener(new HelloWorldPrinter());
        f.add("Center", printButton);
        f.pack();
        f.setVisible(true);
    }

    public Image getImage(String path) {
        Image tempImage = null;
        try {
            URL imageURL = HelloWorldPrinter.class.getResource(path);
            imageURL = HelloWorldPrinter.class.getResource(path);
            tempImage  = Toolkit.getDefaultToolkit().getImage(imageURL);
        } catch (Exception e) {
            System.out.println(e);
        }
        return tempImage;
    }
}

感谢您花时间阅读本文,希望您有解决方案。

编辑:我使用Microsoft Print To PDF,因此我可以查看打印件。我不知道它是否相关,但无论如何我都会添加它。

1 个答案:

答案 0 :(得分:0)

MadProgrammer的解决方案有效。

  

不要使用Toolkit#getImage,这可能会使用线程加载图像或以意想不到的方式缓存结果,考虑使用ImageIO.read,它会阻塞直到图像完全实现。您的getImage方法也可能触发异常并返回空白图像,但由于您忽略了异常结果,因此很难知道 - MadProgrammer