Remove printer dialog-PrintJob Java
In a Java application I do the printing by means of PrintJob, but the way I do the printing when calling the print method it opens a printer dialog box so that I choose which one to print on, I tried and could not make it print without having to call the dialog.
Follows my printing method below.
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();
}
1 answers
You may be trying to adapt this example I made friend to your need. In it, I print out an object of a class in Drawing, you must implement the Printable for an object to print, I get to call the parent class method print() object PrinterJob; so he's going to send you to print directly on the impessora, without showing the dialog when you try to print a PrinterJob of Toolkit - is always going to display the dialog box of the printers, there is no solution in this regard.
Class of the 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
{[1]}
// 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();
}
}
}