JAVA连接打印机打印ADF文件
首先要把需要打印的设备连接到当前的电脑上
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.21</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
/**
* 打印工具类
* @param file 文件路径
* @param printerName 打印机的名称
* @param copies 打印机的份数
* @param duplex 是否双页打印
* @throws Exception
*/
public static void PDFprint(File file , String printerName, Integer copies,boolean duplex) throws Exception {
PDDocument document = null;
try {
document = PDDocument.load(file);
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setJobName(file.getName());
if (printerName != null) {
// 查找并设置打印机
//获得本台电脑连接的所有打印机
PrintService[] printServices = PrinterJob.lookupPrintServices();
if(printServices == null || printServices.length == 0) {
throw new JinJunException("打印失败,未找到可用打印机,请检查。");
}
PrintService printService = null;
//匹配指定打印机
for (int i = 0;i < printServices.length; i++) {
System.out.println(printServices[i].getName());
if (printServices[i].getName().contains(printerName)) {
printService = printServices[i];
break;
}
}
if(printService!=null){
printJob.setPrintService(printService);
}else{
throw new JinJunException("打印失败,未找到名称为 + printerName + 的打印机,请检查。");
}
}
//设置纸张及缩放
PDFPrintable pdfPrintable = new PDFPrintable(document, Scaling.ACTUAL_SIZE);
//设置多页打印
Book book = new Book();
PageFormat pageFormat = new PageFormat();
//设置打印方向
pageFormat.setOrientation(PageFormat.PORTRAIT);//纵向
pageFormat.setPaper(getPaper());//设置纸张
book.append(pdfPrintable, pageFormat, document.getNumberOfPages());
printJob.setPageable(book);
printJob.setCopies(copies);//设置打印份数
//添加打印属性
HashPrintRequestAttributeSet pars = new HashPrintRequestAttributeSet();
if(duplex){
//设置双页打印 (DUPLEX双页)
pars.add(Sides.DUPLEX);
}
printJob.print(pars);
}finally {
if (document != null) {
try {
document.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static Paper getPaper() {
Paper paper = new Paper();
// 默认为A4纸张,对应像素宽和高分别为 595, 842
int width = 595;
int height = 842;
// 设置边距,单位是像素,10mm边距,对应 28px
int marginLeft = 10;
int marginRight = 0;
int marginTop = 10;
int marginBottom = 0;
paper.setSize(width, height);
// 下面一行代码,解决了打印内容为空的问题
paper.setImageableArea(marginLeft, marginRight, width - (marginLeft + marginRight), height - (marginTop + marginBottom));
return paper;
}
public static void main(String[] args) throws Exception {
String pdfFile = "C:\\Users\\86155\\Desktop\\aa.pdf";//文件路径
File file = new File(pdfFile);
String printerName = "Brother DCP-7180DN";//打印机名包含字串
PDFprint(file,printerName,1,false);
}
目前只是本地可以,如果部署到服务器就找不到打印机。有更好的解决方案可以讨论下
版权声明:本文为weixin_45167444原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。