4

java连接打印机打印PDF

 2 years ago
source link: https://wakzz.cn/2018/03/02/java/java%E8%BF%9E%E6%8E%A5%E6%89%93%E5%8D%B0%E6%9C%BA%E6%89%93%E5%8D%B0PDF/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

java连接打印机打印PDF

祈雨的博客
2018-03-02

核心代码:

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();
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK