核心代碼:
public class PrintService {
private static final Logger logger = LoggerFactory.getLogger(PrintService.class);
/**
* 列印
* @param in 檔案流
* @param isDuplex 是否雙頁列印
* @param copies 份數
* @param isPortrait 是否豎打
* @throws Exception
*/
public void print(InputStream in,boolean isDuplex,int copies,boolean isPortrait) throws Exception {
if(in == null) {
throw new TXException("檔案流為空");
}
if(copies <= ) {
throw new TXException("列印份數不應小于0");
}
logger.info("列印檔案: 是否雙頁列印: "+isDuplex+",份數: "+copies+"是否豎打"+isPortrait);
try(PDDocument document = PDDocument.load(in);) {
Book book =new PDFPageable(document);
PrinterJob job = PrinterJob.getPrinterJob();
job.setPageable(book);
HashPrintRequestAttributeSet pars = new HashPrintRequestAttributeSet();
pars.add(MediaName.ISO_A4_WHITE);
// 是否雙頁列印
if(isDuplex) {
if(isPortrait){
// 正常的豎直雙面列印
pars.add(Sides.DUPLEX);
} else {
// 水準雙面列印,雙面長邊反轉列印
pars.add(Sides.TWO_SIDED_LONG_EDGE);
}
}
// 設定成橫/豎列印
if(isPortrait){
pars.add(OrientationRequested.PORTRAIT);
} else {
pars.add(OrientationRequested.LANDSCAPE);
}
// 列印範圍,列印1-2頁
//pars.add(new PageRanges(1, 2));
// 多份列印
for(int i=;i<copies;i++) {
job.print(pars);
}
} catch (Exception e) {
throw e;
}
}
public static void main(String[] args) throws Exception {
InputStream in = new FileInputStream("D:/test.pdf");
new PrintService().print(in, false,,false);
in.close();
}
}