Java 打印Word文档

本文介绍如何在Java程序中通过物理打印机和虚拟打印机来打印Word文档的方法。文中使用了类库Spire.Doc for Java,可通过官网下载jar文件并导入程序或者直接通过maven仓库安装导入

【示例1】通过物理打印机打印

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();
    }
}

 

【示例2】通过虚拟打印机打印

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();
    }
}

 

 

(本文完)

posted @ 2019-11-04 14:37  E-iceblue  阅读(4909)  评论(0编辑  收藏  举报