Java使用“Microsoft Print To PDF”打印时如何指定输出路径
#前言
使用本地虚拟机打印机(Microsoft Print To PDF)可以方便的对打印功能进行测试或者将文件转换成PDF文件,但是每次转换前都要手动选择保存的路径,即便使用Java代码,也是会弹出文件选择框,选择保存到哪里,有什么办法可以固定这个路径或者通过程序指定呢?
指定固定路径
通过检索,大多数的做法是通过指定一个本地路径的端口,这样就可以保存到指定的文件了,参考:如何指定Microsoft Print To PDF的输出路径
程序动态指定
通过查询JDK的文档,发现有一个属性:javax.print.attribute.standard.Destination
指的就是最终文件保存的路径,亲测了一下是有效的,以下是完整的代码示例:
public static void main(String[] args) throws PrintException, IOException, URISyntaxException {// 获取到所有的打印服务PrintService[] printServices = PrinterJob.lookupPrintServices();for (PrintService printService : printServices) {// 找到Microsoft Print To PDF虚拟打印机if (printService.getName().equals("Microsoft Print To PDF")) {DocPrintJob printJob = printService.createPrintJob();// 打印源对象FileInputStream pdfStream = new FileInputStream("E:\\myPic.jpg");Doc doc = new SimpleDoc(pdfStream, DocFlavor.INPUT_STREAM.JPEG, null);PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();// 关键步骤:指定输出路径attributes.add(new Destination(new URI("file:///E://myPic.pdf")));// 执行打印printJob.print(doc, attributes);}}}