Pergunta

Have not touched Java in a few years but I was asked to make some java code to print a picture and some text several times. It works fine on a Mac but printing from a windows machine the print out is cropped. The image is his res and about 8x10 at 300DPI.

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

The URL is the image being printed. This is part of an Java applet. The text addition part is missing in this code but it is like the following:

 g.drawString(markUpText, x, y);

As always thank you in advance.

Foi útil?

Solução

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!

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top