本文介绍了在 Java 中强制目标打印机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在 java 中使用 HashPrintRequestAttributeSet 强制目标打印机?
Is there a way to force the target printer in java, using HashPrintRequestAttributeSet ?
我不希望用户能够在打印对话框中更改打印机
I don't want the user to be able to change the printer in the printdialog
谢谢
推荐答案
不得不以艰难的方式解决这个问题,但为了后代,这里是我的一些代码:
Had to figure this out the hard way, but for the future generations, here's some of mycode:
PrintService[] printServices;
PrintService printService;
PageFormat pageFormat;
String printerName = "Your printer name in Devices and Printers";
PrintServiceAttributeSet printServiceAttributeSet = new HashPrintServiceAttributeSet();
printServiceAttributeSet.add(new PrinterName(printerName, null));
printServices = PrintServiceLookup.lookupPrintServices(null, printServiceAttributeSet);
pageFormat = new PageFormat(); // If you want to adjust heigh and width etc. of your paper.
pageFormat = printerjob.defaultPage();
PrinterJob printerjob = PrinterJob.getPrinterJob();
printerjob.setPrintable(new Server(), pageFormat); // Server was my class's name, you use yours.
try {
printService = printServices[0];
printerjob.setPrintService(printService); // Try setting the printer you want
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Error: No printer named '" + printerName + "', using default printer.");
pageFormat = printerjob.defaultPage(); // Set the default printer instead.
} catch (PrinterException exception) {
System.err.println("Printing error: " + exception);
}
try {
printerjob.print(); // Actual print command
} catch (PrinterException exception) {
System.err.println("Printing error: " + exception);
}
这篇关于在 Java 中强制目标打印机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!