Java (483)

PDF is a cornerstone for document sharing across diverse platforms. In Java development, the ability to generate PDF in Java efficiently is a common requirement for applications ranging from invoicing systems to report generators. Among the myriad libraries available, Spire.PDF for Java stands out as a robust solution. This comprehensive guide explores how to use this powerful Java library to create PDF files from scratch, from templates or from HTML.
- Getting Started with Spire.PDF for Java
- Background: The Coordinate System
- Generate a Basic PDF in Java
- Create PDF from Template in Java
- Bonus: Generate PDF from HTML in Java
- Conclusion
- Frequently Asked Questions (FAQs)
Getting Started with Spire.PDF for Java
Spire.PDF for Java is a robust library simplifies PDF generation in Java without Adobe dependencies. Key features:
- Cross-Platform Support: Runs seamlessly on Windows, Linux, and macOS.
- Rich Content Creation: Add text, images, tables, lists, and barcodes.
- Advanced Security: Apply passwords, digital signatures, and permission controls.
- Easy Integration: Works seamlessly with Java SE and EE environments.
Setup & Installation
To start creating PDF in Java, you first need to add Spire.PDF for Java to your project. You can download the JAR files from the E-iceblue website or add it as a Maven dependency:
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf</artifactId>
<version>12.6.1</version>
</dependency>
</dependencies>
Background: The Coordinate System
In Spire.PDF for Java, the coordinate system defines the positioning of elements (text, images, shapes) on a PDF page. Here’s the key concepts:
- Origin Point (0,0): The origin of the coordinate system is located at the top-left corner of the content area.
- X-axis: Extends horizontally from the left to the right.
- Y-axis: Extends vertically from the top downward.

Generate a Basic PDF in Java
Let’s start with a simple example of creating a PDF document with text. Spire.PDF for Java provides two methods to draw text on a PDF page:
- PdfCanvas.drawString(): Draws single-line text at exact coordinates. Best for headings, labels, or short text snippets.
- PdfTextWidget.draw(): Manages multi-line text with automatic word wrapping and line breaks. Best for paragraphs, long content, paginated text.
Here's the Jave code to create PDF:
import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
public class CreatePdfDocument {
public static void main(String[] args) {
// Create a PdfDocument object
PdfDocument pdf = new PdfDocument();
// Add a page with specified size and margin
PdfPageBase page = pdf.getPages().add(PdfPageSize.A4, new PdfMargins(35f));
// Specify page content
String titleText = "Spire.PDF for Java";
String paraText = "Spire.PDF for Java is a PDF API that enables Java applications to read, write and save PDF documents. " +
"Using this Java PDF component, developers and programmers can implement rich capabilities to" +
"create PDF files from scratch or process existing PDF documents entirely on Java applications (J2SE and J2EE). " +
"Spire.PDF for Java is a totally independent Java PDF library. " +
"It does not require Adobe Acrobat or any other 3rd party software/library installed on system.";
// Create solid brushes
PdfSolidBrush titleBrush = new PdfSolidBrush(new PdfRGBColor(Color.BLUE));
PdfSolidBrush paraBrush = new PdfSolidBrush(new PdfRGBColor(Color.BLACK));
// Create true type fonts
PdfTrueTypeFont titleFont = new PdfTrueTypeFont(new Font("Times New Roman",Font.BOLD,18));
PdfTrueTypeFont paraFont = new PdfTrueTypeFont(new Font("Times New Roman",Font.PLAIN,12));
// Set the text alignment via PdfStringFormat class
PdfStringFormat format = new PdfStringFormat();
format.setAlignment(PdfTextAlignment.Center);
// Draw title on the page
page.getCanvas().drawString(titleText, titleFont, titleBrush, new Point2D.Float((float)page.getClientSize().getWidth()/2, 40),format);
// Create a PdfTextWidget object to hold the paragraph content
PdfTextWidget widget = new PdfTextWidget(paraText, paraFont, paraBrush);
// Create a rectangle where the paragraph content will be placed
Rectangle2D.Float rect = new Rectangle2D.Float(0, 70, (float)page.getClientSize().getWidth(),(float)page.getClientSize().getHeight());
// Set the PdfLayoutType to Paginate to make the content paginated automatically
PdfTextLayout layout = new PdfTextLayout();
layout.setLayout(PdfLayoutType.Paginate);
// Draw paragraph text on the page
widget.draw(page, rect, layout);
// Save the PDF file
pdf.saveToFile("CreatePdfDocument.pdf");
pdf.dispose();
}
}
The code creates a PDF with a centered title and a paragraph that automatically paginates if it exceeds the page height.
The generated PDF file:

Beyond simple text, you can also add other elements to PDF, such as:
Add Images to PDF
Add images (JPG, PNG, etc.) at specified locations on a PDF page:
//Load an image
PdfImage image = PdfImage.fromFile("image.jpg");
//Specify the width and height of the image area on the page
float width = image.getWidth() * 0.50f;
float height = image.getHeight() * 0.50f;
//Draw the image at a specified location on the page
page.getCanvas().drawImage(image, 100f, 60f, width, height);
Add Tables to PDF
Organize data with tables, a useful feature when you generate PDF reports:
//Create a PdfTable object
PdfTable table = new PdfTable();
//Define data
String[] data = {"ID;Name;Department;Position",
"1; David; IT; Manager",
"3; Julia; HR; Manager",
"4; Sophie; Marketing; Manager",
"7; Wickey; Marketing; Sales Rep",
"9; Wayne; HR; HR Supervisor",
"11; Mia; Dev; Developer"};
String[][] dataSource = new String[data.length][];
for (int i = 0; i < data.length; i++) {
dataSource[i] = data[i].split("[;]", -1);
}
//Set data as the table data
table.setDataSource(dataSource);
//Set the first row as header row
table.getStyle().setHeaderSource(PdfHeaderSource.Rows);
table.getStyle().setHeaderRowCount(1);
//Show header(the header is hidden by default)
table.getStyle().setShowHeader(true);
//Draw table on the page
table.draw(page, new Point2D.Float(0, 30));
Refer to: Create Tables in PDF in Java
Create PDF from Template in Java
This Java code demonstrates how to generate a PDF by dynamically replacing placeholders in a pre-designed PDF template. Common use cases include generating emails, reports, invoice or contracts.
import com.spire.pdf.*;
import com.spire.pdf.texts.PdfTextReplaceOptions;
import com.spire.pdf.texts.PdfTextReplacer;
import com.spire.pdf.texts.ReplaceActionType;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
public class GeneratePdfFromTemplate
{
public static void main(String[] args)
{
// Create a PdfDocument object
PdfDocument pdf = new PdfDocument();
// Load a template
pdf.loadFromFile("PdfTemplate.pdf");
// Create a PdfTextReplaceOptions object
PdfTextReplaceOptions textReplaceOptions = new PdfTextReplaceOptions();
// Specify the replace options
textReplaceOptions.setReplaceType(EnumSet.of(ReplaceActionType.IgnoreCase));
textReplaceOptions.setReplaceType(EnumSet.of(ReplaceActionType.WholeWord));
// Get the first page
PdfPageBase page = pdf.getPages().get(0);
// Create a PdfTextReplacer object based on the page
PdfTextReplacer textReplacer = new PdfTextReplacer(page);
// Set replace options
textReplacer.setOptions(textReplaceOptions);
// Specify the placeholder-value pairs in a map
Map<String, String> replacements = new HashMap<>();
replacements.put("{name}", "John Smith");
replacements.put("{date}", "2023-10-05");
replacements.put("{number}", "ID0001265");
replacements.put("{address}", "123 Northwest Freeway, Houston, Texas USA 77040");
// Iterate over the map to replace each placeholder
for (Map.Entry<String, String> entry : replacements.entrySet())
{
textReplacer.replaceAllText(entry.getKey(), entry.getValue());
}
// Save the result PDF
pdf.saveToFile("GeneratePDFromTemplate.pdf");
pdf.dispose();
}
}
Explanation:
Here are some core components for the template-based PDF generation:
- PdfTextReplaceOptions: Defines how replacements are performed (case-insensitive, whole words).
- PdfTextReplacer: Represents the text replacement in a PDF page.
- replaceAllText(): Replaces all occurrences of old text (a placeholder like "{name}") with new text (e.g., "John Smith").
Output:

Bonus: Generate PDF from HTML in Java
Spire.PDF for Java also provides intuitive APIs to convert web URLs, local HTML files, or raw HTML strings to PDF files. For a comprehensive implementation guide, refer to:
Convert HTML to PDF in Java – URLs and HTML Strings/ Files
By mastering the HTML to PDF conversion, Java developers can automate invoice/report generation from web templates, or archive web pages as searchable PDFs.
Conclusion
Spire.PDF for Java provides an efficient way to generate PDF in Java—whether creating basic documents, generating PDFs from HTML or templates. By following the examples in this article, you can quickly integrate professional PDF creation in your Java projects.
Explore Full Features: Spire.PDF for Java Online Documentation
Frequently Asked Questions (FAQs)
Q1: Is Spire.PDF for Java free?
A: Spire.PDF for Java offers both commercial and free versions (with limitations). You can request a trial license to test the commercial version without any restrictions.
Q2: Does it support non-English languages (e.g., Chinese, Japanese)?
A: Yes, use the font that supports the target language. For example:
// To display Chinese text, use a font like "SimSun" or "Microsoft YaHei"
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("SimSun", Font.PLAIN, 12));
// To display Japanese text, use a font like "MS Gothic" or "Yu Gothic"
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("MS Gothic", Font.PLAIN, 12));
Q3: How to secure PDFs with passwords?
A: Set open/permission passwords:
// Create a password-based security policy with open and permission passwords
PdfSecurityPolicy securityPolicy = new PdfPasswordSecurityPolicy("openPwd", "permissionPwd");
// Set the encryption algorithm to AES 256-bit
securityPolicy.setEncryptionAlgorithm(PdfEncryptionAlgorithm.AES_256);
// Encrypt the PDF file
pdf.encrypt(securityPolicy);

QR codes have become an integral part of modern digital interactions, enabling seamless data sharing through scannable patterns. If you’re looking to generate QR codes in Java, the Spire.Barcode for Java library offers a robust, user-friendly solution.
This comprehensive guide will walk you through every aspect of creating QR code in Java, including setup, basic QR code generation, logo integration, advanced customization, and industry best practices.
- Java Barcode Generator Library
- How to Generate a QR Code in Java
- Generate a QR Code with a Logo in Java
- Customize QR Code Options
- Best Practices for QR Code Generation
- Conclusion
Java Barcode Generator Library
Spire.Barcode for Java is a lightweight, high-performance library designed to generate and read 1D and 2D barcodes, including QR codes, Data Matrix, Code 128, and more. It stands out for its:
- Ease of use: Minimal code required to generate barcodes.
- Customization options: Adjust size, color, error correction, and add logos.
- Compatibility: Supports Java SE 6.0 and above, and integrates with popular IDEs like IntelliJ and Eclipse.
- Output flexibility: Export QR codes to common image formats (PNG, JPG, BMP, etc.).
Spire.Barcode simplifies QR code generation with pre-built classes for configuration and rendering. Download it to manually import or add it to your project using Maven:
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.barcode</artifactId>
<version>5.2.0</version>
</dependency>
</dependencies>
Tip: Request a free trial license here to remove evaluation message and watermarks.
You can also use the Free Version to process barcodes:
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.barcode.free</artifactId>
<version>5.2.1</version>
</dependency>
How to Generate a QR Code in Java
Creating a standard QR code with Spire.Barcode for Java involves just a few steps. This example generates a QR code that encodes a URL and saves it as a PNG image.
Key Components:
- BarcodeSettings: Configures all properties of the QR code.
- setType(): Specifies the QR code type (other types like Code 128 are also supported).
- setData(): Defines the content to encode (URL, text, numbers, etc.).
- setX(): Sets the width of each "module" (the tiny squares in the QR code).
- setQRCodeECL(): Defines error correction level.
- generateImage(): Uses the settings to render the QR code as a BufferedImage.
- ImageIO.write(): Saves the image to a file (PNG, JPG, or other formats).
Java code to create a QR code:
import com.spire.barcode.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class GenerateQRcode {
public static void main(String[] args) throws IOException {
// Create a BarcodeSettings object
BarcodeSettings settings = new BarcodeSettings();
// Set the barcode type to QR Code
settings.setType(BarCodeType.QR_Code);
// Set the QR code data
settings.setData("https://www.e-iceblue.com/");
// Set to not display the encoded text (the URL)
settings.setShowText(false);
// Set width of the barcode module
settings.setX(2);
// Set the error correction level
settings.setQRCodeECL(QRCodeECL.M);
// Set the data mode
settings.setQRCodeDataMode(QRCodeDataMode.Auto);
// Create BarCodeGenerator object based on settings
BarCodeGenerator barCodeGenerator = new BarCodeGenerator(settings);
// Generates QR code as a BufferedImage (in-memory image object)
BufferedImage bufferedImage = barCodeGenerator.generateImage();
// Save the generated QR code image in PNG format
ImageIO.write(bufferedImage,"png",new File("QR_Code.png"));
}
}
Output: A basic QR code image in PNG format. When scanned, the user will be directed to the specified URL address.

Integrate with the Spire.PDF for Java library to add the QR code image to a PDF document.
Generate a QR Code with a Logo in Java
Adding a logo to a QR code enhances brand visibility while maintaining scannability. Spire.Barcode for Java simplifies this by allowing you to overlay an image onto the QR code via the setQRCodeLogoImage() method.
Key Considerations:
- Use a small logo (10-20% of QR code size) to avoid disrupting data patterns.
- Ensure high contrast between the logo and QR code background.
Java code to generate a QR code with embedded logo:
import com.spire.barcode.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class QRcodeWithLogo {
public static void main(String[] args) throws IOException {
// Create a BarcodeSettings object
BarcodeSettings settings = new BarcodeSettings();
// Set the barcode type to QR Code
settings.setType(BarCodeType.QR_Code);
// Set the QR code data (URL, text, numbers, etc.)
settings.setData("https://www.e-iceblue.com/");
// Set to not display the encoded text (the URL)
settings.setShowText(false);
// Set width of the barcode module
settings.setX(3);
// Set the error correction level
settings.setQRCodeECL(QRCodeECL.H);
// Set the data mode
settings.setQRCodeDataMode(QRCodeDataMode.Auto);
// Load an image and set it as the logo image for the QR code
BufferedImage image = ImageIO.read(new File("logo.png"));
settings.setQRCodeLogoImage(image);
// Create BarCodeGenerator object based on settings
BarCodeGenerator barCodeGenerator = new BarCodeGenerator(settings);
// Generates QR code as a BufferedImage (in-memory image object)
BufferedImage bufferedImage = barCodeGenerator.generateImage();
// Save the generated QR code image in PNG format
ImageIO.write(bufferedImage,"png",new File("QrCodeWithLogo.png"));
}
}
Output: A PNG image file containing a scannable QR code with a centered logo.

Need to scan the QR code in Java? Refer to: How to Read Barcodes in Java Using Spire.Bacode
Customize QR Code Options
Spire.Barcode for Java lets you tailor QR codes to match your design requirements. Below are key customization options:
1. Add Display Text (Top/Bottom Labels)
Add descriptive text above or below the QR code and set its formatting (font, color, alignment).
// Enable top and bottom text
settings.setShowTopText(true);
settings.isShowBottomText(true);
// Set text content
settings.setTopText("Scan to Visit Our Site");
settings.setBottomText("Example Corp © 2025");
// Customize text appearance
settings.setTopTextFont("Arial", 14.0f);
settings.setTopTextColor(Color.BLUE);
settings.setTopTextMargin(1.0f);
settings.setBottomTextFont("Calibri", 12.0f, FontStyle.Italic);
settings.setBottomTextColor(Color.GRAY);
// Align text (Near, Center, Far)
settings.setTopTextAligment(StringAlignment.Center);
settings.setBottomTextAlignment(StringAlignment.Far);

2. Customize Borders & Quiet Zones
The "quiet zone" is a blank (usually white) area surrounding the QR code (and its border). It’s critical for scanners to recognize where the QR code starts and ends.
Spire.Barcode for Java allows you to set both the visible border and quiet zone:
// Enable border
settings.hasBorder(true);
// Set border properties
settings.setBorderColor(Color.BLUE); // Border color
settings.setBorderWidth(1); // Border thickness
settings.setBorderDashStyle(3); // Dashed border (options: Solid, Dash, Dot, etc.)
// Set border margins
// These margins create the "quiet zone" around the QR code
settings.setLeftMargin(8);
settings.setRightMargin(8);
settings.setTopMargin(8);
settings.setBottomMargin(8);

3. Change Colors
Modify the QR code’s foreground (data) and background colors to match your brand:
// Set foreground color (black by default)
settings.setForeColor(Color.GRAY);
// Set background color (white by default)
settings.setBackColor(new Color(250, 243, 202));

Best Practices for QR Code Generation
Follow these guidelines for professional QR implementations:
- Error Correction Level: Choose wisely:
- L (Low): 7% data recovery
- M (Medium): 15% recovery
- Q (Quartile): 25% recovery
- H (High): 30% recovery (best for logos)
- Optimal Size: Minimum 22 cm (0.8x0.8 in) for print, 200200 px for digital
- Contrast: Ensure high contrast between code and background
- Test Scannability: Always verify your QR codes with multiple devices/ scanner apps
Conclusion
Generating QR codes in Java is straightforward with libraries like Spire.Barcode. Whether you need a basic QR code encoding text/URL, a branded code with a logo, or a fully customized design, this library provides the tools to achieve it efficiently. By following the examples and best practices outlined in this guide, you’ll be able to integrate professional-grade QR codes into your Java applications, enhancing user experience and enabling seamless data sharing.
This article presents how to import Spire.Barcode.jar in Java application and create barcode image using the classes involved.
Import Spire.Barcode.jar file
Step 1: Download Spire.Barcode for Java from the following URL. Unzip the package into a directory, you'll get Spire.Barcode.jar and Spire.Common.jar in the lib folder.
Step 2: Create a Java project in Eclipse.
Step 3: Right click the project name, select "New" - "Folder" to create a folder named "Lib".

Step 4: Copy the Spire.Barcode.jar file and Spire.Common.jar file to this folder.

Step 5: Select all the jar files, then right click on one of them and select "Build Path" – "Add to Build Path".

Until now, Spire.Barcode.jar and Spire.Common.jar have been referenced in your Java project. Expand the specific jar file in the “Package Explore” pane, and you’ll be able to view the classes, methods, properties, etc. inside the jar file.

Using the code
Following code snippet provides an example of creating Code 128 barcode using Spire.Barcode for Java.
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.spire.barcode.BarCodeGenerator;
import com.spire.barcode.BarCodeType;
import com.spire.barcode.BarcodeSettings;
public class CODE_128 {
public static void main(String[] args) throws IOException {
//create an instance of BarcodeSetteings
BarcodeSettings settings = new BarcodeSettings();
//set barcode type
settings.setType(BarCodeType.CODE_128);
//set barcode data
settings.setData("123456789");
//set the display text
settings.setData2D("123456789");
//show text on bottom
settings.setShowTextOnBottom(true);
//set the border invisible
settings.hasBorder(false);
//create BarCodeGenerator object based on settings
BarCodeGenerator barCodeGenerator = new BarCodeGenerator(settings);
//generate image data and store in BufferedImage instance
BufferedImage bufferedImage = barCodeGenerator.generateImage();
//save to .png file format
ImageIO.write(bufferedImage, "png", new File("CODE128.png"));
System.out.println("Complete!");
}
}
Output:
