我想使用“Microsoft Print to PDF”打印机将节点打印到 pdf 文件。假设 Printer 对象已经被提取,我有下一个功能,该功能运行良好。
public static void printToPDF(Printer printer, Node node) {
PrinterJob job = PrinterJob.createPrinterJob(printer);
if (job != null) {
job.getJobSettings().setPrintQuality(PrintQuality.HIGH);
PageLayout pageLayout = job.getPrinter().createPageLayout(Paper.A4, PageOrientation.PORTRAIT,
Printer.MarginType.HARDWARE_MINIMUM);
boolean printed = job.printPage(pageLayout, node);
if (printed) {
job.endJob();
} else {
System.out.println("Printing failed.");
}
} else {
System.out.println("Could not create a printer job.");
}
}
我在这里遇到的唯一问题是弹出一个对话框并询问保存 pdf 的目标路径。我正在努力寻找以编程方式设置路径的解决方案,但没有成功。有什么建议么?先感谢您。
经过更多研究后,我得到了一个丑陋的黑客。我从 PrinterJob 访问了 jobImpl 私有字段,并从中取出了属性。因此,我插入了目标属性,显然它正在按要求工作。我知道这不太好,但是……是可行的。如果您有更好的建议,请随时发布。
try {
java.lang.reflect.Field field = job.getClass().getDeclaredField("jobImpl");
field.setAccessible(true);
PrinterJobImpl jobImpl = (PrinterJobImpl) field.get(job);
field.setAccessible(false);
field = jobImpl.getClass().getDeclaredField("printReqAttrSet");
field.setAccessible(true);
PrintRequestAttributeSet printReqAttrSet = (PrintRequestAttributeSet) field.get(jobImpl);
field.setAccessible(false);
printReqAttrSet.add(new Destination(new java.net.URI("file:/C:/deleteMe/wtv.pdf")));
} catch (Exception e) {
System.err.println(e);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)