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

Graphics2D drawImage won't send correctly to printer

我的问题是,我正在尝试使用 Java 进行打印,但似乎每次都给出随机结果(看看图片,您就会明白)。我第一次 运行 图像打印正常,但第二次有一个黑框覆盖了一半的屏幕。这里是 First Run

和Second run

代码如下:

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 以便查看打印件。我不知道它是否相关,但无论如何我都会添加它。

MadProgrammer 的解决方案有效。

Don't use Toolkit#getImage, this could using a thread to load the image an or caching the results in unexpected ways, consider using ImageIO.read instead, it will block until the image is fully realised. It's also possible that your getImage method is triggering an exception and is returning a blank image, but since you ignore the exception result, it's hard to know – MadProgrammer