21xrx.com
2025-06-02 06:10:46 Monday
文章检索 我的文章 写文章
Java生成HTML转PDF实现及代码案例
2023-06-15 16:34:34 深夜i     32     0
Java HTML PDF

在很多场景中,我们需要将HTML文件转换成PDF文件,这个过程需要借助一些工具或者库。在Java开发中,如果我们需要实现HTML转PDF的功能,就可以使用Itext来实现。

Itext是一个Java PDF处理库,可以生成PDF文档,以及将FTP文件或PDF格式的文件合并。同时,Itext也支持将HTML文件转换成PDF文件的功能。

下面是一个简单的代码案例:

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import java.io.*;
import java.nio.charset.Charset;
public class HtmlToPdf {
  public static void main(String[] args) throws IOException, DocumentException {
    String htmlContent = "
Hello World!
这是一个HTML转PDF的简单案例"; 
    String pdfPath = "D:/test.pdf";
    htmlToPdf(htmlContent, pdfPath);
  }
  public static void htmlToPdf(String htmlContent, String pdfPath) throws IOException, DocumentException {
    OutputStream outputStream = new FileOutputStream(new File(pdfPath));
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    document.open();
    InputStream inputStream = new ByteArrayInputStream(htmlContent.getBytes(Charset.forName("UTF-8")));
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, inputStream, Charset.forName("UTF-8"));
    document.close();
    outputStream.close();
  }
}

以上代码中,我们先定义了一个HTML字符串,然后将其传入方法`htmlToPdf`中,最后输出PDF文件,并将其保存到指定路径下。

  
  

评论区