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