Home Web Front-end Front-end Q&A java html to pdf

java html to pdf

May 15, 2023 pm 03:37 PM

With the development of the Internet, more and more companies and individuals have begun to save and share their documents and information in electronic form. Among these electronic documents, the PDF format is undoubtedly one of the most popular and versatile formats, because it can be displayed in the same way on different platforms regardless of operating systems and applications, and it is also not easy to edit. Revise.

However, sometimes we need to convert some HTML pages or Java program output content into PDF format. At this time, we need to use some professional tools and technologies. This article introduces the specific steps and ideas of this process by explaining how the Java language uses some libraries and frameworks to realize the function of converting HTML and Java to PDF.

1. Use Flying Saucer to convert HTML to PDF

Flying Saucer is a Java CSS rendering engine specially used to convert XHTML, XML and CSS style sheets into PDF or image formats. It provides an easy-to-use API that can render complete and high-quality pages in PDF with features such as super fonts and CSS3.

1. Introduce the dependency library of Flying Saucer

Add the dependency in the pom.xml file as follows:

<dependency>    
    <groupId>org.xhtmlrenderer</groupId>    
    <artifactId>flying-saucer-pdf</artifactId>    
    <version>9.1.20</version>
</dependency>
Copy after login

2. Use the ITextRenderer object to convert HTML to PDF

Create a template through the following code and fill in the HTML content:

// DOM解析器
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
// 创建一个Model用于存储转换后的文档 
Document document = builder.newDocument(); 
 
// 读取html内容并转换为文档树 
StringReader reader = new StringReader("要转化为PDF的html格式内容"); 
InputSource source = new InputSource(reader); 
// 获取根元素 
Element root = document.getDocumentElement(); 
// 将html输入文档树种 
Node node = document.importNode(root, true); 
// 将html根元素加入文档树中 
document.appendChild(node); 
 
// 转化为PDF 
ITextRenderer renderer = new ITextRenderer(); 
renderer.setDocument(document, null); 
renderer.layout(); 
OutputStream out = new FileOutputStream(pdfUrl); 
renderer.createPDF(out);
Copy after login

2. Use iText to convert Java objects to PDF

In addition to converting HTML to PDF, we can also Convert Java objects to PDF files through the iText library. iText is a Java PDF operation library that provides the ability and operation API to generate PDF format files.

1. Introduce iText dependency

Add iText dependency library in Maven, as shown below:

<dependency>    
    <groupId>com.itextpdf</groupId>    
    <artifactId>itextpdf</artifactId>    
    <version>5.5.11</version>
</dependency>
Copy after login

2. Create PDF document object

// 创建pdf文件对象 
Document document = new Document(PageSize.A4); 
// 文件输出流 
OutputStream outputStream = new FileOutputStream("test.pdf"); 
// 将文件流作为输出对象 
PdfWriter.getInstance(document, outputStream); 
// 打开文件 
document.open(); 
// 向文件中添加段落,代码省略 
// 关闭文件 
document.close()
Copy after login

3 , Add content to the document

The following code can add Java objects to PDF:

// 添加文字 
Font font = new Font(); 
font.setStyle(Font.BOLD); 
font.setSize(18); 
Paragraph paragraph = new Paragraph("Hello World!", font); 
document.add(paragraph); 
 
// 添加表格 
PdfPTable table = new PdfPTable(3); 
table.addCell("Candidate ID"); 
table.addCell("Candidate Name"); 
table.addCell("Status"); 
for(int i=0;i<10;i++) { 
    table.addCell("00"+i); 
    table.addCell("Candidate "+i); 
    table.addCell("Selected"); 
}
document.add(table);
Copy after login

4. Output PDF file

Finally, the PDF file is exported through the file output stream Output:

// 文件输出流 
OutputStream outputStream = new FileOutputStream("test.pdf"); 
// 将文件流作为输出对象 
PdfWriter.getInstance(document, outputStream);
Copy after login

It can be seen that iText provides a rich API that can be used to create and manipulate PDF document objects, while Flying Saucer can handle complex CSS styles and XHTML tags well, converting HTML pages into Convert to PDF file. I believe that using these two tools, you will more easily convert HTML and Java program content into PDF files.

The above is the detailed content of java html to pdf. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do you connect React components to the Redux store using connect()? How do you connect React components to the Redux store using connect()? Mar 21, 2025 pm 06:23 PM

Article discusses connecting React components to Redux store using connect(), explaining mapStateToProps, mapDispatchToProps, and performance impacts.

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

How do you define routes using the <Route> component? How do you define routes using the <Route> component? Mar 21, 2025 am 11:47 AM

The article discusses defining routes in React Router using the &lt;Route&gt; component, covering props like path, component, render, children, exact, and nested routing.

What are the limitations of Vue 2's reactivity system with regard to array and object changes? What are the limitations of Vue 2's reactivity system with regard to array and object changes? Mar 25, 2025 pm 02:07 PM

Vue 2's reactivity system struggles with direct array index setting, length modification, and object property addition/deletion. Developers can use Vue's mutation methods and Vue.set() to ensure reactivity.

What are Redux reducers? How do they update the state? What are Redux reducers? How do they update the state? Mar 21, 2025 pm 06:21 PM

Redux reducers are pure functions that update the application's state based on actions, ensuring predictability and immutability.

What are Redux actions? How do you dispatch them? What are Redux actions? How do you dispatch them? Mar 21, 2025 pm 06:21 PM

The article discusses Redux actions, their structure, and dispatching methods, including asynchronous actions using Redux Thunk. It emphasizes best practices for managing action types to maintain scalable and maintainable applications.

What are the benefits of using TypeScript with React? What are the benefits of using TypeScript with React? Mar 27, 2025 pm 05:43 PM

TypeScript enhances React development by providing type safety, improving code quality, and offering better IDE support, thus reducing errors and improving maintainability.

How can you use useReducer for complex state management? How can you use useReducer for complex state management? Mar 26, 2025 pm 06:29 PM

The article explains using useReducer for complex state management in React, detailing its benefits over useState and how to integrate it with useEffect for side effects.

See all articles