1

数年間Javaに触れていませんでしたが、画像とテキストを印刷するためのJavaコードを数回作成するように依頼されました。Mac では正常に動作しますが、Windows マシンから印刷すると印刷が切り取られます。画像は彼の解像度で、300DPI で約 8x10 です。

public class printClass implements Printable {

BufferedImage image;
private URL url;

printClass(URL url1) {
    url = url1;
}

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

    Graphics2D g2d = (Graphics2D) g;
    g2d.translate(pf.getImageableX(), pf.getImageableY());

    AffineTransform theAT = g2d.getTransform();

    double theScaleFactor = (72d / 300d);

    Font font = new Font("Arial", Font.PLAIN, 10);
    Font font2 = new Font("Arial", Font.PLAIN, 5);

    g2d.setFont(font);



    if (page < 10) {
        g2d.scale(theScaleFactor, theScaleFactor);
        g2d.drawRenderedImage(image, null);
        g2d.setTransform(theAT);
        return PAGE_EXISTS;
    } else {
        return NO_SUCH_PAGE;
    }

}public void init() {

    try {
        img = ImageIO.read(url);
        image = (BufferedImage) img;
    } catch (IOException e) {
        System.out.println("Error: " + e);
    }
    PrinterJob job = PrinterJob.getPrinterJob();
    PrinterResolution pr = new PrinterResolution(300, 300, PrinterResolution.DPI);
    PrintRequestAttributeSet attrib = new HashPrintRequestAttributeSet();
    PageFormat pFormat = job.getPageFormat(attrib);
    Paper paper = pFormat.getPaper();
    paper.setImageableArea(0.0,0.0,pFormat.getPaper().getWidth(), pFormat.getPaper().getHeight());
    pFormat.setPaper(paper);


    attrib.add(pr);
    attrib.add(PrintQuality.HIGH);

    job.setPrintable(this);

    boolean ok = job.printDialog();
    if (ok) {
        try {
            job.print(attrib);
        } catch (PrinterException ex) {
        }
    }
}
}

URLは印刷中の画像です。これは Java アプレットの一部です。このコードにはテキスト追加部分がありませんが、次のようになります。

 g.drawString(markUpText, x, y);

いつもありがとうございます。

4

1 に答える 1

1

Okay so I solved my own problem. I did not include the print format to the printable.

 job.setPrintable(this,pFormat);

This cause some other interesting problems with print quality and location in Windows and location in Mac.

I solved the quality issues by removing the DPI and and PrintQuality.HIGH from the attributes.

I solved the location issue with the following code in the prinatble function:

 g2d.translate(pf.getImageableX() + 30, pf.getImageableY()+30);

I also switched to the new Copies to attributes to allow me to easily control the amount of copies they want printed.

Still not sure if this is the best way to go about this but it works!

于 2012-06-11T19:53:20.167 に答える