'How to print() without printDialog()?
So I have this code that print some string lines, and I want to print it whitout having to choose the printer, and how can I set the pageformat ?
import java.awt.Graphics;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import javax.swing.JPanel;
public class Test extends JPanel {
public static void main(String[] args) {
try {
PrinterJob pjob = PrinterJob.getPrinterJob();
pjob.setJobName("Graphics Demo Printout");
pjob.setCopies(1);
pjob.setPrintable(new Printable() {
public int print(Graphics pg, PageFormat pf, int pageNum) {
if (pageNum > 0) // we only print one page
return Printable.NO_SUCH_PAGE; // ie., end of job
pg.drawString("aaaaa", 10, 10);
pg.drawString("bbbbb", 10, 20);
return Printable.PAGE_EXISTS;
}
});
if (!pjob.printDialog()) // choose printer
return;
pjob.print();
} catch (PrinterException pe) {
pe.printStackTrace();
}
}
}
Solution 1:[1]
You can specify the PageFormat as an additional parameter for the setPrintable() method. To create a PageFormat object you can ask the PrinterJob object.
And as soon as you provide a PageFormat object the call to printerDialog() is (at least on my machine) no longer necessary.
I've modified your sample code accordingly:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import javax.print.PrintService;
public class Test {
public static void main(String[] args) {
try {
PrinterJob pjob = PrinterJob.getPrinterJob();
pjob.setJobName("Graphics Demo Printout");
pjob.setCopies(1);
// on my machine `printServices[2]` is a virtual PDF printer - good for testing since it doesn't any paper
// PrintService[] printServices = PrinterJob.lookupPrintServices();
// pjob.setPrintService(printServices[2]);
PageFormat pageFormat = pjob.defaultPage();
pjob.setPrintable(new Printable() {
public int print(Graphics pg, PageFormat pf, int pageNum) {
if (pageNum > 0) // we only print one page
return Printable.NO_SUCH_PAGE; // ie., end of job
Font f = pg.getFont();
pg.setFont(f.deriveFont(Font.PLAIN, 24));
pg.setColor(Color.black);
pg.drawString("aaaaa", 100, 100);
pg.drawString("bbbbb", 100, 200);
return Printable.PAGE_EXISTS;
}
}, pageFormat);
pjob.print();
} catch (PrinterException pe) {
pe.printStackTrace();
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Thomas Kläger |
