Passer au contenu du pied de page
UTILISATION D'IRONPDF POUR JAVA
Comment utiliser Tesseract OCR for .NET sur Windows

HTML2PDF Java (Exemple de Code Tutoriel)

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

IronPDF - Une bibliothèque Java

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


Prérequis

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. Le JDK peut être téléchargé depuis le site Web d'Oracle.
  2. Maven: Maven must be installed as it is a build automation tool used mainly for Java projects. Maven peut être téléchargé depuis le site Web d'Apache Maven.
  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. Vous devrez également ajouter la dépendance Slf4j dans le fichier pom.xml.

    <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

Convertir une chaîne HTML en 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 rend toutes les images et le texte sans perdre aucun formatage. Les boutons sont cliquables et les zones de texte sont modifiables dans le fichier PDF.

Résumé

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.

Questions Fréquemment Posées

À quoi sert IronPDF for Java ?

IronPDF for Java est une bibliothèque qui permet la création, la modification et la manipulation programmatique de documents PDF. Elle prend en charge la conversion de formats tels que HTML, JavaScript et images en PDF tout en conservant la mise en page et la mise en forme d'origine.

Comment puis-je convertir du HTML en PDF en Java sans perdre la mise en forme ?

IronPDF for Java peut convertir du HTML en PDF tout en préservant la mise en forme en utilisant des méthodes comme renderHtmlAsPdf pour les chaînes HTML, renderHtmlFileAsPdf pour les fichiers HTML et renderUrlAsPdf pour les URL de pages Web.

Quelles sont les conditions préalables pour utiliser IronPDF dans un projet Java ?

Pour utiliser IronPDF dans un projet Java, vous avez besoin du Java Development Kit (JDK), Maven et de la bibliothèque IronPDF Java. Vous devez également inclure les dépendances nécessaires dans votre fichier pom.xml, comme Slf4j.

Comment convertissez-vous une URL de page Web en PDF en utilisant IronPDF for Java ?

Vous pouvez convertir une URL de page Web en PDF en utilisant la méthode renderUrlAsPdf dans IronPDF for Java. Cette méthode prend l'URL comme argument et génère un document PDF.

Est-ce qu'IronPDF for Java prend en charge CSS et JavaScript lors de la conversion de HTML en PDF ?

Oui, IronPDF for Java peut rendre du HTML ainsi que CSS et JavaScript, garantissant que le PDF résultant conserve le style original et les éléments interactifs.

Comment définir la clé de licence dans IronPDF for Java ?

Dans IronPDF for Java, vous définissez la clé de licence en utilisant la méthode License.setLicenseKey dans votre fichier Java principal, en remplaçant 'Votre clé de licence' par la clé réelle fournie.

Quelles sont certaines des principales fonctionnalités d'IronPDF for Java ?

IronPDF for Java offre des fonctionnalités telles que la conversion de HTML en PDF, l'ajout d'en-têtes et de pieds de page, la création de tableaux, l'inclusion de signatures numériques et la personnalisation des mises en page et des formats PDF.

Quels avantages IronPDF for Java propose-t-il par rapport aux autres bibliothèques PDF ?

IronPDF for Java excelle dans la préservation de la mise en forme des documents, prend en charge le multithreading, et offre de nombreuses options de personnalisation pour les PDF. Il est également compatible avec divers formats d'entrée, y compris HTML, JavaScript et images.

Existe-t-il une version d'essai disponible pour IronPDF for Java ?

Oui, IronPDF for Java offre une version gratuite d'essai, permettant aux développeurs de tester l'ensemble de ses fonctionnalités et capacités dans un environnement de production avant d'acheter une licence commerciale.

Comment puis-je garantir que mon processus de conversion PDF conserve la mise en page originale ?

Pour conserver la mise en page originale lors de la conversion PDF, utilisez les méthodes d'IronPDF comme renderHtmlAsPdf, qui sont conçues pour préserver la mise en forme et les éléments interactifs du document source.

Darrius Serrant
Ingénieur logiciel Full Stack (WebOps)

Darrius Serrant est titulaire d'un baccalauréat en informatique de l'université de Miami et travaille comme ingénieur marketing WebOps Full Stack chez Iron Software. Attiré par le codage dès son plus jeune âge, il a vu l'informatique comme à la fois mystérieuse et accessible, en faisant le ...

Lire la suite