Saltar al pie de página
USANDO IRONPDF PARA JAVA

Cómo Convertir PNG a PDF en Java (Tutorial)

This article will use IronPDF for Java library to create PDF documents from image file formats programmatically.

IronPDF - A Java Library

Iron Software engineers have now developed IronPDF Library for Java, which helps Java developers create new documents, edit, write, resize, and manipulate PDF documents. IronPDF allows working with every aspect of a PDF file or PDF conversion. It provides developers with a wide range of features for creating and customizing PDFs in Java. It also helps control the layout and formatting of PDFs.

IronPDF for Java is built on the capabilities of the .NET Framework, making it a versatile tool for working with PDFs compared to other open-source libraries. In addition to creating and manipulating PDFs, it primarily helps convert images and HTML files to PDF and other file formats as well.

Steps to Convert PNG to PDF in Java

Prerequisites

To create a PNG to PDF conversion application, you will need the following prerequisites downloaded and installed:

  1. Java Development Kit (JDK): The latest version of JDK must be installed on your computer to compile and run the convert PNG to PDF application. The JDK can be downloaded from the Oracle website.
  2. Maven: Maven needs to be installed as it is a build automation tool used primarily for Java projects. Maven can be downloaded from the Apache Maven website.
  3. IronPDF Java Library: Now you will need the latest version of IronPDF added as a dependency to your PNG to PDF conversion project. Add the following IronPDF dependency to your project's pom.xml file:

    <dependency>
      <groupId>com.ironsoftware</groupId>
      <artifactId>ironpdf-java</artifactId>
      <version>VERSION_NUMBER</version>
    </dependency>
    <dependency>
      <groupId>com.ironsoftware</groupId>
      <artifactId>ironpdf-java</artifactId>
      <version>VERSION_NUMBER</version>
    </dependency>
    XML
  4. You will also need to add the Slf4j dependency in the pom.xml file.

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>2.0.5</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>2.0.5</version>
    </dependency>
    XML

Once all the prerequisites are downloaded and installed, the project can now be used to convert PNG images to PDF documents in Java applications.

Add Imports to Java Main File

First of all, you will need the following imports for converting PNG images to PDF files using IronPDF in your Java application.

import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;
JAVA

Once the imports are added, you are good to go with the image-to-PDF conversion.

Convert Single PNG to PDF File

IronPDF helps developers convert a single PNG or JPG image to a PDF file with a few simple steps. The Java code snippet is shown in the following example:

// Create a list to hold the path of the image to be converted
List<Path> paths = new ArrayList<>();
paths.add(Paths.get("example.png")); // Add image path to the list

// Create a PDF document from the image and save the PDF
PdfDocument.fromImage(paths).saveAs(Paths.get("example.pdf"));
// Create a list to hold the path of the image to be converted
List<Path> paths = new ArrayList<>();
paths.add(Paths.get("example.png")); // Add image path to the list

// Create a PDF document from the image and save the PDF
PdfDocument.fromImage(paths).saveAs(Paths.get("example.pdf"));
JAVA

Here, you first need to get the path of the image file that you are trying to convert to PDF. Then, you add that image path to a List and call the fromImage method. Finally, call the saveAs method to save the converted PNG file to the filesystem.

Convert Multiple PNGs into a PDF File

IronPDF also allows developers to combine multiple PNG or JPG images into a single PDF document, as shown in the following code example.

// Define the directory containing images to convert
Path imageDirectory = Paths.get("assets/images");

// Create an empty List to hold image Paths
List<Path> imageFiles = new ArrayList<>();

// Populate the List with images' paths from the directory using DirectoryStream
try (DirectoryStream<Path> stream = Files.newDirectoryStream(imageDirectory, "*.{png, jpg, gif}")) {
    for (Path entry : stream) {
        imageFiles.add(entry); // Add image file path to the list
    }

    // Create a PDF document from all images and save it
    PdfDocument.fromImage(imageFiles).saveAs(Paths.get("multiple_images.pdf"));
} catch (IOException exception) {
    throw new RuntimeException(String.format("Error converting images to PDF from directory: %s: %s",
            imageDirectory,
            exception.getMessage()),
            exception);
}
// Define the directory containing images to convert
Path imageDirectory = Paths.get("assets/images");

// Create an empty List to hold image Paths
List<Path> imageFiles = new ArrayList<>();

// Populate the List with images' paths from the directory using DirectoryStream
try (DirectoryStream<Path> stream = Files.newDirectoryStream(imageDirectory, "*.{png, jpg, gif}")) {
    for (Path entry : stream) {
        imageFiles.add(entry); // Add image file path to the list
    }

    // Create a PDF document from all images and save it
    PdfDocument.fromImage(imageFiles).saveAs(Paths.get("multiple_images.pdf"));
} catch (IOException exception) {
    throw new RuntimeException(String.format("Error converting images to PDF from directory: %s: %s",
            imageDirectory,
            exception.getMessage()),
            exception);
}
JAVA

The fromImage method in the above code can also accept a list of PNG image path objects. Each path object references a valid path to an image stored locally. In this case, the images are from the same directory, so a DirectoryStream found in java.nio.file classes is used to build up a list of all the images contained in the directory.

Now, the fromImage method will render each PNG or JPG image present in the list on a separate page of the PDF document. Finally, use the saveAs method to save the converted images to the multiple_images.pdf output.

After running the project with any of the above code examples, the output is generated in PDF file format. Here, the output shown is from the "Convert PNG to PDF" Multiple Images.

How to Convert PNG to PDF in Java (Tutorial), Figure 1: PNG to PDF Output

PNG to PDF Output

You can check further code examples on image conversion with IronPDF and also download IronPDF for Java from the IronPDF Official Website.

How to Convert PNG to PDF in Java (Tutorial), Figure 2: IronPDF for Java IronPDF for Java

IronPDF has a great quality of rendering all images and text without losing any format. Form components in PDFs are also editable in the converted PDF file.

Summary

This article demonstrates how to generate PDFs using the convert image to PDF feature of IronPDF. In conclusion, IronPDF is a powerful library developed for Java developers to work with the PDF file format. It allows developers to easily create PDF documents from Multiple Images from scratch. It also supports XML documents to PDF along with HTML and image files. IronPDF is a great PDF API that helps Software Engineers extract and write content from PDF files.

IronPDF for Java is free to use, but for deployment purposes, it has a commercial license starting from $liteLicense. You can also access the free trial of the full version of IronPDF to test its functionality in production mode.

Preguntas Frecuentes

¿Cómo puedo convertir una imagen PNG a PDF en Java?

Puedes convertir una imagen PNG a un PDF en Java usando el método fromImage de IronPDF. Primero, añade la ruta de la imagen a una lista y pásala al método. Luego, guarda el resultado usando el método saveAs.

¿Puedo convertir múltiples imágenes PNG a un solo PDF usando Java?

Sí, IronPDF te permite convertir múltiples imágenes PNG en un único documento PDF. Usa un DirectoryStream para reunir las rutas de las imágenes desde un directorio y pásalas al método fromImage.

¿Qué pasos se necesitan para convertir archivos PNG a PDF en Java?

Para convertir archivos PNG a PDF usando IronPDF, instala el Kit de Desarrollo de Java (JDK), Maven, y agrega IronPDF a las dependencias de tu proyecto. Usa el método fromImage para convertir imágenes y saveAs para guardar el PDF.

¿Es IronPDF gratuito para usar en desarrollo Java?

IronPDF for Java es gratis de usar durante el desarrollo pero requiere una licencia comercial para el despliegue. Está disponible una prueba gratuita de la versión completa para pruebas.

¿Cuáles son los requisitos previos para usar IronPDF en un proyecto Java?

Para usar IronPDF en un proyecto Java, necesitas el Kit de Desarrollo de Java (JDK), Maven, y la biblioteca Java de IronPDF. Añade la dependencia de IronPDF al archivo pom.xml de tu proyecto.

¿Qué características ofrece IronPDF para desarrolladores Java?

IronPDF for Java ofrece características como la conversión de imágenes y HTML a PDF, la edición de componentes de formularios, y asegura una representación de alta calidad de imágenes y texto sin perder el formato.

¿Cómo maneja IronPDF la representación de imágenes en documentos PDF?

IronPDF proporciona una representación de imagen de alta calidad en documentos PDF, asegurando que todas las imágenes y textos mantengan su formato y calidad originales.

¿Cómo puedo asegurar la calidad alta de los PDFs al convertir imágenes usando Java?

IronPDF garantiza un resultado en PDF de alta calidad al representar con precisión imágenes y texto sin perder el formato. Usa el método fromImage para mantener la calidad durante la conversión.

¿Cuál es el papel de Maven en la configuración de un proyecto Java con IronPDF?

Maven se usa para gestionar las dependencias, incluyendo IronPDF, en tu proyecto Java. Añade IronPDF como una dependencia en tu pom.xml para facilitar la fácil integración y actualizaciones.

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