DEV Community

Jack9012
Jack9012

Posted on

How to Print PDFs in Java: Silent Printing and Print Dialog Selection

PDF printing is a common business requirement in daily Java backend and desktop development scenarios, such as report printing, document slip printing, and document archiving printing. Java natively provides the core printing API java.awt.print. However, this native API cannot directly parse and render PDF documents. Third-party PDF parsing libraries are required to work alongside it to achieve full printing capabilities.

Print PDF Documents with Java

This article combines two technologies: Spire.PDF for Java (for PDF parsing and rendering) and java.awt.print (for system print job scheduling). It implements two mainstream PDF printing scenarios: silent printing to the default printer without pop-up windows, and printing with a dialog for manual printer selection. Complete runnable code and detailed explanations of underlying principles are provided.

1. Tech Stack and Environment Setup

1.1 Core Dependency Overview

  • java.awt.print : The built-in JDK printing toolkit with no extra dependencies required. It is mainly responsible for retrieving system printers, configuring print page formats, scheduling print jobs, and catching printing exceptions. It serves as the foundational core for Java printing functions.
  • Spire.PDF for Java : A professional PDF parsing library used to load local PDF files and render PDF page content. It adapts to the print rendering interface of the native printing API and addresses the limitation that vanilla Java cannot print PDFs directly.

1.2 Project Dependency Configuration

For Maven projects, add the Spire.PDF dependency in pom.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.pdf</artifactId>
        <version>12.9.0</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

2. Scenario 1: Silent Printing to Default Printer (No Print Dialog)

This scenario applies to background automatic printing with no manual intervention . The system directly sends print jobs to the default printer without popping up any print configuration windows, running silently throughout the process.

Core implementation logic: Obtain the system default print job via PrinterJob, customize the printable area of the print page, load the PDF document and bind it to the print job, then trigger printing directly.

Full Runnable Code

import com.spire.pdf.PdfDocument;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
/**
 * PDF Silent Printing (Default Printer, No Dialog)
 */
public class PrintWithDefaultPrinter {
    public static void main(String[] args) {
        // 1. Get print job object for the system default printer
        PrinterJob printerJob = PrinterJob.getPrinterJob();
        // 2. Initialize page format and retrieve default page size and orientation
        PageFormat pageFormat = printerJob.defaultPage();
        // 3. Get paper object for the page and customize printable area
        Paper paper = pageFormat.getPaper();
        // Set full printable area of the paper (remove default margins to fit full PDF page)
        paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());
        // Bind customized paper settings to page format
        pageFormat.setPaper(paper);
        // 4. Load local PDF document
        PdfDocument pdf = new PdfDocument();
        // Replace with your actual local PDF file path
        pdf.loadFromFile("input.pdf");
        // 5. Bind PDF document with page format to prepare print rendering
        printerJob.setPrintable(pdf, pageFormat);
        // 6. Execute silent print job
        try {
            printerJob.print();
            System.out.println("PDF silent print job completed");
        } catch (PrinterException e) {
            e.printStackTrace();
            System.err.println("PDF silent printing failed: " + e.getMessage());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Key Code Explanations

  • PrinterJob.getPrinterJob(): Retrieves the system default print job instance and automatically binds to the machine’s default printer.
  • paper.setImageableArea(): Resets the paper printable area and removes default margin padding, preventing incomplete PDF output or excessive white space on printed pages.
  • printerJob.print(): Triggers the print job directly with no interactive dialog, ideal for automated printing workflows.

3. Scenario 2: Printing with Dialog Popup (Manual Printer Configuration)

This scenario is suitable for cases where users need to select printers and adjust print parameters . After the program starts, the native system print dialog opens. Users may switch printers, set print copies, page ranges, portrait/landscape orientation and other parameters before confirming to print.

Core implementation logic: Based on the silent printing logic, add a print dialog check. The print job will only execute after user confirmation, offering greater flexibility.

Full Runnable Code

import com.spire.pdf.PdfDocument;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
/**
 * PDF Printing with Dialog (Manual Printer Selection & Parameter Configuration)
 */
public class PrintWithPrintDialog {
    public static void main(String[] args) {
        // 1. Initialize print job
        PrinterJob printerJob = PrinterJob.getPrinterJob();
        // 2. Configure print page and paper format
        PageFormat pageFormat = printerJob.defaultPage();
        Paper paper = pageFormat.getPaper();
        paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());
        pageFormat.setPaper(paper);
        // 3. Load local PDF file
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("input.pdf");
        // 4. Bind PDF document and print format
        printerJob.setPrintable(pdf, pageFormat);
        // 5. Bring up system print dialog and check user confirmation
        if (printerJob.printDialog()) {
            try {
                // Execute printing after user confirmation
                printerJob.print();
                System.out.println("PDF print job with dialog completed");
            } catch (PrinterException e) {
                e.printStackTrace();
                System.err.println("PDF printing with dialog failed: " + e.getMessage());
            }
        } else {
            System.out.println("User cancelled the print job");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Key Code Explanations

  • printerJob.printDialog(): Launches the native system print dialog and returns a boolean value. true means the user confirms printing; false means the user cancels.
  • All print parameters (printer selection, copy count, page numbers) are configured via the system dialog instead of hardcoding in code, accommodating diverse printing requirements.
  • Custom printable area configuration is retained to ensure complete and intact PDF print layout.

4. Common Issues and Notes

4.1 File Path Compatibility

The example uses Windows absolute paths. When deployed on Linux or macOS, modify the paths to match the target operating system and ensure the application has read permissions for the PDF file.

4.2 Incomplete Printed Content / Excessive White Margins

The primary solution is the paper.setImageableArea() method shown in code. It resets the printable area and overrides default system margin restrictions to match the original PDF dimensions.

4.3 Print Exception Handling

PrinterException is caught in the code, which can capture printing failures such as offline printers, out-of-paper status, or corrupted files, enabling business-layer alerting and logging.

5. Summary

This article implements two core PDF printing solutions in Java using the native java.awt.print API together with Spire.PDF:

  1. Silent Printing : No dialog window, fully automatic execution for background automated printing tasks.
  2. Dialog-Based Printing : Supports manual parameter configuration with high flexibility for user-initiated printing on the frontend.

Both code samples are concise, reusable and free of redundant logic. They can be directly adopted in Java desktop and backend projects. The implementation solves the core limitation that native Java cannot print PDFs directly while ensuring reliable and complete print layout rendering.

Top comments (0)