打印对象
一份设置为A3纸张, 页面边距为(10, 10, 10, 10)mm的PDF文件.
PageFormat
默认PDFPrintable无法设置页面大小.
1 PDFPrintable printable = new PDFPrintable(document); 2 PrinterJob job = PrinterJob.getPrinterJob(); 3 job.setPrintable(printable);
需要把它放到一个Book中, 再设置即可
1 Book book = new Book(); 2 book.append(printable, pageFormat); 3 printerJob.setPageable(book); 4 printerJob.print();
设置纸张属性
1 Paper paper = new Paper(); 2 paper.setSize(width, height); 3 // 设置边距 4 paper.setImageableArea(marginLeft, marginRight, width - (marginLeft + marginRight), height - (marginTop + marginBottom)); 5 // 自定义页面设置 6 PageFormat pageFormat = new PageFormat(); 7 // 设置页面横纵向 8 pageFormat.setOrientation(PageFormat.PORTRAIT); 9 pageFormat.setPaper(paper);
注意: 这边计量单位都是在dpi 72下的尺寸.
如果拿到是mm, 需要转为px. 例如10mm转换
10 * 72 * 10 / 254 = 28px
如果打印出现了截断, 一般是因为没有添加自定义纸张导致的.
完整代码如下
1 InputStream in = new FileInputStream("d:\a3.pdf"); 2 PDDocument document = PDDocument.load(in); 3 PDFPrintable printable = new PDFPrintable(document, Scaling.ACTUAL_SIZE); 4 5 PrinterJob printerJob = PrinterJob.getPrinterJob(); 6 7 PaperSize a3 = PaperSize.PAPERSIZE_A3; 8 // A3 纸张在72 dpi下的宽高 841 * 1190 9 int width = a3.getWidth().toPixI(72); 10 int height = a3.getHeight().toPixI(72); 11 // 10mm边距, 对应 28px 12 int marginLeft = 28; 13 int marginRight = 28; 14 int marginTop = 28; 15 int marginBottom = 28; 16 17 Paper paper = new Paper(); 18 paper.setSize(width, height); 19 // 设置边距 20 paper.setImageableArea(marginLeft, marginRight, width - (marginLeft + marginRight), height - (marginTop + marginBottom)); 21 // 自定义页面设置 22 PageFormat pageFormat = new PageFormat(); 23 // 设置页面横纵向 24 pageFormat.setOrientation(PageFormat.PORTRAIT); 25 pageFormat.setPaper(paper); 26 27 Book book = new Book(); 28 book.append(printable, pageFormat); 29 printerJob.setPageable(book); 30 printerJob.print();