Tuesday, 15 September 2020 07:08

New method to print Word document in Java

Written by  support iceblue
Rate this item
(0 votes)

This article will demonstrate how to print the word document by PrinterJob class offered by Spire.Doc for Java. We could set the paper size, copies and whether to show print dialog. Here comes to the details:

import com.spire.doc.*;
import java.awt.print.*;
public class WordPrint {

    public static void main(String[] args) throws Exception {
        //Load the sample document
        Document doc = new Document();
        doc.loadFromFile("Sample.docx");

        PrinterJob loPrinterJob = PrinterJob.getPrinterJob();
        PageFormat loPageFormat = loPrinterJob.defaultPage();

        //set the paper size
        Paper loPaper = loPageFormat.getPaper();
        loPaper.setSize(600, 500);
        loPageFormat.setPaper(loPaper);

        //remove the default margin
        loPaper.setImageableArea(0, 0, loPageFormat.getWidth(), loPageFormat.getHeight());
        //set copies
        loPrinterJob.setCopies(1);
        loPrinterJob.setPrintable(doc, loPageFormat);
        //set the print dialog
        if (loPrinterJob.printDialog()) {
            //print the word document
            try {
                loPrinterJob.print();
            } catch (PrinterException e)

            {
                e.printStackTrace();
            }
        }
    }
}
More in this category: « Print Word Documents in Java