JavaFX - 以编程方式设置目标路径以将节点直接打印到pdf文件 [英] JavaFX - set programmatically the destination path to print directly a node to pdf file
问题描述
我想使用Microsoft Print to PDF打印机将节点打印到pdf文件。假设已经提取了Printer对象,我有下一个功能正常工作。
I want to print a node to a pdf file using "Microsoft Print to PDF" printer. Supposing that the Printer object is already extracted I have the next function which is working perfectly.
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。我一直在努力寻找以编程方式设置路径的解决方案,但没有成功。有什么建议?提前谢谢你。
The only issue that I have here, is that a dialog box is popping up and asking for a destination path to save the pdf. I was struggling to find a solution to set the path programmatically, but with no success. Any suggestions? Thank you in advance.
推荐答案
经过一些研究,我带来了一个丑陋的黑客。我从PrinterJob访问了jobImpl私有字段,并从中获取了属性。因此,我插入了目标属性,显然它正在按要求工作。我知道这不好,但......有点可行。如果您有任何更好的建议,请不要犹豫发布。
After some more research I came with an ugly hack. I accessed jobImpl private field from PrinterJob, and I took attributes out of it. Therefore I inserted the destination attribute, and apparently it is working as requested. I know it is not nice, but ... is kind of workable. If you have any nicer suggestion, please do not hesitate to post them.
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);
}
这篇关于JavaFX - 以编程方式设置目标路径以将节点直接打印到pdf文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!