Java 打印Word文檔

本文介紹如何在Java程序中經過物理打印機和虛擬打印機來打印Word文檔的方法。文中使用了類庫Spire.Doc for Java,可經過官網下載jar文件並導入程序或者直接經過maven倉庫安裝導入html

【示例1】經過物理打印機打印java

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】經過虛擬打印機打印maven

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

 

 

(本文完)spa

相關文章
相關標籤/搜索