因为这个答案在谷歌上是最重要的,所以这里有一个代码示例:
public class printWithoutDialog implements printable
{
public PrintService findPrintService(String printerName)
{
for (PrintService service : PrinterJob.lookupPrintServices())
{
if (service.getName().equalsIgnoreCase(printerName))
return service;
}
return null;
}
@Override
public int print(Graphics g, PageFormat pf, int page) throws PrinterException
{
if (page > 0) { /* We have only one page, and 'page' is zero-based */
return NO_SUCH_PAGE;
}
/* User (0,0) is typically outside the imageable area, so we must
* translate by the X and Y values in the PageFormat to avoid clipping
*/
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
/* Now we perform our rendering */
g.setFont(new Font("Roman", 0, 8));
g.drawString("Hello world !", 0, 10);
return PAGE_EXISTS;
}
public printSomething(String printerName)
{
//find the printService of name printerName
PrintService ps = findPrintService(printerName);
//create a printerJob
PrinterJob job = PrinterJob.getPrinterJob();
//set the printService found (should be tested)
job.setPrintService(ps);
//set the printable (an object with the print method that can be called by "job.print")
job.setPrintable(this);
//call je print method of the Printable object
job.print();
}
}
要在没有对话框的情况下使用 Java 打印,您只需向 PrinterJob 指定要设置的打印服务是什么。printService 类为您想要的打印机提供服务。此类实现可打印,因为它是在 Java 教程(带对话框)中制作的。唯一的区别在于“printSompething”功能,您可以在其中找到评论。