更新時間:2022-04-21 11:16:06 來源:動力節(jié)點 瀏覽5870次
Java調(diào)用打印機的步驟是怎樣的?動力節(jié)點小編來告訴大家。
1.獲取PrinterJob
一般都用PrinterJob.lookupPrintServices()來獲取本地配置的打印機列表
public static PrinterJob getPrintServiceByName(String printerName) throws Exception{
PrinterJob job = PrinterJob.getPrinterJob();
// 遍歷查詢打印機名稱
boolean flag = false;
for (PrintService ps : PrinterJob.lookupPrintServices()) {
String psName = ps.toString();
// 選用指定打印機,需要精確查詢打印機就用equals,模糊查詢用contains
if (psName.contains(printerName)) {
flag = true;
job.setPrintService(ps);
break;
}
}
if(!flag){
throw new RuntimeException("打印失敗,未找到名稱為" + printerName + "的打印機,請檢查。");
}
return job;
}
2.設(shè)置PrinterJob紙張樣式
public static void setPageStyle(PDDocument document, PrinterJob job) {
job.setPageable(new PDFPageable(document));
Paper paper = new Paper();
int width = 215;
int height = 170;
// 設(shè)置打印紙張大小
paper.setSize(width,height); // 1/72 inch
// 設(shè)置邊距,單位是像素,10mm邊距,對應 28px
int marginLeft = 1;
int marginRight = 0;
int marginTop = 10;
int marginBottom = 0;
// 設(shè)置打印位置 坐標
paper.setImageableArea(marginLeft, marginRight, width - (marginLeft + marginRight), height - (marginTop + marginBottom));
// custom page format
PageFormat pageFormat = new PageFormat();
pageFormat.setPaper(paper);
// override the page format
Book book = new Book();
// append all pages 設(shè)置一些屬性 是否縮放 打印張數(shù)等
book.append(new PDFPrintable(document, Scaling.ACTUAL_SIZE), pageFormat, 1);
job.setPageable(book);
}
3.打印PDF
public static PDDocument printPdf(String pdfPath, String printerName) throws Exception {
File file = new File(pdfPath);
PDDocument document = PDDocument.load(file);
PrinterJob job = getPrintServiceByName(printerName);
setPageStyle(document, job);
// 開始打印
job.print();
return document;
}
相關(guān)閱讀