【问题标题】:Printing a "Printable" object to a PDF file silently以静默方式将“可打印”对象打印到 PDF 文件
【发布时间】:2017-05-09 07:45:58
【问题描述】:

如何以静默方式将“java.awt.print.Printable”对象打印到 PDF?
有几点需要注意:

  • 我没有 pdf 文件格式的数据
  • 我正在处理现有代码,因此无法离开可打印界面

所以我可以用 job.printDialog() 很好地打印它。但我需要能够默默地做到这一点(无需用户输入)。可用的 PDF 打印机是“Adobe PDF”,我想如果需要可以安装其他打印机。

这是基本代码:

Printable printout = /*object*/;
Book pageable = new Book();
pageable.append(printout, pageFormat);

DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PAGEABLE;
PrintRequestAttributeSet patts = new HashPrintRequestAttributeSet();

// Add Filepath?

PrintService[] ps = PrintServiceLookup.lookupPrintServices(flavor, patts);
if (ps.length == 0)
    throw new IllegalStateException("No Printer found");

PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintService(ps[0]);

job.setPrintable(printout);

【问题讨论】:

    标签: java pdf printing


    【解决方案1】:

    我最终决定放弃尝试在 java 中执行此操作,而是使用 PDF 打印机,它可以选择以静默方式打印到预定路径。

    DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PAGEABLE;
    PrintRequestAttributeSet patts = new HashPrintRequestAttributeSet();
    PrintService[] ps = PrintServiceLookup.lookupPrintServices(flavor, patts);
    
    System.out.println("Available printers: " + Arrays.asList(ps));
    
    PrintService myService = null;
    for (PrintService printService : ps) {
        if (printService.getName().contains("PDF Writer - bioPDF")) {
            myService = printService;
            break;
        }
    }
    
    if (myService == null) {
        throw new IllegalStateException("bioPDF Printer not found");
    }
    
    PrinterJob job = PrinterJob.getPrinterJob();
    job.setJobName(jobName);
    job.setPrintService(myService);
    job.setPrintable(printout);
    
    job.print();
    

    【讨论】:

      猜你喜欢
      • 2015-06-07
      • 2015-01-27
      • 1970-01-01
      • 2010-09-14
      • 2017-05-24
      • 2011-02-22
      • 2021-02-11
      • 2020-02-22
      • 2017-04-11
      相关资源
      最近更新 更多