Cómo Imprimir Archivos PDF en Java

How To Print PDF Files Using Java

This article was translated from English: Does it need improvement?
Translated
View the article in English

Introduction

PDF is important in Java applications because it allows developers to create and manipulate PDF documents in a platform-independent manner. The PDF format is widely used for storing and sharing documents, so being able to work with it is important for many Java applications that deal with document management or document-based workflows.

There are several ways to generate and print PDF files in Java. A common approach is to use a library that provides classes for creating and manipulating PDF documents. This How-to Guide will show how to use the IronPDF library to generate and print PDF files in Java applications.


IronPDF: Java PDF Library

IronPDF is a Java library that can be used to generate, manipulate, and convert PDF documents. It is based on the IronPDf C# .NET library, which provides a similar set of features for the .NET platform.

IronPDF provides a high-level API for working with PDF documents, allowing developers to work with PDF files without having to deal with the low-level details of the file type. It supports common PDF operations such as creating new documents, adding content, formatting text, and merging PDF files, and splitting PDF files.

IronPDF provides support for converting HTML, CSS, and JavaScript code to PDF, making it easy to generate PDF files from web pages or HTML templates. It also offers the option to print PDF documents.

Steps to Print a PDF Document Using IronPDF Java

Prerequisites

To print PDF files in Java, there are some prerequisites:

  1. Eclipse IDE or any other Java IDE
  2. A Maven Project running in Eclipse or in any other IDE
  3. A stable internet connection to install the IronPDF Java library

Install IronPDF Library in Maven Project

To install IronPDF in a Maven project, you need to add the IronPDF dependency to your project's pom.xml file.

Add the following dependencies to the <dependencies> section of the pom.xml file:

<dependency>
    <groupId>com.ironsoftware</groupId>
    <artifactId>ironpdf</artifactId>
    <version>YOUR_VERSION_HERE</version>
</dependency>
<dependency>
    <groupId>com.ironsoftware</groupId>
    <artifactId>ironpdf</artifactId>
    <version>YOUR_VERSION_HERE</version>
</dependency>
XML

After adding the dependencies to the pom.xml file, run the mvn install command in the terminal, or press Ctrl+S to download and install IronPDF in your Maven project.

Before we can start using IronPDF, you must first import the IronPDF classes in the main App.java source file, as found in the src folder.

Java Print PDFs - Figure 1: Package explorer tree for ironpdf-java

Package Explorer Tree for IronPDF for Java

Open the "App.java" file and add the IronPDF package by using the following import statement.

import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.*;
JAVA

Load a PDF in a Java Application

IronPDF for Java provides a constructor for loading PDF content into the library. Valid arguments that this constructor can accept include a byte array and a file path. For password-protected documents, a third parameter containing the password for the PDF file can also be provided.

The code snippet below loads a PDF located on the filesystem.

// Set the license key for IronPDF
License.setLicenseKey("Enter-Your-License");  

// Load PDF from the filesystem
PdfDocument pdf = new PdfDocument(Paths.get("MyPdf.pdf"));
// Set the license key for IronPDF
License.setLicenseKey("Enter-Your-License");  

// Load PDF from the filesystem
PdfDocument pdf = new PdfDocument(Paths.get("MyPdf.pdf"));
JAVA

Print a PDF Document With Default Settings

IronPDF provides two ways to print PDF files. The first way is to print the document immediately using default printer and page settings. You can use the printWithoutDialog method to perform this action.

// Print PDF document using default printer settings without showing a print dialog
pdf.printWithoutDialog();
// Print PDF document using default printer settings without showing a print dialog
pdf.printWithoutDialog();
JAVA

The Print Dialog

The second way is to allow the user to specify printing options prior to printing. You can achieve this functionality using the print method.

// Display print dialog to let the user specify printing options
pdf.print();
// Display print dialog to let the user specify printing options
pdf.print();
JAVA

The print dialog window will appear when this method is invoked, allowing the user to change the printer, set paper size, change the number of copies, etc.

Java Print PDFs - Figure 2: Print dialog shown after running the program using print()

Print dialog shown after running the program using the print() method

Full Source Code

The complete source file used in this How-To Guide is below.

package IronPDF.ironpdf_java;

// Import statement for IronPDF Java
import com.ironsoftware.ironpdf.*;
import java.awt.print.PrinterException;
import java.io.IOException;
import java.nio.file.Paths;

public class App {
    public static void main(String[] args) throws PrinterException, IOException {
        // Apply your license key
        License.setLicenseKey("Enter-Your-License");

        // Load PDF document from the file system
        PdfDocument pdf = new PdfDocument(Paths.get("MyPdf.pdf"));

        // Print the PDF document without displaying a print dialog
        pdf.printWithoutDialog();

        // Display the print dialog for the user to configure printing options
        pdf.print();
    }
}
package IronPDF.ironpdf_java;

// Import statement for IronPDF Java
import com.ironsoftware.ironpdf.*;
import java.awt.print.PrinterException;
import java.io.IOException;
import java.nio.file.Paths;

public class App {
    public static void main(String[] args) throws PrinterException, IOException {
        // Apply your license key
        License.setLicenseKey("Enter-Your-License");

        // Load PDF document from the file system
        PdfDocument pdf = new PdfDocument(Paths.get("MyPdf.pdf"));

        // Print the PDF document without displaying a print dialog
        pdf.printWithoutDialog();

        // Display the print dialog for the user to configure printing options
        pdf.print();
    }
}
JAVA

Learn more about PDF Printing in Java using the IronPDF library.

Summary

In conclusion, IronPDF is a powerful and easy-to-use library for printing PDFs in Java applications. With its rich set of features and extensive documentation, IronPDF makes it simple to generate and customize professional-quality PDFs that can be printed or shared with others. Whether you need to create invoices, reports, or any other type of document, IronPDF has you covered.

IronPDF offers a free trial for testing in production. Pricing of IronPDF starts from $799. Give IronPDF a try and see how it can help you streamline your PDF printing workflow.

Preguntas Frecuentes

¿Cómo puedo imprimir archivos PDF usando Java?

Puedes usar IronPDF for Java para imprimir archivos PDF utilizando la clase PdfDocument. Esto te permite cargar un archivo PDF e imprimirlo usando printWithoutDialog para configuraciones predeterminadas o print para opciones de impresión personalizadas.

¿Qué pasos se necesitan para instalar la biblioteca para imprimir PDFs en Java?

Para instalar IronPDF en un proyecto Maven, agrega la dependencia de IronPDF a tu archivo pom.xml bajo la sección <dependencies>, luego ejecuta mvn install en tu terminal.

¿Puede IronPDF convertir contenido HTML en un documento PDF en Java?

Sí, IronPDF puede convertir HTML, CSS y JavaScript en archivos PDF, lo que facilita la creación de PDFs a partir de páginas web o plantillas HTML.

¿Qué características ofrece la biblioteca Java para la manipulación de PDFs?

IronPDF proporciona características como creación de PDF, manipulación, conversión de HTML a PDF, fusión y división de documentos, y opciones de impresión personalizables.

¿Qué requisitos previos se necesitan para imprimir PDFs usando IronPDF en Java?

Necesitas un IDE de Java como Eclipse, una configuración de proyecto Maven y una conexión a internet para instalar IronPDF para imprimir PDFs.

¿Cómo puedo cargar y manipular un documento PDF en IronPDF for Java?

Utiliza el constructor PdfDocument en IronPDF para cargar documentos PDF, ya sea por ruta de archivo o matriz de bytes, con soporte para archivos protegidos con contraseña.

¿IronPDF for Java ofrece una versión de prueba?

Sí, IronPDF ofrece una versión de prueba gratuita para probar sus características en producción antes de adquirir una licencia.

¿Cómo personalizo los ajustes de la impresora al imprimir un PDF?

Usa el método print en IronPDF para mostrar un cuadro de diálogo de impresión, permitiéndote seleccionar opciones de impresora, tamaño de papel y cantidad de copias.

¿Cuál es la función del método printWithoutDialog en IronPDF?

El método printWithoutDialog en IronPDF te permite imprimir documentos PDF inmediatamente usando las configuraciones de la impresora predeterminada sin mostrar un cuadro de diálogo de impresión.

Darrius Serrant
Ingeniero de Software Full Stack (WebOps)

Darrius Serrant tiene una licenciatura en Ciencias de la Computación de la Universidad de Miami y trabaja como Ingeniero de Marketing WebOps Full Stack en Iron Software. Atraído por la programación desde joven, vio la computación como algo misterioso y accesible, convirtiéndolo en el ...

Leer más
¿Listo para empezar?
Versión: 2025.11 recién lanzado