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:
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/maven-dependency.xml
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>2024.9.1</version>
</dependency>
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/maven-dependency.xml
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>2024.9.1</version>
</dependency>
- Import the library and create a PDF:
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/quickstart.java
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"));
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/quickstart.java
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"));
How to Create a PDF File in Java
- 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:
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/maven-full.xml
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>2024.9.1</version>
</dependency>
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/maven-full.xml
<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:
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/gradle-dependency.gradle
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:
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/imports.java
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;
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/imports.java
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:
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/license-setup.java
License.setLicenseKey("Your-License-Key");
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/license-setup.java
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.
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/html-string-to-pdf.java
// 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"));
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/html-string-to-pdf.java
// 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:
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/html-string-styled.java
// 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"));
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/html-string-styled.java
// 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.
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:
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/html-file-to-pdf.java
// 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"));
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/html-file-to-pdf.java
// 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:
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/url-to-pdf.java
// Render a live web page to PDF
PdfDocument webPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
webPdf.saveAs(Paths.get("ironpdf-homepage.pdf"));
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/url-to-pdf.java
// 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:
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/url-to-pdf-auth.java
// 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"));
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/url-to-pdf-auth.java
// 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:
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/pdf-formatting.java
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"));
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/pdf-formatting.java
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:
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/password-protect-basic.java
// 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"));
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/password-protect-basic.java
// 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:
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/password-protect-advanced.java
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);
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/password-protect-advanced.java
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:
After entering the correct password, the PDF opens and displays the full content:
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.
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/spring-boot-controller.java
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);
}
}
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/spring-boot-controller.java
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?
Pass your HTML string to PdfDocument.renderHtmlAsPdf(). The method returns a PdfDocument object in memory. Call pdf.saveAs(Paths.get("output.pdf")) to write it to disk. IronPDF supports full HTML5, CSS3, and JavaScript.
What Java version does IronPDF require?
IronPDF for Java requires JDK 8 or later. JDK 11 LTS is the recommended minimum for production deployments.
How do I add IronPDF to a Maven project?
Add the dependency block with groupId com.ironsoftware and artifactId ironpdf inside the <dependencies> section of your pom.xml, then run mvn install.
How do I create a PDF from a local HTML file in Java?
Call PdfDocument.renderHtmlFileAsPdf() with the path to your HTML file. IronPDF resolves all linked CSS, images, and JavaScript relative to the file's directory automatically.
Can I create a PDF from a URL in Java?
Yes. Call PdfDocument.renderUrlAsPdf() with the target URL. IronPDF fetches the page using Chromium and returns a PdfDocument. For pages behind HTTP authentication, pass credentials through ChromePdfRenderOptions.
How do I password protect a PDF in Java with IronPDF?
Create a SecurityOptions object, call setUserPassword() with your password, then pass the options to urlPdf.getSecurity().setSecurityOptions() before calling saveAs().
How do I use IronPDF in a Spring Boot application?
Inject your PDF generation logic into a @RestController method. Call PdfDocument.renderHtmlAsPdf(), then use pdf.getBinaryData() to get a byte array and return it as a ResponseEntity<byte[]> with MediaType.APPLICATION_PDF.
How do I set page size and orientation in IronPDF for Java?
Create a ChromePdfRenderOptions object, call setPaperSize() and setPaperOrientation(), then pass it as the second argument to any render method. Set paper size before orientation to avoid ordering conflicts.
Does IronPDF run on Linux and macOS for Java?
Yes. IronPDF for Java runs on Windows, Linux, and macOS. It also supports cloud deployments on AWS, Azure, and Google Cloud without requiring an external PDF viewer or rendering engine.
Will PDFs have a watermark without a license key?
Yes. Without a valid license key, IronPDF adds a trial watermark to all generated documents. Call License.setLicenseKey() with a valid key at application startup to remove it.




