How to Write PDF File in Java

The PDF format is widely used in today's digital world due to its universal compatibility and its ability to preserve the formatting of a document. While there are many tools available to create PDFs, in some cases, it may be necessary to generate PDFs programmatically. This may be necessary when a large number of PDFs need to be created automatically, or when the creative process needs to be integrated into an existing software system. Creating PDFs programmatically requires a deep understanding of the PDF format and the ability to manipulate it using programming languages.

In this article, we will explore IronPDF for creating PDF documents programmatically. We will also provide examples and code snippets to demonstrate how to create PDFs programmatically using the IronPDF C# PDF Library. By the end of this article, readers will have a good understanding of how to generate PDFs programmatically and of the tools available to help them achieve their goals.

IronPDF for Java PDF Library

The IronPDF for Java PDF library allows developers to create, edit, and manipulate PDF documents in their Java applications. Java developers who need to create PDF files from their applications' data will find this library to be an excellent choice because it offers a diverse set of functionalities.

IronPDF comes with features such as adding new HTML content, adding HTML headers and footers, stamping and watermarking documents, creating password-protected PDF files, digitally signing PDF files, adding backgrounds and foregrounds, creating a full PDF file from XML documents, adding and editing annotations, and creating outlines and bookmarks. Let's take a closer look.

Add New HTML Content

With IronPDF, developers can easily add new HTML content to their PDF documents. This is a great feature for developers who want to dynamically generate their PDF form documents with rich HTML content. The library supports many HTML elements, including images, links, and tables, among others. HTML content can also be styled using CSS, making it easy to create professional-looking PDFs.

import com.ironsoftware.ironpdf.*;  
import java.io.IOException;  
import java.nio.file.Paths;  

// Apply your license key
License.setLicenseKey("YOUR-LICENSE-KEY");

// Set a log path
Settings.setLogPath(Paths.get("C:/tmp/IronPdfEngine.log"));

// Render the HTML as a PDF. Stored in myPdf as type PdfDocument;
PdfDocument myPdf = PdfDocument.renderHtmlAsPdf("<h1> ~Hello World~ </h1> Made with IronPDF!");

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

Output PDF

Add HTML Headers and Footers

Headers and footers are essential components of many PDF documents, and IronPDF makes it easy to add HTML headers and footers to your documents. With IronPDF, developers can add custom headers and footers to their PDF documents, including text, images, and page numbers. This feature is particularly useful for businesses that need to add branding or copyright information to their documents.

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
// Merge Fields are: {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
HtmlHeaderFooter footer = new HtmlHeaderFooter();
footer.setMaxHeight(15); // millimeters
footer.setHtmlFragment("<center><i>{page} of {total-pages}</i></center>");
footer.setDrawDividerLine(true);
pdf.addHtmlFooter(footer);
List<PdfDocument> pdfs = new ArrayList<>();

// Build a header using an image asset
// Note the use of BaseUrl to set a relative path to the assets
HtmlHeaderFooter header = new HtmlHeaderFooter();
header.setMaxHeight(20); // millimeters
header.setHtmlFragment("<img src=\"logo.png\" />");
header.setBaseUrl("./assets/");
pdf.addHtmlHeader(header);
try {
    pdf.saveAs(Paths.get("assets/html_headers_footers.pdf"));
} catch (IOException e) {
    throw new RuntimeException(e);
}
JAVA
Output PDF

Output PDF

Stamp & Watermark

Using IronPDF, developers can add stamps and watermarks to their PDF documents. Watermarks are transparent images or text that appear in the document's background, while stamps add a custom message or image to a new document.

These features are great for businesses that need to protect their documents from unauthorized use or to add a custom message to their documents.

package IronPDF.ironpdf_java;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.stamp.HorizontalAlignment;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;

public class test {
    public static void main (String[] args) throws IOException {
        License.setLicenseKey("Your-License");
        // Create a new PDF or load an existing one from the filesystem
        PdfDocument pdf = PdfDocument.fromFile(Paths.get("C:\\byteToPdf.pdf"));

        pdf.applyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, VerticalAlignment.TOP, HorizontalAlignment.CENTER);

        pdf.saveAs(Paths.get("assets/watermark.pdf"));
    }
}
JAVA
Output PDF

Output PDF

Backgrounds & Foregrounds

IronPDF also allows developers to add custom backgrounds and foregrounds to their PDF documents. Foregrounds are used to add custom text or images on top of a document, while backgrounds add a custom image or color to the background. Business owners who want their documents or PDF forms to have custom branding or graphics will find this feature particularly useful.

import com.ironsoftware.ironpdf.*;  
import java.io.IOException;  
import java.nio.file.Paths;

// Load background and foreground PDFs from the filesystem (or create them programmatically)  
PdfDocument backgroundPdf = PdfDocument.fromFile(Paths.get("assets/MyBackground.pdf"));  
PdfDocument foregroundPdf = PdfDocument.fromFile(Paths.get("assets/MyForeground.pdf"));  

// Render content (HTML, URL, etc) as a PDF Document  
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://www.nuget.org/packages/IronPdf");  

// Add the background and foreground PDFs to the newly-rendered document.  
pdf.addBackgroundPdf(backgroundPdf);  
pdf.addForegroundPdf(foregroundPdf);  

pdf.saveAs(Paths.get("assets/BackgroundForegroundPdf.pdf"));
JAVA

Add & Edit Annotations

Annotations are a great way to add additional information to PDF documents, such as notes, comments, or highlights. With IronPDF, developers can easily add and edit annotations to their PDF documents.

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;

// Create a new PDF or load an existing one 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"));
JAVA
Output File

Output File

Outlines & Bookmarks

Developers can create PDF documents with bookmarks using IronPDF. An outline provides a high-level overview of the contents of a document, while bookmarks provide quick access to specific sections. For large or complex documents, this feature allows users to navigate quickly to their desired sections.

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 (or create a new one from HTML)
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"));
JAVA

Summary

This article explores various features of IronPDF, such as the ability to add annotations, bookmarks, HTML content, background and foreground colors, and headers and footers to PDF documents. The article provides step-by-step instructions for implementing these features using IronPDF, making it easy for developers to create professional-looking PDF documents that meet their specific needs.

Whether you're building a web application or a desktop application, IronPDF can help you streamline the process of generating PDF documents, saving you time and effort while ensuring that your documents look great.

The license starts from $749. IronPDF also offers a free trial, allowing developers to test the library and evaluate its capabilities before making a purchase decision. During the trial period, users have access to all the features of the library, including support and updates. After the trial period, users can choose to purchase a license to continue using the library. The pricing for IronPDF varies depending on the number of developers using the library and the type of license.