gpt4 book ai didi

java - 如何使用 iText 将 HTML 转换为 PDF

转载 作者:IT老高 更新时间:2023-10-28 20:56:54 29 4
gpt4 key购买 nike

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class GeneratePDF {
public static void main(String[] args) {
try {

String k = "<html><body> This is my Project </body></html>";

OutputStream file = new FileOutputStream(new File("E:\\Test.pdf"));

Document document = new Document();
PdfWriter.getInstance(document, file);

document.open();

document.add(new Paragraph(k));

document.close();
file.close();

} catch (Exception e) {

e.printStackTrace();
}
}
}

这是我将 HTML 转换为 PDF 的代码。我可以转换它,但在 PDF 文件中它保存为整个 HTML,而我只需要显示文本。 <html><body> This is my Project </body></html>保存为 PDF,而它应该只保存 This is my Project .

最佳答案

您可以使用 HTMLWorker像这样的类(已弃用):

import com.itextpdf.text.html.simpleparser.HTMLWorker;
//...
try {
String k = "<html><body> This is my Project </body></html>";
OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
Document document = new Document();
PdfWriter.getInstance(document, file);
document.open();
HTMLWorker htmlWorker = new HTMLWorker(document);
htmlWorker.parse(new StringReader(k));
document.close();
file.close();
} catch (Exception e) {
e.printStackTrace();
}

或使用 XMLWorker , (从 this jar 下载)使用此代码:

import com.itextpdf.tool.xml.XMLWorkerHelper;
//...
try {
String k = "<html><body> This is my Project </body></html>";
OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, file);
document.open();
InputStream is = new ByteArrayInputStream(k.getBytes());
XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
document.close();
file.close();
} catch (Exception e) {
e.printStackTrace();
}

关于java - 如何使用 iText 将 HTML 转换为 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17825782/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com