DEV Community

jelizaveta
jelizaveta

Posted on

Easily Handle Word Document Printing with Java

Implementing direct printing functionality for Word documents in Java applications is a common requirement for many enterprise-level applications. This article will detail how to use the Spire.Doc for Java library in conjunction with the java.awt.print package from the Java Standard Library to achieve a complete solution for loading Word documents and printing them to a specified printer.

Preparation

First, ensure that the necessary dependencies are already introduced into your project. Spire.Doc for Java is a powerful Word document processing library that supports document creation, editing, conversion, and printing. You can add this library via Maven or by manually downloading it. Meanwhile, java.awt.print is part of the Java Standard Library and requires no additional installation.

xml

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>14.1.3</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Next, ensure that your system can recognize the printer to be used, which can be tested via the printer control panel.

Code Implementation

The following is a complete example code demonstrating how to print a Word document using Java:

java

import com.spire.doc.Document;
import javax.print.PrintService;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

public class PrintWithSpecifiedPrinter {

    public static void main(String[] args) throws PrinterException {

        // Create a PrinterJob object, initially associated with the default printer
        PrinterJob printerJob = PrinterJob.getPrinterJob();

        // Specify the printer name
        PrintService myPrintService = findPrintService("\\\\192.168.1.104\\HP LaserJet P1007");
        printerJob.setPrintService(myPrintService);

        // Create a PageFormat instance and set the default size and orientation
        PageFormat pageFormat = printerJob.defaultPage();

        // Return a copy of the Paper object associated with this PageFormat
        Paper paper = pageFormat.getPaper();

        // Set the printable area of the Paper
        paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());
        pageFormat.setPaper(paper);

        // Create a document object
        Document document = new Document();

        // Load the Word document from a file
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx");

        // Set the format for the document to be printed
        printerJob.setPrintable(document, pageFormat);

        // Execute the print operation
        try {
            printerJob.print();
        } catch (PrinterException e) {
            e.printStackTrace();
        }
    }

    // Find the print service
    private static PrintService findPrintService(String printerName) {
        PrintService[] printServices = PrinterJob.lookupPrintServices();
        for (PrintService printService : printServices) {
            if (printService.getName().equals(printerName)) {
                return printService;
            }
        }
        return null;
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation

  1. Create PrinterJob object :
    • Use PrinterJob.getPrinterJob() to initialize a default print job.
  2. Find print service :
    • The findPrintService method iterates through all print services in the system and matches the specified printer name.
  3. Define paper format :
    • Use the PageFormat and Paper classes to set the paper size and printable area.
  4. Load Word document :
    • Use the Document class from Spire.Doc to load the Word document from the specified path.
  5. Print document :
    • Use printerJob.print() to execute the print operation. Also, handle potential PrinterException errors.

Conclusion

By following the above steps, you can easily integrate printing functionality into your Java applications. By leveraging the Spire.Doc for Java and java.awt.print libraries, you can achieve automatic printing of Word documents, enhancing user experience and work efficiency. During development, be sure to ensure the printer connection is normal and the file paths are correct to avoid runtime errors.

Top comments (0)