java - 在 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 并指向defaultPrinter
了PrintService
. 该文件已创建,但它不是 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 将其保存到某个位置?
解决方案
事实证明,只有 Windows 系统需要属性。如果你在 Linux 系统上使用属性,它只会保存打印机命令而不是 PDF。
如果您lpr
在 linux 系统上调用job.print();
,它将以这种方式创建 PDF,为作业命名,以便您可以在系统上找到它。
必须安装 cups-pdf 和 cups-bsd。
推荐阅读
- shell - Shell - 如何在 for 循环中从文件中提取和替换值
- android - Fabric Beta:组织之间的渠道冲突?
- extjs - 6.5.3 经典 - 可以在图表轴标签上添加工具提示吗?
- c - 整数提升如何在 C Cast 上工作?
- sql - 在从数据库选择中检索 xmltype 时需要帮助
- python - 如何从csv中删除一列?
- assembly - WebAssembly 如何在任何机器上运行?
- android - 如何在 React Native 中正确修剪用户输入?
- javascript - 如何正确更新 Vuex 商店?
- jquery - Jquery 变量在 html 中显示 [object Object] 但在 console.log 中显示正确的值