首页 > 解决方案 > 在 Linux 系统上使用 Java Printable 保存 PDF 文件

问题描述

我有一个工作类,它通过实现 Printable 并使用 PrinterJob 将 PDF 创建到设定位置来为用户创建和保存 PDF 文件。这在 Windows 系统上完美运行,但我在 Linux 系统上遇到了麻烦。

我正在尝试在 Linux 系统上自动创建这些 PDF,如下所示:

    PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintable( this );
    job.setPrintService( defaultPrinter );
    // create a new HashPrintRequestAttributeSet
    HashPrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
    // set the output file as a destination 
    attributes.add(new Destination(new File(fileName).toURI()));
    job.print(attributes);

我已经在我的 Linux 系统上安装了 cups-pdf 并指向defaultPrinterPrintService. 该文件已创建,但它不是 PDF 文件,而是 Postscript 文件。CUPS 甚至没有为此创建打印作业,所以我相信它只是创建一个带有打印机命令的 postscript 文件。

Postscript 文件开始如下:

%!PS-Adobe-3.0
%%BeginProlog
/imStr 0 def /imageSrc {currentfile /ASCII85Decode filter /RunLengthDecode filter  imStr readstring pop } def
/BD {bind def} bind def
/D {def} BD
/C {curveto} BD
/L {lineto} BD
/M {moveto} BD
/R {grestore} BD
/G {gsave} BD
/N {newpath} BD
/P {closepath} BD
/EC {eoclip} BD
/WC {clip} BD
/EF {eofill} BD
/WF {fill} BD
/SG {setgray} BD
/SC {setrgbcolor} BD
...

我知道我可以使用 PDFBox 自己绘制 PDF,但所有代码都用于创建 PDF 文件,并且都可以在 Windows 上运行。是否可以让 linux 系统创建 PDF 并使用 PrinterJob 将其保存到某个位置?

标签: javalinuxpdfpostscriptcups

解决方案


事实证明,只有 Windows 系统需要属性。如果你在 Linux 系统上使用属性,它只会保存打印机命令而不是 PDF。

如果您lpr在 linux 系统上调用job.print();,它将以这种方式创建 PDF,为作业命名,以便您可以在系统上找到它。

必须安装 cups-pdf 和 cups-bsd。


推荐阅读