本文介绍如何使用Spire.Doc for Java打印Word文档到特定的物理打印机或虚拟打印机。
打印到物理打印机
import com.spire.doc.Document;
import com.spire.ms.System.Drawing.Printing.PrinterSettings;
public class PrintWord {
public static void main(String[] args) {
//加载Word文档
Document document = new Document();
document.loadFromFile("C:\\Users\\Administrator\\Desktop\\DocoumentToPrint.docx");
//创建PrinterSettings对象
PrinterSettings printerSettings = new PrinterSettings();
//指定物理打印机名称
printerSettings.setPrinterName("\\\\192.168.1.104\\HP LaserJet P1007");
//设置打印份数
printerSettings.setCopies((short) 1);
//设置打印范围
printerSettings.setFromPage(2);
printerSettings.setToPage(4);
//应用打印设置
document.getPrintDocument().setPrinterSettings(printerSettings);
//执行打印
document.getPrintDocument().print();
}
}
打印到虚拟打印机
import com.spire.doc.Document;
import com.spire.ms.System.Drawing.Printing.PrinterSettings;
public class PrintWord {
public static void main(String[] args) {
//加载Word文档
Document document = new Document();
document.loadFromFile("C:\\Users\\Administrator\\Desktop\\DocumentToPrint.docx");
//创建PrinterSettings对象
PrinterSettings printerSettings = new PrinterSettings();
//指定虚拟打印机
printerSettings.setPrinterName("Microsoft Print to PDF");
//打印到文档
printerSettings.setPrintToFile(true);
//指定打印文档的保存路径和名称
printerSettings.setPrintFileName("output/PrintToPDF.pdf");
//应用打印设置
document.getPrintDocument().setPrinterSettings(printerSettings);
//执行打印
document.getPrintDocument().print();
}
}