How to Create PDF Files in Java
Creating PDF files in Java is a common requirement for business applications: generating invoices and reports on demand, producing certificates, receipts, and audit logs. IronPDF for Java converts HTML to PDF using a full Chromium rendering engine, which means any HTML5, CSS3, and JavaScript content renders faithfully, without formatting loss.
This guide covers three PDF creation methods: from an HTML string, from a local HTML file, and from a live URL. It also covers page formatting, password protection, and Spring Boot integration.
Quickstart: Create a PDF from HTML in Java- Add IronPDF to your
pom.xml:
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>2024.9.1</version>
</dependency>
-
Import the library and create a PDF:
import com.ironsoftware.ironpdf.*; import java.nio.file.Paths; // Set your license key (remove watermarks in production) License.setLicenseKey("Your-License-Key"); // Convert HTML string to PDF and save PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Hello, IronPDF!</h1>"); pdf.saveAs(Paths.get("output.pdf"));Java
Minimal Workflow (5 steps)
- Install the IronPDF Java library via Maven or Gradle
- Import
com.ironsoftware.ironpdf.*and set your license key - Call
PdfDocument.renderHtmlAsPdf()with an HTML string to create a PDF in memory - Use
PdfDocument.renderHtmlFileAsPdf()to convert a local HTML file to PDF - Call
pdf.saveAs()to write the finished document to disk
What Is IronPDF for Java, and Why Use It?
IronPDF for Java is a PDF generation and manipulation library built on the Chromium rendering engine. Because it renders HTML exactly as Chrome does, it handles complex layouts, custom fonts, CSS animations, JavaScript-generated content, and embedded images with no manual layout code.
The library covers the full PDF lifecycle in a single dependency. Developers can create documents from scratch, convert existing HTML content, merge or split files, add watermarks, encrypt with passwords, extract text and images, and generate fillable forms, all through a consistent API. For HTML-heavy workflows, IronPDF avoids the manual page layout calculations required by low-level PDF libraries like Apache PDFBox.
Unlike iText, which requires an AGPL open-source license for most commercial uses, IronPDF ships with commercial-friendly licensing and requires no complex license compliance review. IronPDF for Java ships as a Maven artifact and runs on Windows, Linux, and macOS. It integrates with Spring Boot, Jakarta EE, and standalone Java applications. The library also supports server deployments on AWS, Azure, and Google Cloud.
What Are the Prerequisites for Using IronPDF in Java?
Which Java Version and Build Tool Are Required?
IronPDF for Java requires JDK 8 or later. The recommended minimum is JDK 11 (LTS) for production use. Download the JDK from the Oracle download page or use an OpenJDK distribution such as Eclipse Temurin.
Maven (3.6+) and Gradle (7.0+) are both supported. Maven is the more common choice for enterprise Java projects.
How Do I Add IronPDF to a Maven Project?
Open your project's pom.xml and add the following dependency inside the <dependencies> block:
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>2024.9.1</version>
</dependency>
After saving, run mvn install or let your IDE resolve the dependency automatically. Maven downloads IronPDF from Maven Central, so no private repository configuration is needed.
How Do I Add IronPDF to a Gradle Project?
Add the following line to the dependencies block in your build.gradle file:
implementation 'com.ironsoftware:ironpdf:2024.9.1'
Run gradle build to fetch the library. Check Maven Central for the latest published version.
What Imports and Configuration Are Needed?
Add these import statements at the top of your Java source file:
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import com.ironsoftware.ironpdf.render.PaperOrientation;
import com.ironsoftware.ironpdf.render.PaperSize;
import com.ironsoftware.ironpdf.security.SecurityOptions;
import com.ironsoftware.ironpdf.security.SecurityManager;
import java.io.IOException;
import java.nio.file.Paths;
Before generating any PDFs, set your license key in the main method or application startup:
License.setLicenseKey("Your-License-Key");
Note: Without a valid license key, PDFs are generated with a trial watermark. Purchase a license or start a free trial to remove it. See using license keys in Java for additional configuration options.
How Do I Create a PDF from an HTML String in Java?
Pass any HTML string directly to PdfDocument.renderHtmlAsPdf(). IronPDF returns a PdfDocument instance representing the finished document in memory. Call saveAs() to write it to disk.
// HTML content with inline CSS
String htmlContent = "<h1>Hello World!</h1><p>This is an example HTML string.</p>";
// Render HTML string to PDF
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(htmlContent);
// Save to disk
pdf.saveAs(Paths.get("html.pdf"));
renderHtmlAsPdf() supports the full HTML5 and CSS3 specification, including web fonts, Flexbox, Grid layouts, and JavaScript execution. The following example uses a multi-line HTML template with custom styles:
// Multi-line HTML with CSS styling using a text block (Java 13+)
String styledHtml = """
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #2563eb; border-bottom: 2px solid #e5e7eb; padding-bottom: 8px; }
.summary { background: #f3f4f6; padding: 16px; border-radius: 4px; }
</style>
</head>
<body>
<h1>Invoice #1042</h1>
<div class="summary">
<p>Amount due: $1,250.00</p>
<p>Due date: 2024-06-01</p>
</div>
</body>
</html>
""";
PdfDocument invoice = PdfDocument.renderHtmlAsPdf(styledHtml);
invoice.saveAs(Paths.get("invoice.pdf"));
The invoice example above uses Java text blocks (available since Java 13) for cleaner multi-line HTML. For older Java versions, concatenate the HTML string manually or load it from a file using renderHtmlFileAsPdf(). For a broader look at HTML-to-PDF conversion including JavaScript rendering, see the HTML to PDF tutorial for Java.
<!DOCTYPE html> document.How Do I Create a PDF from a Local HTML File in Java?
Use PdfDocument.renderHtmlFileAsPdf() to convert an HTML file stored on the local file system. Pass the path as a string; relative paths resolve against the current working directory:
// Convert a local HTML file to PDF
PdfDocument filePdf = PdfDocument.renderHtmlFileAsPdf("invoice-template.html");
// Save the converted document
filePdf.saveAs(Paths.get("invoice_output.pdf"));
IronPDF resolves all referenced assets (external CSS files, local images, and JavaScript libraries) relative to the HTML file's directory. This means you can build a complete HTML template with linked stylesheets and run it through IronPDF without modifying any asset paths.
The method accepts both a String path and a java.nio.file.Path object. For production use, prefer absolute paths to avoid working-directory ambiguity. See the HTML file to PDF example for a complete working demonstration.
How Do I Create a PDF from a Web Page URL in Java?
PdfDocument.renderUrlAsPdf() fetches a live URL, renders it using Chromium, and returns a PDF. This is useful for capturing dashboard snapshots, generating PDF receipts from hosted receipt pages, or archiving web content:
// Render a live web page to PDF
PdfDocument webPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
webPdf.saveAs(Paths.get("ironpdf-homepage.pdf"));
For pages behind HTTP authentication, pass credentials through ChromePdfRenderOptions:
// Configure render options with login credentials
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
renderOptions.setAuthUsername("username");
renderOptions.setAuthPassword("password");
// Render authenticated page to PDF
PdfDocument securedPdf = PdfDocument.renderUrlAsPdf("https://your-internal-app.com/report", renderOptions);
securedPdf.saveAs(Paths.get("internal-report.pdf"));
See the URL to PDF code example for details. For more complex login flows using cookies or form-based authentication, see website login handling.
How Do I Control Page Size, Orientation, and Margins?
Use ChromePdfRenderOptions to customize the physical layout of the output PDF. Pass the configured options as the second argument to any render method. The most common settings are page orientation, paper size, and margins:
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
// Set landscape orientation (default is portrait)
renderOptions.setPaperOrientation(PaperOrientation.LANDSCAPE);
// Use US Letter paper size (default is A4)
renderOptions.setPaperSize(PaperSize.LETTER);
// Set margins in millimeters (top, right, bottom, left)
renderOptions.setMarginTop(15);
renderOptions.setMarginRight(15);
renderOptions.setMarginBottom(15);
renderOptions.setMarginLeft(15);
// Include background colors and images
renderOptions.setPrintHtmlBackgrounds(true);
// Apply options when rendering
PdfDocument report = PdfDocument.renderHtmlAsPdf("<h1>Quarterly Report</h1>", renderOptions);
report.saveAs(Paths.get("report.pdf"));
ChromePdfRenderOptions exposes over 30 settings beyond the ones shown above, including DPI, JavaScript execution timeout, zoom factor, and CSS media type. See PDF generation settings for a full list. For custom paper sizes not in the PaperSize enum, see custom PDF paper sizes.
How Do I Add Password Protection to a PDF in Java?
SecurityOptions controls read and owner passwords as well as permission flags. Pass SecurityOptions to the document's SecurityManager before saving:
// Create security settings with a user-facing password
SecurityOptions securityOptions = new SecurityOptions();
securityOptions.setUserPassword("shareable");
// Apply security to the document
PdfDocument urlPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
SecurityManager securityManager = urlPdf.getSecurity();
securityManager.setSecurityOptions(securityOptions);
// Save the password-protected document
urlPdf.saveAs(Paths.get("protected.pdf"));
For stricter control, set an owner password and restrict specific operations:
SecurityOptions advancedSecurity = new SecurityOptions();
// User password: required to open the file
advancedSecurity.setUserPassword("user-open-pass");
// Owner password: required to change security settings
advancedSecurity.setOwnerPassword("owner-admin-pass");
// Restrict editing operations
advancedSecurity.setAllowPrint(false);
advancedSecurity.setAllowCopy(false);
advancedSecurity.setAllowEditContent(false);
advancedSecurity.setAllowEditAnnotations(false);
Opening the PDF prompts the reader for a password:

PDF readers display a password prompt when the document is protected with a user password.
After entering the correct password, the PDF opens and displays the full content:

The document renders normally after the correct password is supplied.
See security and metadata settings for the full list of permission flags.
How Do I Generate PDFs in a Spring Boot Application?
IronPDF integrates directly with Spring Boot. Return a PDF as a byte-array HTTP response from any controller method; this pattern works for on-demand report generation, invoice downloads, and data exports.
import com.ironsoftware.ironpdf.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
@RestController
@RequestMapping("/api/pdf")
public class PdfController {
@GetMapping("/invoice/{id}")
public ResponseEntity<byte[]> generateInvoice(@PathVariable String id) throws IOException {
// Build HTML dynamically using the invoice ID
String html = """
<html><body>
<h1>Invoice #%s</h1>
<p>Amount due: $500.00</p>
</body></html>
""".formatted(id);
// Render and return as PDF download
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(html);
byte[] pdfBytes = pdf.getBinaryData();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
headers.setContentDispositionFormData("attachment", "invoice-" + id + ".pdf");
return ResponseEntity.ok().headers(headers).body(pdfBytes);
}
}
The getBinaryData() method returns the PDF as a byte array, which Spring Boot streams directly to the client. No temporary file is written to disk. For high-throughput deployments, instantiate License.setLicenseKey() in a @PostConstruct method or application startup listener rather than per-request.
What Are the Next Steps for Java PDF Creation?
This guide demonstrated four approaches to PDF generation in Java using IronPDF: HTML string rendering, local file conversion, URL capture, and Spring Boot HTTP response streaming. All methods share the same PdfDocument API, ChromePdfRenderOptions for formatting control, and SecurityOptions for access protection.
IronPDF for Java also supports adding and stamping watermarks, merging multiple PDF files, splitting PDFs into individual pages, adding digital signatures, rendering JavaScript charts to PDF, and printing PDFs programmatically.
Start a free trial to generate PDFs without watermarks, or view licensing options to choose a plan that fits your project. Ready to go deeper? Check out the full IronPDF for Java tutorial page.
Frequently Asked Questions
How do I create a PDF from an HTML string in Java using IronPDF?
To create a PDF from an HTML string in Java using IronPDF, use the `PdfDocument.renderHtmlAsPdf()` method. Pass your HTML content as a string, and the method will return a `PdfDocument` object. You can then save this document to disk using the `saveAs()` method.
Can I convert a local HTML file to a PDF in Java with IronPDF?
Yes, you can convert a local HTML file to a PDF in Java using IronPDF. Use the `PdfDocument.renderHtmlFileAsPdf()` method by passing the file path as an argument. This method will render the HTML file and return a `PdfDocument` which can be saved to your desired location.
Is it possible to create a PDF from a live URL with IronPDF for Java?
Yes, IronPDF for Java allows you to create a PDF from a live URL using the `PdfDocument.renderUrlAsPdf()` method. Provide the URL as a parameter, and the method will fetch the content, render it to PDF, and return a `PdfDocument` object.
How can I integrate IronPDF into a Maven project?
To integrate IronPDF into a Maven project, add the IronPDF dependency to your `pom.xml` file under the `
What are the prerequisites for using IronPDF in Java?
IronPDF for Java requires JDK 8 or later, with JDK 11 (LTS) recommended for production. Supported build tools include Maven (3.6+) and Gradle (7.0+). You don't need any additional private repository configuration as IronPDF is available on Maven Central.
How do I add password protection to PDFs using IronPDF?
To add password protection to PDFs with IronPDF, use the `SecurityOptions` class to set a user and/or owner password, and apply it through the document's `SecurityManager` before saving the PDF.
Can IronPDF be used in Spring Boot applications?
Yes, IronPDF can be integrated with Spring Boot by using a controller method to generate PDFs and return them as byte-array HTTP responses. This setup is ideal for generating reports, invoices, and more dynamically through web endpoints.
What formatting options are available in IronPDF for Java?
IronPDF provides extensive formatting options through the `ChromePdfRenderOptions` class, allowing you to set page sizes, orientations, margins, and more. You can configure these options and pass them to the rendering methods for customized PDF output.
Is it possible to run IronPDF on different operating systems?
Yes, IronPDF for Java is cross-platform and can be run on Windows, Linux, and macOS. It's also compatible with various cloud services like AWS, Azure, and Google Cloud.
How does IronPDF for Java handle complex HTML and JavaScript?
IronPDF uses a full Chromium rendering engine, ensuring that complex HTML5, CSS3, and JavaScript content is faithfully rendered without formatting loss. This makes it well-suited for converting dynamic web pages to PDFs.

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.