푸터 콘텐츠로 바로가기
JAVA용 IRONPDF 사용

Java에서 PNG를 PDF로 변환하는 방법(튜토리얼)

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.

자주 묻는 질문

Java에서 PNG 이미지를 PDF로 변환하려면 어떻게 해야 하나요?

IronPDF의 fromImage 메서드를 사용하여 Java에서 PNG 이미지를 PDF로 변환할 수 있습니다. 먼저 이미지 경로를 목록에 추가하고 메서드에 전달합니다. 그런 다음 saveAs 메서드를 사용하여 출력을 저장합니다.

Java를 사용하여 여러 개의 PNG 이미지를 하나의 PDF로 변환할 수 있나요?

예, IronPDF를 사용하면 여러 개의 PNG 이미지를 하나의 PDF 문서로 변환할 수 있습니다. 디렉터리에서 이미지 경로를 수집하여 에서이미지 메서드에 전달하려면 DirectoryStream를 사용하세요.

Java에서 PNG 파일을 PDF로 변환하려면 어떤 단계가 필요하나요?

IronPDF를 사용하여 PNG 파일을 PDF로 변환하려면 Java 개발 키트(JDK), Maven을 설치하고 프로젝트의 종속성에 IronPDF를 추가하세요. 이미지를 변환하려면 fromImage 메서드를 사용하고 PDF를 저장하려면 saveAs를 사용합니다.

IronPDF는 Java 개발에 무료로 사용할 수 있나요?

Java용 IronPDF는 개발 중에는 무료로 사용할 수 있지만 배포를 위해서는 상용 라이선스가 필요합니다. 테스트를 위해 정식 버전의 무료 평가판을 사용할 수 있습니다.

Java 프로젝트에서 IronPDF를 사용하기 위한 전제 조건은 무엇인가요?

Java 프로젝트에서 IronPDF를 사용하려면 JDK(Java 개발 키트), Maven 및 IronPDF Java 라이브러리가 필요합니다. 프로젝트의 pom.xml 파일에 IronPDF 종속성을 추가하세요.

IronPDF는 Java 개발자를 위해 어떤 기능을 제공하나요?

Java용 IronPDF는 이미지와 HTML을 PDF로 변환하고, 양식 구성 요소를 편집하고, 서식을 잃지 않고 이미지와 텍스트의 고품질 렌더링을 보장하는 등의 기능을 제공합니다.

IronPDF는 PDF 문서의 이미지 렌더링을 어떻게 처리하나요?

IronPDF는 PDF 문서에서 고품질 이미지 렌더링을 제공하여 모든 이미지와 텍스트가 원래 서식과 품질을 유지하도록 보장합니다.

Java를 사용하여 이미지를 변환할 때 고품질 PDF를 보장하려면 어떻게 해야 하나요?

IronPDF는 서식을 잃지 않고 이미지와 텍스트를 정확하게 렌더링하여 고품질 PDF 출력을 보장합니다. 변환하는 동안 품질을 유지하려면 에서 이미지로 메서드를 사용하세요.

IronPDF로 Java 프로젝트를 설정할 때 Maven의 역할은 무엇인가요?

Maven은 Java 프로젝트에서 IronPDF를 비롯한 종속성을 관리하는 데 사용됩니다. 쉽게 통합하고 업데이트할 수 있도록 pom.xml에 IronPDF를 종속 요소로 추가하세요.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.