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

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

创建PDF文件


 

 1     public static byte[] createHelloPDF() {
 2         ByteArrayOutputStream out = new ByteArrayOutputStream();
 3         try {
 4             PDDocument doc = new PDDocument();
 5             PDPage page = new PDPage();
 6             doc.addPage(page);
 7             PDFont font = PDType1Font.HELVETICA_BOLD;
 8             PDPageContentStream content = new PDPageContentStream(doc, page);
 9             content.beginText();
10             content.setFont(font, 20);
11             content.moveTextPositionByAmount(250, 700);
12             content.drawString("Hello Print!");
13 
14             content.endText();
15             content.close();
16             doc.save(out);
17             doc.close();
18         } catch (Exception e) {
19             e.printStackTrace();
20         }
21         return out.toByteArray();
22     }

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

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

 打印文件


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

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

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

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

缩放问题


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

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

 1         public enum Scaling {
 2             // 实际大小
 3             ACTUAL_SIZE,
 4             // 缩小
 5             SHRINK_TO_FIT,
 6             // 拉伸
 7             STRETCH_TO_FIT,
 8             // 适应
 9             SCALE_TO_FIT;
10 
11             private Scaling() {
12             }
13         }

 

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

Scaling.ACTUAL_SIZE

posted @ 2017-11-28 17:09  大道方圆  阅读(7002)  评论(0编辑  收藏  举报