PDFBox创建并打印PDF文件, 以及缩放问题的处理.

时间:2023-03-10 00:40:25
PDFBox创建并打印PDF文件, 以及缩放问题的处理.

PDFBox带了一些很方便的API, 可以直接创建 读取 编辑 打印PDF文件.

创建PDF文件


     public static byte[] createHelloPDF() {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage(page);
PDFont font = PDType1Font.HELVETICA_BOLD;
PDPageContentStream content = new PDPageContentStream(doc, page);
content.beginText();
content.setFont(font, 20);
content.moveTextPositionByAmount(250, 700);
content.drawString("Hello Print!"); content.endText();
content.close();
doc.save(out);
doc.close();
} catch (Exception e) {
e.printStackTrace();
}
return out.toByteArray();
}

这边如果不把他save到byte[]里, 而是直接close, 返回PDDocument 给外部文件.

可能会出现Cannot read while there is an open stream writer

打印文件


         // 获取本地创建的空白PDF文件
PDDocument document = PDDocument.load(createHelloPDF());
// 加载成打印文件
PDFPrintable printable = new PDFPrintable(document);
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(printable);
job.print();

如需要打印自定义纸张, 参加另外一篇博客 使用PDFBox打印自定义纸张的PDF

如果想要读取本地pdf文件, 那就更简单了, 直接

         InputStream in = new FileInputStream("d:\\cc.pdf");
PDDocument document = PDDocument.load(in); 

缩放问题


不过发现打印出来的pdf文件存在缩放问题. 显得边距很大, 能跑马.

研究了下, 发现PDFPrintable可以接受是否缩放的参数.

         public enum Scaling {
// 实际大小
ACTUAL_SIZE,
// 缩小
SHRINK_TO_FIT,
// 拉伸
STRETCH_TO_FIT,
// 适应
SCALE_TO_FIT; private Scaling() {
}
}

因此只要在 new PDFPrintable(document), 传入Scaling, 就不会缩放了.

Scaling.ACTUAL_SIZE