打印對象
一份設置為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();