将获取的pdf文件按页拆分:参考https://q.cnblogs.com/q/99944/
pdf文件有多页,第一页需设置横向打印,其他页设置为纵向打印。
PDDocument document = PDDocument.load(new File(filePath)); Splitter splitter = new Splitter(); List<PDDocument> pages = splitter.split(document); ListIterator<PDDocument> iterator = pages.listIterator(); int i = 1; while (iterator.hasNext()) { PrintService service = PrintServiceLookup.lookupDefaultPrintService(); PDDocument pd = iterator.next(); boolean isSuc = PrintUtil.printWithAttributes(pd, service,i); i++; System.out.println(isSuc+"----------------------打印服务"); }
public static boolean printWithAttributes(PDDocument document, PrintService service, int i) { try { PrinterJob job = PrinterJob.getPrinterJob(); //设置打印机 不设置,则使用默认打印机 job.setPrintService(service); PrintRequestAttributeSet attr = new HashPrintRequestAttributeSet(); if (i == 1) { //设置横向打印 attr.add(OrientationRequested.LANDSCAPE); } // attr.add(MediaSizeName.ISO_A5); //设置纸张类型 print(document, job, attr); return true; } catch (Exception e) { return false; } } private static void print(PDDocument document, PrinterJob job, PrintRequestAttributeSet attr) throws IOException, PrinterException { PDFPrintable printable = new PDFPrintable(document, Scaling.SCALE_TO_FIT); job.setPrintable(printable); job.print(attr); }
<dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.8</version> </dependency>