代码拉取完成,页面将自动刷新
System : Windows 10
Intellij IDEA : Ultimate 2020.3.4
Java : 1.8.0_333
CSDN : https://lijinjiang.blog.csdn.net/article/details/128005123
该项目实现了在CS端调用本地打印机服务打印PDF的功能
Apache PDFbox 是一个开源的、基于 Java 的、支持 PDF 文档生成的工具库,它可以用于创建新的 PDF 文档,修改现有的 PDF 文档,还可以从 PDF 文档中提取所需的内容。Apache PDFBox 还包含了数个命令行工具。可以说,这个开源的工具库的功能是很强大的,在此,我们只研究打印功能
Apache PDFbox 的优点:功能强大,代码开源,较完美的解决了 PDF 格式文件的一系列处理,使用方便
获取了本地的所有打印机服务,并将系统的默认打印机作为首选项
//获取本地的打印服务,并且设置默认打印机
private JComboBox<String> selectPrintService() {
defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();//获取默认打印机
JComboBox<String> comboBox = new JComboBox<>();
//获得本台电脑连接的所有打印机
PrintService[] printServices = PrinterJob.lookupPrintServices();
if (printServices == null || printServices.length == 0) {
comboBox.addItem("获取本地打印机失败,请联系管理员!");
} else {
for (PrintService printService : printServices) {
String value = printService.getName();
serviceMap.put(value, printService);//将打印机名称及打印机服务添加到集合
comboBox.addItem(value);
//将默认打印机设置为下拉选的默认选择项
if (defaultPrintService != null && defaultPrintService.getName().equals(value)) {
comboBox.setSelectedItem(value);
}
}
}
return comboBox;
}
打印功能实现
public void print(Container parent) {
PDDocument document = null;
File file;
try {
file = new File(filepath);
if (file == null || !file.exists()) {
JOptionPane.showMessageDialog(parent, "要打印的PDF文件不存在!", "警告", JOptionPane.WARNING_MESSAGE);
return;
}
document = PDDocument.load(file);
PrinterJob printerJob = PrinterJob.getPrinterJob();
printerJob.setJobName(file.getName());
printerJob.setPrintService(defaultPrintService);//设置打印机
//设置纸张及缩放
PDFPrintable pdfPrintable = new PDFPrintable(document, scaling);
//设置多页打印
Book book = new Book();
PageFormat pageFormat = new PageFormat();
//设置打印方向
pageFormat.setOrientation(orientation);//纵向
Paper paper = getPaper();
pageFormat.setPaper(paper);
book.append(pdfPrintable, pageFormat, document.getNumberOfPages());
printerJob.setPageable(book);
printerJob.setCopies(copies);//设置打印份数
//添加打印属性
HashPrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
attributes.add(sides); //设置单双页
attributes.add(MediaSizeName.ISO_A4);//默认A4纸打印
printerJob.print(attributes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (document != null) {
try {
document.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private Paper getPaper() {
Paper paper = new Paper();
// 默认为A4纸张,对应像素宽和高分别为 595, 842
int width = 595;
int height = 842;
// 设置边距,单位是像素,10mm边距,对应 28px
int marginLeft = 12;
int marginRight = 12;
int marginTop = 12;
int marginBottom = 12;
paper.setSize(width, height);
// 下面一行代码,解决了打印内容为空的问题
paper.setImageableArea(marginLeft, marginRight, width - (marginLeft + marginRight), height - (marginTop + marginBottom));
return paper;
}
执行界面
选择打印机
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。