本文介绍如何在Java程序中通过物理打印机和虚拟打印机来打印Word文档的方法。文中使用了类库Spire.Doc for Java,可通过官网下载jar文件并导入程序或者直接通过maven仓库安装导入。
【示例1】通过物理打印机打印importcom.spire.doc.Document;
importcom.spire.ms.System.Drawing.Printing.PrinterSettings;
publicclassPrintWord{
publicstaticvoidmain(String[]args){
//加载Word文档
Documentdocument=newDocument();
document.loadFromFile("C:\\Users\\Administrator\\Desktop\\DocoumentToPrint.docx");
//创建PrinterSettings对象
PrinterSettingsprinterSettings=newPrinterSettings();
//指定物理打印机名称
printerSettings.setPrinterName("\\\\192.168.1.104\\HPLaserJetP1007");
//设置打印份数
printerSettings.setCopies((short)1);
//设置打印范围
printerSettings.setFromPage(2);
printerSettings.setToPage(4);
//应用打印设置
document.getPrintDocument().setPrinterSettings(printerSettings);
//执行打印
document.getPrintDocument().print();
}
}
【示例2】通过虚拟打印机打印importcom.spire.doc.Document;
importcom.spire.ms.System.Drawing.Printing.PrinterSettings;
publicclassPrintWord{
publicstaticvoidmain(String[]args){
//加载Word文档
Documentdocument=newDocument();
document.loadFromFile("C:\\Users\\Administrator\\Desktop\\DocumentToPrint.docx");
//创建PrinterSettings对象
PrinterSettingsprinterSettings=newPrinterSettings();
//指定虚拟打印机
printerSettings.setPrinterName("MicrosoftPrinttoPDF");
//打印到文档
printerSettings.setPrintToFile(true);
//指定打印文档的保存路径和名称
printerSettings.setPrintFileName("output/PrintToPDF.pdf");
//应用打印设置
document.getPrintDocument().setPrinterSettings(printerSettings);
//执行打印
document.getPrintDocument().print();
}
}
(本文完)