Edit PDF in Java (Full Tutorial)
This tutorial gives a high-level overview of how Java developers can edit the content and structure of existing PDF documents using IronPDF. This includes PDF documents rendered from HTML using IronPDF's HTML conversion features, as well as PDFs produced using other third-party apps and software libraries.
A tutorial for editing PDF documents in C#.NET and VB.NET is also available.
This tutorial assumes that the reader already knows how to use IronPDF to convert HTML content into PDFs. Consider reading the HTML to PDF tutorial first before continuing with this tutorial if you are not familiar with the feature (or need to refresh on the basic workflow).
How to Edit PDF File in Java
Table of Contents
- Edit Document Structure
- Manipulating PDF documents
- Add, Copy, and Delete Pages
- Merge and Split PDFs
- Set the Custom size of PDF documents
- Set PDF Orientation
- Set Custom Margins of PDF
- Convert PDF documents to Images
- Add Background and Foreground
- Add PDF as Background
- Add PDF as Foreground
- Images and Text Extraction
- Extract Content
- Extract Images
- Edit Document Properties
- Add and Use PDF Metadata
- Digital Signatures
- Compress PDFs
- Edit PDF Content
- Add Headers and Footers
- Outlines and Bookmarks
- Add and Edit Annotations
- Stamping and Watermarking
- Stamper Overview
- Stamper Examples
- Stamp Text onto a PDF
- Stamp an Image onto a PDF
- Stamp a Barcode onto a PDF
- Stamp a QR Code onto a PDF
- Add a Watermark to a PDF
- Using Forms in PDFs
- Create and Edit Forms
- Fill Existing Forms
- Send PDF for Printing
Getting Started
Start using IronPDF in your project today with a free trial.
There are two ways to incorporate the IronPDF Library in a Java Project:
- Add IronPDF as a dependency in a Maven-configured Java Project
- Download the IronPDF JAR File and add it to the project classpath manually.
To install IronPDF in a Java project using Maven, include the artifacts given below in the dependency section of the Java project's pom.xml file.
<!-- Add the IronPDF Maven dependency here -->
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>REPLACE_WITH_VERSION_NUMBER</version>
</dependency>
<!-- Add the IronPDF Maven dependency here -->
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>REPLACE_WITH_VERSION_NUMBER</version>
</dependency>
Developers who prefer to manage the JAR file manually can download the IronPDF library JAR file and add it to their project's classpath.
Tutorial Content
Edit Document Structure
Manipulating PDF documents
IronPDF makes managing PDFs effortless with its capability to add PDFs at specific indexes, copy pages either as a range or individually, and delete pages with ease. All these tasks are handled seamlessly in the background.
Add Pages
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
// Load existing PDF
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
// Create a cover page as a new PDF
PdfDocument coverPagePdf = PdfDocument.renderHtmlAsPdf("<h1>Cover Page</h1><hr>");
// Prepend the cover page PDF to the main PDF
PDF.prependPdf(coverPagePdf);
// Save the combined PDF
PDF.saveAs(Paths.get("report_with_cover.pdf"));
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
// Load existing PDF
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
// Create a cover page as a new PDF
PdfDocument coverPagePdf = PdfDocument.renderHtmlAsPdf("<h1>Cover Page</h1><hr>");
// Prepend the cover page PDF to the main PDF
PDF.prependPdf(coverPagePdf);
// Save the combined PDF
PDF.saveAs(Paths.get("report_with_cover.pdf"));
Copy Pages
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
// Load existing PDF
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
// Copy the first page of PDF
PdfDocument copiedPdf = PDF.copyPages(0, 1);
// Save the copied page to a new PDF
copiedPdf.saveAs("report_highlight.pdf");
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
// Load existing PDF
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
// Copy the first page of PDF
PdfDocument copiedPdf = PDF.copyPages(0, 1);
// Save the copied page to a new PDF
copiedPdf.saveAs("report_highlight.pdf");
Delete Pages
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
// Load existing PDF
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
// Remove the last page of the PDF
PDF.removePages(PageSelection.lastPage()).saveAs(Paths.get("assets/lastPageRemove.pdf"));
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
// Load existing PDF
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
// Remove the last page of the PDF
PDF.removePages(PageSelection.lastPage()).saveAs(Paths.get("assets/lastPageRemove.pdf"));
Attach a Cover Page
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.headerfooter.HeaderFooterOptions;
import java.io.IOException;
import java.nio.file.Paths;
// Create a Sample Cover Page using RenderHtmlAsPdf
PdfDocument coverPage = PdfDocument.renderHtmlAsPdf("<h1>This is a Cover Page</h1>");
// Render a web page as PDF
PdfDocument webpage = PdfDocument.renderUrlAsPdf("https://www.nuget.org/packages/IronPdf/");
// Set header/footer options
HeaderFooterOptions headerFooterOptions = new HeaderFooterOptions();
headerFooterOptions.setFirstPageNumber(1);
TextHeaderFooter footer = new TextHeaderFooter();
footer.setLeftText("");
footer.setCenterText("Page {page}");
footer.setRightText("");
webpage.addTextFooter(footer, headerFooterOptions);
// Merge the cover page with the web page and save the new PDF to the filesystem.
try {
PdfDocument.merge(coverPage, webpage).saveAs(Paths.get("assets/cover_page_pdf.pdf"));
} catch (IOException e) {
throw new RuntimeException(e);
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.headerfooter.HeaderFooterOptions;
import java.io.IOException;
import java.nio.file.Paths;
// Create a Sample Cover Page using RenderHtmlAsPdf
PdfDocument coverPage = PdfDocument.renderHtmlAsPdf("<h1>This is a Cover Page</h1>");
// Render a web page as PDF
PdfDocument webpage = PdfDocument.renderUrlAsPdf("https://www.nuget.org/packages/IronPdf/");
// Set header/footer options
HeaderFooterOptions headerFooterOptions = new HeaderFooterOptions();
headerFooterOptions.setFirstPageNumber(1);
TextHeaderFooter footer = new TextHeaderFooter();
footer.setLeftText("");
footer.setCenterText("Page {page}");
footer.setRightText("");
webpage.addTextFooter(footer, headerFooterOptions);
// Merge the cover page with the web page and save the new PDF to the filesystem.
try {
PdfDocument.merge(coverPage, webpage).saveAs(Paths.get("assets/cover_page_pdf.pdf"));
} catch (IOException e) {
throw new RuntimeException(e);
}
Know more about attaching cover pages in PDF documents.
Merge and Split PDFs
IronPDF Java simplifies the process of merging multiple PDFs into one or splitting an existing PDF using its user-friendly API.
Join Multiple Existing PDF documents into a Single PDF document
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
// HTML content for two PDFs
String htmlA = "<p>[PDF_A]</p><p>[PDF_A] 1st Page</p><div style='page-break-after: always;'></div><p>[PDF_A] 2nd Page</p>";
String htmlB = "<p>[PDF_B]</p><p>[PDF_B] 1st Page</p><div style='page-break-after: always;'></div><p>[PDF_B] 2nd Page</p>";
// Render to PDFs
PdfDocument pdfA = PdfDocument.renderHtmlAsPdf(htmlA);
PdfDocument pdfB = PdfDocument.renderHtmlAsPdf(htmlB);
// Merge PDFs
PdfDocument merged = PdfDocument.merge(pdfA, pdfB);
merged.saveAs(Paths.get("assets/merged.pdf"));
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
// HTML content for two PDFs
String htmlA = "<p>[PDF_A]</p><p>[PDF_A] 1st Page</p><div style='page-break-after: always;'></div><p>[PDF_A] 2nd Page</p>";
String htmlB = "<p>[PDF_B]</p><p>[PDF_B] 1st Page</p><div style='page-break-after: always;'></div><p>[PDF_B] 2nd Page</p>";
// Render to PDFs
PdfDocument pdfA = PdfDocument.renderHtmlAsPdf(htmlA);
PdfDocument pdfB = PdfDocument.renderHtmlAsPdf(htmlB);
// Merge PDFs
PdfDocument merged = PdfDocument.merge(pdfA, pdfB);
merged.saveAs(Paths.get("assets/merged.pdf"));
Splitting a PDF and Extracting Pages
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
// Load existing PDF
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
// Copy the first page to a new PDF
PdfDocument copied = PDF.copyPage(0);
copied.saveAs(Paths.get("assets/Split.pdf"));
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
// Load existing PDF
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
// Copy the first page to a new PDF
PdfDocument copied = PDF.copyPage(0);
copied.saveAs(Paths.get("assets/Split.pdf"));
Set the Custom Size of PDF Documents
IronPDF enables developers to create PDF documents with non-standard dimensions, beyond the conventional A4 size (8½ by 11 inches or 21.59 by 27.94 cm).
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.render.*;
import java.io.IOException;
import java.nio.file.Paths;
// Sample HTML content
String html = "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>";
// Configure the render options
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
renderOptions.setPaperSize(PaperSize.Custom);
// Set custom paper dimensions in centimeters
renderOptions.setCustomPaperSizeInCentimeters(13.97, 13.97);
// Render HTML with specified dimensions to PDF
PdfDocument.renderHtmlAsPdf(html, renderOptions).saveAs(Paths.get("assets/CustomPaperSize.pdf"));
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.render.*;
import java.io.IOException;
import java.nio.file.Paths;
// Sample HTML content
String html = "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>";
// Configure the render options
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
renderOptions.setPaperSize(PaperSize.Custom);
// Set custom paper dimensions in centimeters
renderOptions.setCustomPaperSizeInCentimeters(13.97, 13.97);
// Render HTML with specified dimensions to PDF
PdfDocument.renderHtmlAsPdf(html, renderOptions).saveAs(Paths.get("assets/CustomPaperSize.pdf"));
Know more tricks about the custom size of the PDFs.
Set PDF Orientation
IronPDF for Java allows modification of page orientation in both new and existing PDFs. By default, new PDFs created with IronPDF are set to portrait orientation, but developers can change it by using a ChromePdfRenderOptions instance when converting content (such as HTML, RTFs, and URLs) into PDFs.
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.page.PageRotation;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import java.io.IOException;
import java.nio.file.Paths;
// Use the setPaperOrientation method to set rendered PDFs in portrait or landscape orientation.
// Note: This will only work for newly-created PDFs!
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
renderOptions.setPaperOrientation(PaperOrientation.LANDSCAPE);
PdfDocument newPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com", renderOptions);
newPdf.saveAs(Paths.get("assets/LandscapePdf.pdf"));
// Use the rotatePage/rotateAllPages methods to adjust the page orientation for existing PDFs
PdfDocument existingPdf = PdfDocument.fromFile(Paths.get("assets/example.pdf"));
// Get the orientation of the first page of the existing PDF document.
PageRotation firstPageRotation = existingPdf.getPagesInfo().get(0).getPageRotation();
System.out.println(firstPageRotation);
// Rotate the first page of the document only 90 degrees clockwise.
existingPdf.rotatePage(PageRotation.CLOCKWISE_90, PageSelection.firstPage());
// Rotate all pages of the document clockwise.
existingPdf.rotateAllPages(PageRotation.CLOCKWISE_270);
existingPdf.saveAs(Paths.get("assets/ExistingPdfRotated.pdf"));
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.page.PageRotation;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import java.io.IOException;
import java.nio.file.Paths;
// Use the setPaperOrientation method to set rendered PDFs in portrait or landscape orientation.
// Note: This will only work for newly-created PDFs!
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
renderOptions.setPaperOrientation(PaperOrientation.LANDSCAPE);
PdfDocument newPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com", renderOptions);
newPdf.saveAs(Paths.get("assets/LandscapePdf.pdf"));
// Use the rotatePage/rotateAllPages methods to adjust the page orientation for existing PDFs
PdfDocument existingPdf = PdfDocument.fromFile(Paths.get("assets/example.pdf"));
// Get the orientation of the first page of the existing PDF document.
PageRotation firstPageRotation = existingPdf.getPagesInfo().get(0).getPageRotation();
System.out.println(firstPageRotation);
// Rotate the first page of the document only 90 degrees clockwise.
existingPdf.rotatePage(PageRotation.CLOCKWISE_90, PageSelection.firstPage());
// Rotate all pages of the document clockwise.
existingPdf.rotateAllPages(PageRotation.CLOCKWISE_270);
existingPdf.saveAs(Paths.get("assets/ExistingPdfRotated.pdf"));
If you want to get more information, you can visit IronPDF's website section on setting PDF orientation.
Set Custom Margins of PDF
IronPDF creates new PDFs with a default margin of 25mm on all sides (top, bottom, left, right). However, developers can customize each margin with specific measurements to meet design requirements using IronPDF.
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import java.io.IOException;
import java.nio.file.Paths;
// Set Margins (in millimeters)
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
renderOptions.setMarginTop(40);
renderOptions.setMarginLeft(20);
renderOptions.setMarginRight(20);
renderOptions.setMarginBottom(40);
PdfDocument.renderHtmlFileAsPdf("assets/wikipedia.html", renderOptions).saveAs(Paths.get("assets/MyContent.pdf"));
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import java.io.IOException;
import java.nio.file.Paths;
// Set Margins (in millimeters)
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
renderOptions.setMarginTop(40);
renderOptions.setMarginLeft(20);
renderOptions.setMarginRight(20);
renderOptions.setMarginBottom(40);
PdfDocument.renderHtmlFileAsPdf("assets/wikipedia.html", renderOptions).saveAs(Paths.get("assets/MyContent.pdf"));
Visit the IronPDF website to know more about setting custom margins for PDF documents.
Convert PDF documents to Images
IronPDF can export pages of a loaded PDF file, converted source content, or a modified PDF with headers, footers, margins, etc. into images that can be saved to a file system, stored in a database, or transmitted over networks.
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.image.ToImageOptions;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;
// Load the PDF from file
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/composite.pdf"));
// Extract all the pages from the PDF file as images
List<BufferedImage> extractedImages = pdf.toBufferedImages();
// Options to set maximum image dimensions and DPI for each extracted image
ToImageOptions rasterOptions = new ToImageOptions();
rasterOptions.setImageMaxHeight(100);
rasterOptions.setImageMaxWidth(100);
// Extract images for all pages with specified dimensions
List<BufferedImage> sizedExtractedImages = pdf.toBufferedImages(rasterOptions, PageSelection.allPages());
// Save each extracted image to the file system
int i = 1;
for (BufferedImage extractedImage : sizedExtractedImages) {
String fileName = "assets/images/" + i++ + ".png";
ImageIO.write(extractedImage, "PNG", new File(fileName));
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.image.ToImageOptions;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;
// Load the PDF from file
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/composite.pdf"));
// Extract all the pages from the PDF file as images
List<BufferedImage> extractedImages = pdf.toBufferedImages();
// Options to set maximum image dimensions and DPI for each extracted image
ToImageOptions rasterOptions = new ToImageOptions();
rasterOptions.setImageMaxHeight(100);
rasterOptions.setImageMaxWidth(100);
// Extract images for all pages with specified dimensions
List<BufferedImage> sizedExtractedImages = pdf.toBufferedImages(rasterOptions, PageSelection.allPages());
// Save each extracted image to the file system
int i = 1;
for (BufferedImage extractedImage : sizedExtractedImages) {
String fileName = "assets/images/" + i++ + ".png";
ImageIO.write(extractedImage, "PNG", new File(fileName));
}
Add Background and Foreground
IronPDF provides addBackground
and addForeground
methods for adding a specific background or foreground element to PDFs. These methods enable developers to incorporate content from one PDF as the background or foreground of another PDF, making it efficient for generating collections of PDFs based on a common design template.
Add PDF as background
import com.ironsoftware.ironpdf.*;
import java.io.IOException;
import java.nio.file.Paths;
// Load background PDF from the filesystem
PdfDocument backgroundPdf = PdfDocument.fromFile(Paths.get("assets/MyBackground.pdf"));
// Render content as a PDF Document
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
// Add the background PDF to the newly-rendered document
pdf.addBackgroundPdf(backgroundPdf);
// Save the PDF with background
pdf.saveAs(Paths.get("assets/BackgroundPdf.pdf"));
import com.ironsoftware.ironpdf.*;
import java.io.IOException;
import java.nio.file.Paths;
// Load background PDF from the filesystem
PdfDocument backgroundPdf = PdfDocument.fromFile(Paths.get("assets/MyBackground.pdf"));
// Render content as a PDF Document
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
// Add the background PDF to the newly-rendered document
pdf.addBackgroundPdf(backgroundPdf);
// Save the PDF with background
pdf.saveAs(Paths.get("assets/BackgroundPdf.pdf"));
Add PDF as Foreground
import com.ironsoftware.ironpdf.*;
import java.io.IOException;
import java.nio.file.Paths;
// Load foreground PDF from the filesystem
PdfDocument foregroundPdf = PdfDocument.fromFile(Paths.get("assets/MyForeground.pdf"));
// Render content as a PDF Document
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
// Add the foreground PDF to the newly-rendered document
pdf.addForegroundPdf(foregroundPdf);
// Save the PDF with foreground
pdf.saveAs(Paths.get("assets/BackgroundForegroundPdf.pdf"));
import com.ironsoftware.ironpdf.*;
import java.io.IOException;
import java.nio.file.Paths;
// Load foreground PDF from the filesystem
PdfDocument foregroundPdf = PdfDocument.fromFile(Paths.get("assets/MyForeground.pdf"));
// Render content as a PDF Document
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
// Add the foreground PDF to the newly-rendered document
pdf.addForegroundPdf(foregroundPdf);
// Save the PDF with foreground
pdf.saveAs(Paths.get("assets/BackgroundForegroundPdf.pdf"));
Images and Text Extraction
IronPDF's comprehensive PDF creation and editing functions include the ability to extract content granularly with its content extraction methods.
The extractAllText
method is available on all PdfDocument
objects and returns a string containing all the text in the PDF document. Additionally, extractAllImages
returns a collection of all embedded images in the PDF, each in the form of a BufferedImage
object. To retrieve the images as raw bytes, use the extractAllRawImages
method.
Extract Content
// Render URL content to PDF
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://unsplash.com/");
// Extract all text
String text = pdf.extractAllText();
System.out.println("Text extracted from the website: " + text);
// Render URL content to PDF
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://unsplash.com/");
// Extract all text
String text = pdf.extractAllText();
System.out.println("Text extracted from the website: " + text);
Extract Images
import java.nio.file.*;
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://unsplash.com/");
try {
// Extract images from the PDF
List<BufferedImage> images = pdf.extractAllImages();
System.out.println("Number of images extracted from the website: " + images.size());
int i = 0;
for (BufferedImage image : images) {
// Save each extracted image
ImageIO.write(image, "PNG", Files.newOutputStream(Path.of("assets/extracted_" + ++i + ".png")));
}
} catch(Exception exception) {
System.out.println("Failed to extract images from the website");
exception.printStackTrace();
}
import java.nio.file.*;
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://unsplash.com/");
try {
// Extract images from the PDF
List<BufferedImage> images = pdf.extractAllImages();
System.out.println("Number of images extracted from the website: " + images.size());
int i = 0;
for (BufferedImage image : images) {
// Save each extracted image
ImageIO.write(image, "PNG", Files.newOutputStream(Path.of("assets/extracted_" + ++i + ".png")));
}
} catch(Exception exception) {
System.out.println("Failed to extract images from the website");
exception.printStackTrace();
}
Edit Document Properties
Add and Use PDF Metadata
IronPDF offers the ability to modify PDF metadata and security features, including making PDFs read-only, unprintable, password-protected, and encrypted. In IronPDF for Java, the MetadataManager
can be used to access and edit a PDF's metadata. The MetadataManager
class provides direct access to metadata content and allows developers to easily read and edit common metadata properties through getters and setters with the same names.
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.security.PdfPrintSecurity;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Date;
// Load a PDF with password
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/encrypted.pdf"), "password");
// Edit the metadata
MetadataManager metadata = pdf.getMetadata();
metadata.setAuthor("Satoshi Nakamoto");
metadata.setKeywords("SEO, Friendly");
metadata.setModifiedDate(new Date().toString());
// Edit security settings to make PDF read-only
SecurityOptions securityOptions = new SecurityOptions();
securityOptions.setAllowUserCopyPasteContent(false);
securityOptions.setAllowUserAnnotations(false);
securityOptions.setAllowUserPrinting(PdfPrintSecurity.FULL_PRINT_RIGHTS);
securityOptions.setAllowUserFormData(false);
securityOptions.setOwnerPassword("top-secret");
securityOptions.setUserPassword("sharable");
// Change or set the document encryption password
SecurityManager securityManager = pdf.getSecurity();
securityManager.removePasswordsAndEncryption();
securityManager.makePdfDocumentReadOnly("secret-key");
securityManager.setSecurityOptions(securityOptions);
pdf.saveAs(Paths.get("assets/secured.pdf"));
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.security.PdfPrintSecurity;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Date;
// Load a PDF with password
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/encrypted.pdf"), "password");
// Edit the metadata
MetadataManager metadata = pdf.getMetadata();
metadata.setAuthor("Satoshi Nakamoto");
metadata.setKeywords("SEO, Friendly");
metadata.setModifiedDate(new Date().toString());
// Edit security settings to make PDF read-only
SecurityOptions securityOptions = new SecurityOptions();
securityOptions.setAllowUserCopyPasteContent(false);
securityOptions.setAllowUserAnnotations(false);
securityOptions.setAllowUserPrinting(PdfPrintSecurity.FULL_PRINT_RIGHTS);
securityOptions.setAllowUserFormData(false);
securityOptions.setOwnerPassword("top-secret");
securityOptions.setUserPassword("sharable");
// Change or set the document encryption password
SecurityManager securityManager = pdf.getSecurity();
securityManager.removePasswordsAndEncryption();
securityManager.makePdfDocumentReadOnly("secret-key");
securityManager.setSecurityOptions(securityOptions);
pdf.saveAs(Paths.get("assets/secured.pdf"));
Digital Signatures
IronPDF for Java allows for the secure signing of new or existing PDF files using either X509Certificate2
digital certificates in .pfx or .p12 format. By digitally signing a PDF, the file's authenticity is guaranteed and it cannot be altered without proper validation of the certificate. This enhances the reliability of the document.
If you're looking for a free way to generate a signing certificate, Adobe Reader has you covered. Simply follow the instructions outlined in the Adobe Digital ID tutorial.
In addition to the traditional digital signing process, IronPDF for Java also offers the option to sign PDFs using a handwritten signature image or company stamp image. This makes it easier for businesses to personalize their documents and add an extra layer of security.
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.signature.Signature;
import com.ironsoftware.ironpdf.signature.SignatureManager;
// Load PDF to be signed
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
// Load digital certificate
File path = new File("assets/Ironpdf.pfx");
byte[] certificate = new byte[(int)path.length()];
// Create a signature from the certificate
Signature signature = new Signature(certificate, "1234");
// Sign the PDF
SignatureManager manager = PDF.getSignature();
manager.SignPdfWithSignature(signature);
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.signature.Signature;
import com.ironsoftware.ironpdf.signature.SignatureManager;
// Load PDF to be signed
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
// Load digital certificate
File path = new File("assets/Ironpdf.pfx");
byte[] certificate = new byte[(int)path.length()];
// Create a signature from the certificate
Signature signature = new Signature(certificate, "1234");
// Sign the PDF
SignatureManager manager = PDF.getSignature();
manager.SignPdfWithSignature(signature);
Compress PDFs
IronPDF reduces PDF file size with its compressImages
method in the PdfDocument
class, making it easy to compress PDFs that include large images. This optimization leads to significant savings in storage space and cost while transmitting PDFs across email and other communication channels.
import com.ironsoftware.ironpdf.*;
import java.io.IOException;
import java.nio.file.Paths;
// Load a PDF from file
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/document.pdf"));
// Compress the images in the PDF
// Valid image compression values range from 1 to 100, where 100 represents 100% of the original image quality.
pdf.compressImages(60);
pdf.saveAs(Paths.get("assets/document_compressed.pdf"));
// You can also optionally scale down the image resolution according to its visible size in the PDF
pdf.compressImages(90, true);
pdf.saveAs(Paths.get("assets/document_scaled_compressed.pdf"));
import com.ironsoftware.ironpdf.*;
import java.io.IOException;
import java.nio.file.Paths;
// Load a PDF from file
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/document.pdf"));
// Compress the images in the PDF
// Valid image compression values range from 1 to 100, where 100 represents 100% of the original image quality.
pdf.compressImages(60);
pdf.saveAs(Paths.get("assets/document_compressed.pdf"));
// You can also optionally scale down the image resolution according to its visible size in the PDF
pdf.compressImages(90, true);
pdf.saveAs(Paths.get("assets/document_scaled_compressed.pdf"));
Editing PDF Content
Add Headers and Footers
IronPDF provides the ability to add custom HTML headers and footers to PDFs using the ChromePdfRenderOptions
and HtmlHeaderFooter
classes. IronPDF enables custom text headers and footers to be added to PDFs through the TextHeaderFooter
class, which allows specifying text for the left, right, or center regions of the header/footer. This includes the use of built-in templating tags like {date}, {time}, and {page}, or any other custom text desired.
HTML Header and Footer
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.headerfooter.HtmlHeaderFooter;
import java.io.IOException;
import java.nio.file.Paths;
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
// Build a footer using HTML, including template fields for page numbers
HtmlHeaderFooter footer = new HtmlHeaderFooter();
footer.setMaxHeight(15); // millimeters
footer.setHtmlFragment("<center><i>{page} of {total-pages}</i></center>");
footer.setDrawDividerLine(true);
pdf.addHtmlFooter(footer);
// Build a header using an image asset
HtmlHeaderFooter header = new HtmlHeaderFooter();
header.setMaxHeight(20); // millimeters
header.setHtmlFragment("<img src=\"logo.png\" />");
header.setBaseUrl("./assets/"); // Base URL for relative paths
pdf.addHtmlHeader(header);
try {
pdf.saveAs(Paths.get("assets/html_headers_footers.pdf"));
} catch (IOException e) {
throw new RuntimeException(e);
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.headerfooter.HtmlHeaderFooter;
import java.io.IOException;
import java.nio.file.Paths;
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
// Build a footer using HTML, including template fields for page numbers
HtmlHeaderFooter footer = new HtmlHeaderFooter();
footer.setMaxHeight(15); // millimeters
footer.setHtmlFragment("<center><i>{page} of {total-pages}</i></center>");
footer.setDrawDividerLine(true);
pdf.addHtmlFooter(footer);
// Build a header using an image asset
HtmlHeaderFooter header = new HtmlHeaderFooter();
header.setMaxHeight(20); // millimeters
header.setHtmlFragment("<img src=\"logo.png\" />");
header.setBaseUrl("./assets/"); // Base URL for relative paths
pdf.addHtmlHeader(header);
try {
pdf.saveAs(Paths.get("assets/html_headers_footers.pdf"));
} catch (IOException e) {
throw new RuntimeException(e);
}
Text Header and Footer
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.font.FontTypes;
import com.ironsoftware.ironpdf.headerfooter.TextHeaderFooter;
import com.ironsoftware.ironpdf.headerfooter.HeaderFooterOptions;
import java.io.IOException;
// Initialize HeaderFooterOptions object.
HeaderFooterOptions options = new HeaderFooterOptions();
PdfDocument pdf = PdfDocument.renderUrlAsPdf("http://www.google.com");
// Define a simple text header including the URL
TextHeaderFooter textHeader = new TextHeaderFooter();
textHeader.setDrawDividerLine(true);
textHeader.setCenterText("{url}");
textHeader.setFont(FontTypes.getHelvetica());
textHeader.setFontSize(12);
pdf.addTextHeader(textHeader, options);
// Define a footer including date and page numbers
TextHeaderFooter textFooter = new TextHeaderFooter();
textFooter.setDrawDividerLine(true);
textFooter.setFont(FontTypes.getArial());
textFooter.setFontSize(10);
textFooter.setLeftText("{date} {time}");
textFooter.setRightText("{page} of {total-pages}");
pdf.addTextFooter(textFooter, options);
try {
pdf.saveAs(Paths.get("assets/text_headers_footers.pdf"));
} catch (IOException e) {
System.out.println("Failed to save PDF");
throw new RuntimeException(e);
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.font.FontTypes;
import com.ironsoftware.ironpdf.headerfooter.TextHeaderFooter;
import com.ironsoftware.ironpdf.headerfooter.HeaderFooterOptions;
import java.io.IOException;
// Initialize HeaderFooterOptions object.
HeaderFooterOptions options = new HeaderFooterOptions();
PdfDocument pdf = PdfDocument.renderUrlAsPdf("http://www.google.com");
// Define a simple text header including the URL
TextHeaderFooter textHeader = new TextHeaderFooter();
textHeader.setDrawDividerLine(true);
textHeader.setCenterText("{url}");
textHeader.setFont(FontTypes.getHelvetica());
textHeader.setFontSize(12);
pdf.addTextHeader(textHeader, options);
// Define a footer including date and page numbers
TextHeaderFooter textFooter = new TextHeaderFooter();
textFooter.setDrawDividerLine(true);
textFooter.setFont(FontTypes.getArial());
textFooter.setFontSize(10);
textFooter.setLeftText("{date} {time}");
textFooter.setRightText("{page} of {total-pages}");
pdf.addTextFooter(textFooter, options);
try {
pdf.saveAs(Paths.get("assets/text_headers_footers.pdf"));
} catch (IOException e) {
System.out.println("Failed to save PDF");
throw new RuntimeException(e);
}
Outlines and Bookmarks
With the BookmarkManager
, developers can create a hierarchical structure of bookmarks within a PDF, allowing users to easily navigate to different sections within the document. To add a new bookmark, developers can use the add method, specifying the title and page number of the bookmark. Bookmarks can also be nested within other bookmarks to create a more organized structure.
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.bookmark.Bookmark;
import com.ironsoftware.ironpdf.bookmark.BookmarkManager;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;
// Load an existing PDF from the file system
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/book.pdf"));
// Add top-level bookmarks to pages of the PDF using their page indices
BookmarkManager bookmarks = pdf.getBookmark();
bookmarks.addBookMarkAtEnd("Author's Note", 2);
bookmarks.addBookMarkAtEnd("Table of Contents", 3);
bookmarks.addBookMarkAtEnd("Summary", 10);
bookmarks.addBookMarkAtEnd("References", 12);
// Retrieve a reference to the Summary bookmark so that we can add a sublist of bookmarks to it.
List<Bookmark> bookmarkList = bookmarks.getBookmarks();
Bookmark bookmark = bookmarkList.get(2);
bookmark.AddChildBookmark("Conclusion", 11);
// Save the PDF to the filesystem
pdf.saveAs(Paths.get("assets/bookmarked.pdf"));
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.bookmark.Bookmark;
import com.ironsoftware.ironpdf.bookmark.BookmarkManager;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;
// Load an existing PDF from the file system
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/book.pdf"));
// Add top-level bookmarks to pages of the PDF using their page indices
BookmarkManager bookmarks = pdf.getBookmark();
bookmarks.addBookMarkAtEnd("Author's Note", 2);
bookmarks.addBookMarkAtEnd("Table of Contents", 3);
bookmarks.addBookMarkAtEnd("Summary", 10);
bookmarks.addBookMarkAtEnd("References", 12);
// Retrieve a reference to the Summary bookmark so that we can add a sublist of bookmarks to it.
List<Bookmark> bookmarkList = bookmarks.getBookmarks();
Bookmark bookmark = bookmarkList.get(2);
bookmark.AddChildBookmark("Conclusion", 11);
// Save the PDF to the filesystem
pdf.saveAs(Paths.get("assets/bookmarked.pdf"));
Add and Edit Annotations
IronPDF allows adding "sticky note" style annotations to specific pages of a PDF using the AnnotationManager
and AnnotationOptions
classes. Developers can create text-based annotations by providing text and (x,y) coordinates as arguments to the AnnotationOptions
constructor, then use the addTextAnnotation
method of the AnnotationManager
to add the annotation to the desired page.
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.annotation.AnnotationIcon;
import com.ironsoftware.ironpdf.annotation.AnnotationManager;
import com.ironsoftware.ironpdf.annotation.AnnotationOptions;
import java.io.IOException;
import java.nio.file.Paths;
// Load an existing PDF from the filesystem
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/example.pdf"));
// Create an annotation to be placed at a specific location on a page.
AnnotationOptions annotation = new AnnotationOptions(
"This is a major title", // Title of the annotation
"This is the long 'sticky note' comment content...", // Content of the annotation
150, // x-axis coordinate location
250 // y-axis coordinate location
);
annotation.setIcon(AnnotationIcon.HELP);
annotation.setOpacity(0.9);
annotation.setPrintable(false);
annotation.setHidden(false);
annotation.setOpen(true);
annotation.setReadonly(true);
annotation.setRotateable(true);
// Add the annotation to a specific page of the PDF
AnnotationManager annotationManager = pdf.getAnnotation();
annotationManager.addTextAnnotation(annotation, 0);
// Save the PDF with the modifications
pdf.saveAs(Paths.get("assets/annotated.pdf"));
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.annotation.AnnotationIcon;
import com.ironsoftware.ironpdf.annotation.AnnotationManager;
import com.ironsoftware.ironpdf.annotation.AnnotationOptions;
import java.io.IOException;
import java.nio.file.Paths;
// Load an existing PDF from the filesystem
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/example.pdf"));
// Create an annotation to be placed at a specific location on a page.
AnnotationOptions annotation = new AnnotationOptions(
"This is a major title", // Title of the annotation
"This is the long 'sticky note' comment content...", // Content of the annotation
150, // x-axis coordinate location
250 // y-axis coordinate location
);
annotation.setIcon(AnnotationIcon.HELP);
annotation.setOpacity(0.9);
annotation.setPrintable(false);
annotation.setHidden(false);
annotation.setOpen(true);
annotation.setReadonly(true);
annotation.setRotateable(true);
// Add the annotation to a specific page of the PDF
AnnotationManager annotationManager = pdf.getAnnotation();
annotationManager.addTextAnnotation(annotation, 0);
// Save the PDF with the modifications
pdf.saveAs(Paths.get("assets/annotated.pdf"));
Stamping and Watermarking
IronPDF for Java has a powerful API that provides extensive capabilities for stamping and watermarking PDFs. With its easy-to-use interface, developers can quickly add images and HTML stamps to their PDFs with ease. Whether you need to add a company logo, a confidentiality notice, or a unique identifier, IronPDF has you covered. The API makes it simple to add eye-catching stamps to your PDFs, giving them a professional and personalized touch.
Stamp Text onto a PDF
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.TextStamper;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;
// Load the PDF from file
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
// Create a text stamper
TextStamper stamper1 = new TextStamper();
stamper1.setText("Hello World! Stamp One Here!");
stamper1.setFontFamily("Bungee Spice");
stamper1.setUseGoogleFont(true);
stamper1.setFontSize(100);
stamper1.setBold(true);
stamper1.setItalic(false);
stamper1.setVerticalAlignment(VerticalAlignment.TOP);
// Apply stamp to the PDF
PDF.applyStamp(stamper1);
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.TextStamper;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;
// Load the PDF from file
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
// Create a text stamper
TextStamper stamper1 = new TextStamper();
stamper1.setText("Hello World! Stamp One Here!");
stamper1.setFontFamily("Bungee Spice");
stamper1.setUseGoogleFont(true);
stamper1.setFontSize(100);
stamper1.setBold(true);
stamper1.setItalic(false);
stamper1.setVerticalAlignment(VerticalAlignment.TOP);
// Apply stamp to the PDF
PDF.applyStamp(stamper1);
Stamp an Image onto a PDF
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.stamp.ImageStamper;
// Load the PDF from file
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
// Create an image stamper with the path to the image
ImageStamper imageStamper = new ImageStamper(Paths.get("assets/logo.png"));
// Apply stamp to all pages
PDF.applyStamp(imageStamper);
// Apply stamp to specific pages
PDF.applyStamp(imageStamper, PageSelection.singlePage(2));
PDF.applyStamp(imageStamper, PageSelection.pageRange(0, 2));
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.stamp.ImageStamper;
// Load the PDF from file
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
// Create an image stamper with the path to the image
ImageStamper imageStamper = new ImageStamper(Paths.get("assets/logo.png"));
// Apply stamp to all pages
PDF.applyStamp(imageStamper);
// Apply stamp to specific pages
PDF.applyStamp(imageStamper, PageSelection.singlePage(2));
PDF.applyStamp(imageStamper, PageSelection.pageRange(0, 2));
Stamp a Barcode onto a PDF
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.BarcodeEncoding;
import com.ironsoftware.ironpdf.stamp.BarcodeStamper;
import com.ironsoftware.ironpdf.stamp.HorizontalAlignment;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;
// Load the PDF from file
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
// Create a barcode stamper with text and encoding type
BarcodeStamper barcodeStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.Code39);
// Set alignment of the barcode stamp
barcodeStamp.setHorizontalAlignment(HorizontalAlignment.LEFT);
barcodeStamp.setVerticalAlignment(VerticalAlignment.BOTTOM);
// Apply stamp to the PDF
PDF.applyStamp(barcodeStamp);
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.BarcodeEncoding;
import com.ironsoftware.ironpdf.stamp.BarcodeStamper;
import com.ironsoftware.ironpdf.stamp.HorizontalAlignment;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;
// Load the PDF from file
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
// Create a barcode stamper with text and encoding type
BarcodeStamper barcodeStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.Code39);
// Set alignment of the barcode stamp
barcodeStamp.setHorizontalAlignment(HorizontalAlignment.LEFT);
barcodeStamp.setVerticalAlignment(VerticalAlignment.BOTTOM);
// Apply stamp to the PDF
PDF.applyStamp(barcodeStamp);
Stamp a QR Code onto a PDF
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.BarcodeEncoding;
import com.ironsoftware.ironpdf.stamp.BarcodeStamper;
import com.ironsoftware.ironpdf.stamp.HorizontalAlignment;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;
// Load the PDF from file
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
// Create a QR code stamper with text and encoding type
BarcodeStamper QRStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.QRCode);
QRStamp.setHeight(50);
QRStamp.setWidth(50);
// Set alignment of the QR code stamp
QRStamp.setHorizontalAlignment(HorizontalAlignment.LEFT);
QRStamp.setVerticalAlignment(VerticalAlignment.BOTTOM);
// Apply stamp to the PDF
PDF.applyStamp(QRStamp);
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.BarcodeEncoding;
import com.ironsoftware.ironpdf.stamp.BarcodeStamper;
import com.ironsoftware.ironpdf.stamp.HorizontalAlignment;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;
// Load the PDF from file
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
// Create a QR code stamper with text and encoding type
BarcodeStamper QRStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.QRCode);
QRStamp.setHeight(50);
QRStamp.setWidth(50);
// Set alignment of the QR code stamp
QRStamp.setHorizontalAlignment(HorizontalAlignment.LEFT);
QRStamp.setVerticalAlignment(VerticalAlignment.BOTTOM);
// Apply stamp to the PDF
PDF.applyStamp(QRStamp);
Add a Watermark to a PDF
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
// Load the PDF from file
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
// HTML for the watermark
String html = "<h1> Example Title <h1/>";
// Set opacity for the watermark
int watermarkOpacity = 30;
// Apply the watermark to the PDF
PDF.applyWatermark(html, watermarkOpacity);
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
// Load the PDF from file
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
// HTML for the watermark
String html = "<h1> Example Title <h1/>";
// Set opacity for the watermark
int watermarkOpacity = 30;
// Apply the watermark to the PDF
PDF.applyWatermark(html, watermarkOpacity);
Using Forms in PDFs
IronPDF Java provides developers with a straightforward and efficient way to set and retrieve values from form text fields in a PDF document. Using the FormManager
class, developers can simply call the setFieldValue
method and provide the name of the desired text field and the value to be filled.
To retrieve a form field's value, the developer can access the field directly through FormManager
's collection of FormField
objects, using the relevant name or index. This level of control over form fields makes it easy for developers to work with dynamic and interactive PDF forms.
Create and Edit Forms
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import java.io.IOException;
import java.nio.file.*;
// Use Case 1: Create a PDF Form from HTML Form Markup
Path outputLocation = Paths.get("assets/BasicForm.pdf");
String formHTML = "<html>"
+ "<body>"
+ "<h2>Editable PDF Form</h2>"
+ "<form>"
+ "First name: <br> <input type='text' name='firstname' value=''> <br>"
+ "Last name: <br> <input type='text' name='lastname' value=''>"
+ "</form>"
+ "</body>"
+ "</html>";
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
renderOptions.setCreatePdfFormsFromHtml(true);
PdfDocument.renderHtmlAsPdf(formHTML, renderOptions).saveAs(outputLocation);
// Use Case 2: Writing Values to the PDF Form
PdfDocument form = PdfDocument.fromFile(outputLocation);
// Set the value of the firstname input field
form.getForm().setFieldValue("firstname", "Minnie");
// Set the value of the lastname input field
form.getForm().setFieldValue("lastname", "Mouse");
// Save the changes to the PDF Form
form.saveAs(Paths.get("assets/BasicForm_Filled.pdf"));
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import java.io.IOException;
import java.nio.file.*;
// Use Case 1: Create a PDF Form from HTML Form Markup
Path outputLocation = Paths.get("assets/BasicForm.pdf");
String formHTML = "<html>"
+ "<body>"
+ "<h2>Editable PDF Form</h2>"
+ "<form>"
+ "First name: <br> <input type='text' name='firstname' value=''> <br>"
+ "Last name: <br> <input type='text' name='lastname' value=''>"
+ "</form>"
+ "</body>"
+ "</html>";
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
renderOptions.setCreatePdfFormsFromHtml(true);
PdfDocument.renderHtmlAsPdf(formHTML, renderOptions).saveAs(outputLocation);
// Use Case 2: Writing Values to the PDF Form
PdfDocument form = PdfDocument.fromFile(outputLocation);
// Set the value of the firstname input field
form.getForm().setFieldValue("firstname", "Minnie");
// Set the value of the lastname input field
form.getForm().setFieldValue("lastname", "Mouse");
// Save the changes to the PDF Form
form.saveAs(Paths.get("assets/BasicForm_Filled.pdf"));
Fill Existing Forms
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.*;
// Load a PDF form from file
PdfDocument form = PdfDocument.fromFile("assets/pdfform.pdf");
// Set the value of the firstname input field
form.getForm().setFieldValue("firstname", "Minnie");
// Set the value of the lastname input field
form.getForm().setFieldValue("lastname", "Mouse");
// Save the changes to the PDF Form
form.saveAs(Paths.get("assets/BasicForm_Filled.pdf"));
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.*;
// Load a PDF form from file
PdfDocument form = PdfDocument.fromFile("assets/pdfform.pdf");
// Set the value of the firstname input field
form.getForm().setFieldValue("firstname", "Minnie");
// Set the value of the lastname input field
form.getForm().setFieldValue("lastname", "Mouse");
// Save the changes to the PDF Form
form.saveAs(Paths.get("assets/BasicForm_Filled.pdf"));
Send PDF for Printing
IronPDF's print method allows developers to easily integrate PDF printing into their applications. By simply calling the print method, the operating system's print dialog will open, providing users with the option to adjust printing settings such as the printer, paper size, and the number of copies.
import com.ironsoftware.ironpdf.PdfDocument;
import java.awt.print.PrinterException;
// Render HTML content to a PDF
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Created with IronPDF!</h1>");
try {
// Print the PDF
pdf.print();
} catch(PrinterException exception) {
System.out.println("Failed to print PDF");
exception.printStackTrace();
}
import com.ironsoftware.ironpdf.PdfDocument;
import java.awt.print.PrinterException;
// Render HTML content to a PDF
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Created with IronPDF!</h1>");
try {
// Print the PDF
pdf.print();
} catch(PrinterException exception) {
System.out.println("Failed to print PDF");
exception.printStackTrace();
}
Frequently Asked Questions
How can I install the IronPDF library in a Java project?
There are two ways to incorporate the IronPDF Library in a Java Project: Add IronPDF as a dependency in a Maven-configured Java Project or download the IronPDF JAR File and add it to the project classpath manually.
How do I edit the structure of a PDF document in Java using IronPDF?
You can edit the structure by adding, copying, or deleting pages, merging or splitting PDFs, and setting custom sizes, orientations, and margins using IronPDF's API.
Can I convert PDF documents to images with IronPDF?
Yes, IronPDF allows you to export pages of a PDF file into images using methods that provide options for image dimensions and DPI.
How can I add headers and footers to a PDF in Java?
IronPDF provides the ability to add custom HTML or text headers and footers to PDFs using the ChromePdfRenderOptions and respective classes for HTML or text.
What features does IronPDF offer for working with PDF forms?
IronPDF allows you to create and edit PDF forms, set and retrieve form field values, and manage form data effectively in Java applications.
How can I add a watermark to a PDF using IronPDF?
You can add a watermark to a PDF by specifying HTML content for the watermark and applying it with a specified opacity using IronPDF's applyWatermark method.
Is it possible to digitally sign a PDF with IronPDF?
Yes, IronPDF allows you to digitally sign a PDF using X509Certificate2 digital certificates in .pfx or .p12 format, enhancing document security.
How do I extract text and images from a PDF using IronPDF?
You can extract all text using the extractAllText method and retrieve images as BufferedImage objects with extractAllImages method from any PdfDocument.
Can I manipulate PDF metadata with IronPDF?
Yes, IronPDF allows you to modify metadata and security features, such as adding or editing metadata properties and setting encryption or password protections.
How can I compress PDF files with IronPDF?
IronPDF provides methods to compress images within PDFs, allowing you to reduce file size by adjusting image quality and resolution.