借助Spire.Doc for Java控件,在Java中将 HTML 文件转换为 PDF

Spire.Doc 是一款专门对 Word 文档进行操作的 类库。在于帮助开发人员无需安装 Microsoft Word情况下,轻松快捷高效地创建、编辑、转换和打印 Microsoft Word 文档。拥有近10年专业开发经验Spire系列办公文档开发工具,专注于创建、编辑、转换和打印Word/PDF/Excel等格式文件处理,小巧便捷,除此之外,你也可以浏览E-iceblue 旗下其他不同语言的文档开发工具~

本文将演示如何在 Java 应用程序中使用 Spire.Doc for Java 将 HTML 字符串和 HTML 文件转换为 PDF(qun:767755948)

HTML 字符串转 PDF

Java 将 HTML 转换为 PDF

import com.spire.doc.*;
import java.io.*;

public class htmlStringToWord {

public static void main(String[] args) throws Exception {

String inputHtml = "InputHtml.txt";
//Create a new document
Document document = new Document();
//Add a section
Section sec = document.addSection();

String htmlText = readTextFromFile(inputHtml);
//add a paragraph and append html string.
sec.addParagraph().appendHTML(htmlText);

//Save to PDF
document.saveToFile("HTMLstringToPDF.pdf", FileFormat.PDF);
}
public static String readTextFromFile(String fileName) throws IOException{
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new FileReader(fileName));
String content = null;
while ((content = br.readLine()) != null) {
sb.append(content);
}
return sb.toString();
}
}
将 HTML 文件转换为 PDF

Java 将 HTML 转换为 PDF

import com.spire.doc.*;
import com.spire.doc.documents.XHTMLValidationType;

public class htmlFileToWord {

public static void main(String[] args) throws Exception {
// Load the sample HTML file
Document document = new Document();
document.loadFromFile("InputHtmlFile.html", FileFormat.Html, XHTMLValidationType.None);

//Save to file
document.saveToFile("Result.pdf",FileFormat.PDF);
}
}

以上便是如何在Java中将 Word 转换为 PDF,如果您有其他问题也可以继续浏览本系列文章,获取相关教程~

猜你喜欢

转载自blog.csdn.net/m0_67129275/article/details/132805049