直接贴代码
public static void printPdf() throws Exception {
//获取pdf文档流
InputStream in = new FileInputStream("d:\\pdfTest.pdf");
//将pdf加载为PDDocument对象
PDDocument document = PDDocument.load(in);
// 加载成打印文件 Scaling.ACTUAL_SIZE 为指定打印pdf的实际大小
PDFPrintable printable = new PDFPrintable(document,Scaling.ACTUAL_SIZE);
//获取默认的打印机
PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
//创建PrinterJob
PrinterJob job = PrinterJob.getPrinterJob();
//将PrinterJob指定打印机
job.setPrintService(printService);
//set 打印文件的对象
job.setPrintable(printable);
//设置打印份数
job.setCopies(1);
job.print();
}
自定义纸张规格写法
public static void printPdf(double width, double height) throws Exception {
InputStream in = new FileInputStream("d:\\de.pdf");
PDDocument document = PDDocument.load(in);
//获取默认的打印机
PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
// 加载成打印文件
PDFPrintable printable = new PDFPrintable(document,Scaling.SCALE_TO_FIT);
Book book = new Book();
Paper paper = new Paper();
paper.setSize(width, height);
// 自定义页面设置
PageFormat pageFormat = new PageFormat();
// 设置打印页面横纵向
//pageFormat.setOrientation(PageFormat.PORTRAIT);
pageFormat.setPaper(paper);
book.append(printable, pageFormat);
PrinterJob job = PrinterJob.getPrinterJob();
//设置带打印格式的打印文件
job.setPageable(book);
job.setPrintService(printService);
job.setPrintable(printable);
job.print();
}
本人小白一个,有不足之处欢迎指正