在 Java 中将 HTML 或二进制文件转换为 PDF 可以使用不同的方式,以下是一些实现方式,每种方式都会提供详细的步骤流程和示例代码。
步骤流程:
添加依赖:
<!-- Maven -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.2</version>
</dependency>
// Gradle
implementation 'com.itextpdf:itextpdf:5.5.13.2'
编写代码:
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
public class HtmlToPdfConverter {
public static void convertHtmlToPdf(String htmlContent, String outputPath) throws Exception {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputPath));
document.open();
ByteArrayInputStream inputStream = new ByteArrayInputStream(htmlContent.getBytes());
XMLWorkerHelper.getInstance().parseXHtml(writer, document, inputStream);
document.close();
}
public static void main(String[] args) {
try {
String htmlContent = "<html><body><h1>Hello, World!</h1></body></html>";
String outputPath = "output.pdf";
convertHtmlToPdf(htmlContent, outputPath);
System.out.println("PDF generated successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
步骤流程:
添加依赖:
<!-- Maven -->
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-core</artifactId>
<version>9.1.22</version>
</dependency>
// Gradle
implementation 'org.xhtmlrenderer:flying-saucer-core:9.1.22'
编写代码:
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.FileOutputStream;
public class HtmlToPdfConverter {
public static void convertHtmlToPdf(String htmlContent, String outputPath) throws Exception {
try (FileOutputStream outputStream = new FileOutputStream(outputPath)) {
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(htmlContent);
renderer.layout();
renderer.createPDF(outputStream);
renderer.finishPDF();
}
}
public static void main(String[] args) {
try {
String htmlContent = "<html><body><h1>Hello, World!</h1></body></html>";
String outputPath = "output.pdf";
convertHtmlToPdf(htmlContent, outputPath);
System.out.println("PDF generated successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
这两种方式都可以将 HTML 内容转换为 PDF,选择其中一种适合你的项目需求和技术栈。记得根据你的项目需要修改 HTML 内容和输出路径。