之前通过网上查询java实现打印机打印功能的方法大部分都是通过SimpleDoc类构件打印机的打印文件属性,通过PrintJob的Print()实现打印,但是打印出来的都是乱码。
首先考虑能不能打印文件,因为程序部署在服务器端,需要直接控制前端设备打印,所以需要无界面化操作,我使用的代码:
public static void PDFprint(File file, String printerName) 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) {
// System.out.print("打印失败,未找到可用打印机,请检查。");
// return;
// }
PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
// // 匹配指定打印机
// 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 {
System.out.print("打印失败,未找到名称为" + printerName + "的打印机,请检查。");
return;
}
}
// 设置纸张及缩放
PDFPrintable pdfPrintable = new PDFPrintable(document, Scaling.ACTUAL_SIZE);
// 设置多页打印
Book book = new Book();
PageF
Java打印PDF文件

本文介绍了一种使用Java在服务器端实现PDF文件打印的方法,并详细解释了如何通过代码配置打印机、纸张尺寸、方向等参数,同时提供了利用POI生成PDF文件的实用工具类。
最低0.47元/天 解锁文章
696





