java连接打印机打印PDF

核心代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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 <= 0) {
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=0;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,1,false);
in.close();
}
}