本文介绍如何使用Spire.Doc for Java打印Word文档到特定的物理打印机或虚拟打印机。
打印到物理打印机
import com.spire.doc.*;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.*;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.PageRanges;
import java.awt.print.*;
public class PrintWord {
public static void main(String[] args) {
//加载Word文档
Document document = new Document();
document.loadFromFile("C:\\Users\\Administrator\\Desktop\\DocoumentToPrint.docx");
// 创建打印任务
PrinterJob loPrinterJob = PrinterJob.getPrinterJob();
// 获取默认纸张格式
PageFormat loPageFormat = loPrinterJob.defaultPage();
// 获取纸张
Paper loPaper = loPageFormat.getPaper();
// 删除默认页边距
loPaper.setImageableArea(0,0,loPageFormat.getWidth(),loPageFormat.getHeight());
// 设置纸张
loPageFormat.setPaper(loPaper);
loPrinterJob.setPrintable(document,loPageFormat);
// 指定你想使用的打印机名称(必须是系统中已安装的打印机)
String targetPrinterName = "Microsoft Print to PDF";
// 获取所有可用的打印服务(打印机)
PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
PrintService targetService = null;
for (PrintService service : printServices) {
if (service.getName().trim().equals(targetPrinterName)) {
targetService = service;
break;
}
}
if (targetService == null) {
System.err.println("未找到名为" + targetPrinterName + " 的打印机。");
System.err.println("可用打印机列表:");
for (PrintService service : printServices) {
System.out.println(" - " + service.getName());
}
return;
}
loPrinterJob.setPrintService(targetService);
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(new PageRanges(2, 4));
aset.add(new Copies(1));
try {
// 打印文档
loPrinterJob.print(aset);
} catch (PrinterException e)
{
e.printStackTrace();
}
// 释放文档资源
document.dispose();
}
}
}







