푸터 콘텐츠로 바로가기
JAVA용 IRONPDF 사용
Windows에서 .NET용 테서랙트 OCR을 사용하는 방법

HTML2PDF Java(코드 예제 튜토리얼)

This article will use IronPDF - a Java library for creating PDF documents programmatically.

IronPDF - A Java Library

Iron Software engineers have now developed IronPDF for Java which helps Java developers to create, edit, and manipulate PDF documents. IronPDF allows you to work with all aspects of PDF files. It offers developers a wide range of features to create and customize PDFs. It also helps to control the layout and formatting of the PDF document.

The main features include the ability to create a PDF file from various sources such as HTML, JavaScript, CSS, XML documents, and various image formats. In addition, IronPDF offers the abilities to add headers and footers to your PDF, create tables in PDFs, include digital signatures, and attachments. It supports complete multithreading and provides even more features!

Steps to Convert HTML to PDF in Java


Prerequisites

To create a PDF Java conversion application, you need to download and install the following prerequisites:

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

    <dependency>
        <groupId>com.ironsoftware</groupId>
        <artifactId>ironpdf</artifactId>
        <version>LATEST_VERSION</version>
    </dependency>
    <dependency>
        <groupId>com.ironsoftware</groupId>
        <artifactId>ironpdf</artifactId>
        <version>LATEST_VERSION</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 HTML files to PDF documents in Java applications.

Adding Necessary Imports and License Key

First, you need to add the IronPDF import to your main Java file where you want to run the code for the PDF converter. You need to import all the required classes, and this can be done with this single line of code:

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

Next, in the main method, enter the license key you obtained at the time of purchase or trial key using the IronPDF setLicenseKey.

// Set the license key for IronPDF. Replace "Your license key" with your actual license key.
License.setLicenseKey("Your license key");
// Set the license key for IronPDF. Replace "Your license key" with your actual license key.
License.setLicenseKey("Your license key");
JAVA

Convert HTML String to PDF

IronPDF can convert HTML content to PDF with simply one line of code.

// Convert an HTML string to a PDF document.
PdfDocument myPdf = PdfDocument.renderHtmlAsPdf("<h1> ~HTML2PDF in JAVA~ </h1> Made with IronPDF!");

// Save the PDF document to a file.
myPdf.saveAs(Paths.get("html_saved.pdf"));
// Convert an HTML string to a PDF document.
PdfDocument myPdf = PdfDocument.renderHtmlAsPdf("<h1> ~HTML2PDF in JAVA~ </h1> Made with IronPDF!");

// Save the PDF document to a file.
myPdf.saveAs(Paths.get("html_saved.pdf"));
JAVA

In the above code, the renderHtmlAsPdf method is used to pass the HTML string that will be converted to a PDF document. Then the saveAs method is called to generate the PDF.

This creates a PDF document named "html_saved.pdf" which contains the HTML content passed as a string.

Convert HTML File to PDF

With the following code, you can convert the HTML file into a PDF document:

// Render the HTML file as a PDF. The resulting PDF is stored in myPdf as a PdfDocument object.
PdfDocument myPdf = PdfDocument.renderHtmlFileAsPdf("example.html");

// Save the PdfDocument to a file.
myPdf.saveAs(Paths.get("html_file_saved.pdf"));
// Render the HTML file as a PDF. The resulting PDF is stored in myPdf as a PdfDocument object.
PdfDocument myPdf = PdfDocument.renderHtmlFileAsPdf("example.html");

// Save the PdfDocument to a file.
myPdf.saveAs(Paths.get("html_file_saved.pdf"));
JAVA

Here, the renderHtmlFileAsPdf method is used to convert an HTML file into a PDF file. CSS and JavaScript can also be rendered along with the HTML file, preserving the layout and formatting of the HTML file.

Convert HTML URL to PDF

Sometimes you want to create PDF files directly from a web page. For this purpose, the IronPDF library provides the method renderUrlAsPdf to convert HTML from a URL to PDF. So the URL is used as an argument to the method.

// Render the HTML content from a URL as a PDF. The resulting PDF is stored in myPdf as a PdfDocument object.
PdfDocument myPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");

// Save the PdfDocument to a file.
myPdf.saveAs(Paths.get("url.pdf"));
// Render the HTML content from a URL as a PDF. The resulting PDF is stored in myPdf as a PdfDocument object.
PdfDocument myPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");

// Save the PdfDocument to a file.
myPdf.saveAs(Paths.get("url.pdf"));
JAVA

You can also specify the formatting of the PDF file, such as page size, page orientation, margin size, layout, and many other properties simply by using the ChromePdfRenderOptions and passing the layout options in the renderUrlAsPdf method as the second argument.

After running the project with any of the above code samples, PDF files will be generated for all HTML content. Below you can see the sample output of "Convert HTML to PDF".

HTML2PDF Java (Code Example Tutorial), Figure 1: URL to PDF Output URL to PDF Output

You can find further code examples to create PDFs from HTML on IronPDF's website for Java developers.

HTML2PDF Java (Code Example Tutorial), Figure 2: IronPDF Website IronPDF Website

IronPDF renders all images and text without losing any formatting. Buttons are clickable, and text boxes are editable in the PDF file.

Summary

This article demonstrated how to create a PDF using the "Convert HTML to PDF" feature of the IronPDF Java API.

IronPDF for Java is free to use but for deployment purposes, it has a commercial license information which starts from only $799. You can also access the free trial of IronPDF for Java to test its functionality in production mode.

자주 묻는 질문

Java용 IronPDF는 어떤 용도로 사용되나요?

Java용 IronPDF는 PDF 문서를 프로그래밍 방식으로 생성, 편집 및 조작할 수 있는 라이브러리입니다. 원본 레이아웃과 서식을 유지하면서 HTML, JavaScript, 이미지와 같은 형식을 PDF로 변환하는 기능을 지원합니다.

서식을 잃지 않고 Java에서 HTML을 PDF로 변환하려면 어떻게 해야 하나요?

Java용 IronPDF는 HTML 문자열의 경우 renderHtmlAsPdf, HTML 파일의 경우 renderHtmlFileAsPdf, 웹 페이지 URL의 경우 renderUrlAsPdf 등의 방법을 사용하여 서식을 보존하면서 HTML을 PDF로 변환할 수 있습니다.

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

Java 프로젝트에서 IronPDF를 사용하려면 JDK(Java 개발 키트), Maven 및 IronPDF Java 라이브러리가 필요합니다. 또한 Slf4j와 같은 필요한 종속성을 pom.xml 파일에 포함해야 합니다.

Java용 IronPDF를 사용하여 웹 페이지 URL을 PDF로 변환하려면 어떻게 해야 하나요?

Java용 IronPDF에서 renderUrlAsPdf 메서드를 사용하여 웹 페이지 URL을 PDF로 변환할 수 있습니다. 이 메서드는 URL을 인수로 받아 PDF 문서를 생성합니다.

Java용 IronPDF는 HTML을 PDF로 변환할 때 CSS와 JavaScript를 지원하나요?

예, Java용 IronPDF는 HTML과 CSS 및 JavaScript를 함께 렌더링하여 결과 PDF가 원본 스타일과 대화형 요소를 유지할 수 있도록 합니다.

Java용 IronPDF에서 라이선스 키는 어떻게 설정하나요?

Java용 IronPDF에서는 기본 Java 파일에서 '라이선스 키'를 제공된 실제 키로 대체하여 License.setLicenseKey 메서드를 사용하여 라이선스 키를 설정합니다.

Java용 IronPDF의 주요 기능은 무엇인가요?

Java용 IronPDF는 HTML을 PDF로 변환, 머리글 및 바닥글 추가, 디지털 서명을 포함한 표 생성, PDF 레이아웃 및 서식 사용자 지정과 같은 기능을 제공합니다.

Java용 IronPDF는 다른 PDF 라이브러리에 비해 어떤 이점을 제공하나요?

Java용 IronPDF는 문서 서식 보존에 탁월하고 멀티스레딩을 지원하며 PDF에 대한 광범위한 사용자 정의 옵션을 제공합니다. 또한 HTML, JavaScript, 이미지 등 다양한 입력 형식과 호환됩니다.

Java용 IronPDF 평가판이 있나요?

예, Java용 IronPDF는 무료 평가판을 제공하여 개발자가 상용 라이선스를 구매하기 전에 프로덕션 환경에서 모든 기능을 테스트할 수 있습니다.

PDF 변환 프로세스에서 원본 레이아웃을 유지하려면 어떻게 해야 하나요?

PDF 변환 중에 원본 레이아웃을 유지하려면 원본 문서의 서식과 대화형 요소를 보존하도록 설계된 IronPDF의 renderHtmlAsPdf와 같은 메서드를 사용하세요.

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

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

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