Print Word Document in Java

This article demonstrates how to print a Word document to a specific physical printer or virtual printer by using Spire.Doc for Java.

Print to Physical Printer

import com.spire.doc.Document;
import com.spire.ms.System.Drawing.Printing.PrinterSettings;

public class PrintWord {

    public static void main(String[] args) {

        //load a Word document that you want to print
        Document document = new Document();
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\DocoumentToPrint.docx");

        //create a PrinterSettings object
        PrinterSettings printerSettings = new PrinterSettings();

        //specify printer name
        printerSettings.setPrinterName("\\\\192.168.1.104\\HP LaserJet P1007");

        //set copies to print
        printerSettings.setCopies((short) 1);

        //set the page range to print
        printerSettings.setFromPage(2);
        printerSettings.setToPage(4);

        //apply printer settings
        document.getPrintDocument().setPrinterSettings(printerSettings);

        //execute print
        document.getPrintDocument().print();
    }
}

Print to PDF

import com.spire.doc.Document;
import com.spire.ms.System.Drawing.Printing.PrinterSettings;

public class PrintWord {

    public static void main(String[] args) {

        //load a Word document that you want to print
        Document document = new Document();
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\ToPrint.docx");

        //create a PrinterSettings object
        PrinterSettings printerSettings = new PrinterSettings();

        //specify virtual printer name
        printerSettings.setPrinterName("Microsoft Print to PDF");

        //print to file
        printerSettings.setPrintToFile(true);

        //specify path and name of the printed file
        printerSettings.setPrintFileName("output/PrintToPDF.pdf");

        //apply printer settings
        document.getPrintDocument().setPrinterSettings(printerSettings);

        //execute print
        document.getPrintDocument().print();
    }
}