Remove Printer Dialog - Printjob Java

Asked

Viewed 1,452 times

3

In a Java application I do the printing through Printjob, but in the way I do the printing by calling the Print method it opens a printer dialog box so I choose which one to print, I tried and I couldn’t get it to print without having to call the dialogue.

Follow down to my printing method.

Print out java.

public void imprimir() {


    Frame f = new Frame("Frame temporário");
    f.setSize((int) 283.46, 500);
    f.pack();


    Toolkit tk = f.getToolkit();

    PrintJob pj = tk.getPrintJob(f, "MP4200", null);



    if (pj != null) {
        Graphics g = pj.getGraphics();

    ...Aqui vai os dados impressos...


        g.dispose();

        pj.end();
    }


    f.dispose();
}

1 answer

0


You may be trying to adapt this example that I made friend to your need. In it I print an object of the Drawing class that you must implement Printable for it to be a printable object, then I call in the main class the method print() of the object Printerjob, so it will have print directly on the impeller, without displaying the dialog, when you try to print from a Printerjob of a Toolkit will always display the dialog box of the printers, there is no solution in this sense.

Class of object to be printed.


public class Desenho implements Printable {
    // Deve implementar Printable para que seja um objeto imprimivel

    @Override
    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
            throws PrinterException {
        if (pageIndex > 0) {
            return Printable.NO_SUCH_PAGE;
        } else {
            // Renderiza um quadrado
            Graphics2D g2d = (Graphics2D) graphics;
            int x = 90;
            int y = 90;
            g2d.draw(new Rectangle2D.Double(x, y, 500, 500));

            // Mostra que imprimiu o objeto
            return Printable.PAGE_EXISTS;
        }
    }
}   

And the test class

public class Impressora {

// Classe main para testar o exemplo
public static void main(String[] args) {
    Impressora imp = new Impressora();
    imp.imprimir();
}

public void imprimir() {
    PrinterJob impressor = PrinterJob.getPrinterJob();
    // Informo ao impressor o objeto que quero imprimir
    impressor.setPrintable(new Desenho()); 
    try {
        // Manda imprimir diretamente na impressora padrão
        impressor.print();
        // Abre a caixa de dialogo de impressão
        // impressor.printDialog();
    } catch (PrinterException e) {
        e.printStackTrace();
    }
}

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.