Question:
In a Java application I print through PrintJob, but the way I print when I call the Print method it opens a printer dialog so I can choose which one to print on, I tried and I couldn't make it print without having to call the dialogue.
Below is my printing method.
print.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();
}
Answer:
You may be trying to adapt this example I made my friend to your own needs. In it I print an object of the Drawing class that must implement Printable so that it is a printable object, then I call in the main class the print() method of the PrinterJob object, so it will print directly to the printer, without displaying the dialog, when you attempts to print from a Toolkit PrinterJob will always display the printers dialog, there is no workaround.
Object class 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();
}
}
}