gpt4 book ai didi

java - iText 样式将 HTML 解析为 PDF

转载 作者:搜寻专家 更新时间:2023-11-01 02:12:56 25 4
gpt4 key购买 nike

我对 iText 有疑问。

我点击了这个链接:How to export html page to pdf format?

我的片段:

    String str = "<html><head><body><div style=\"width:100%;height:100%;\"><h3 style=\"margin-left:5px;margin-top:40px\">First</h3><div style=\"margin-left:15px;margin-top:15px\"><title></title><p>sdasdasd shshshshdffgdfgd</p></div><h3 style=\"margin-left:5px;margin-top:40px\">The dream</h3><div style=\"margin-left:15px;margin-top:15px\"></div></div></body></head></html>";
String fileNameWithPath = "/Users/cecco/Desktop/pdf2.pdf";


com.itextpdf.text.Document document =
new com.itextpdf.text.Document(com.itextpdf.text.PageSize.A4);
FileOutputStream fos = new FileOutputStream(fileNameWithPath);
com.itextpdf.text.pdf.PdfWriter pdfWriter =
com.itextpdf.text.pdf.PdfWriter.getInstance(document, fos);

document.open();

document.addAuthor("Myself");
document.addSubject("My Subject");
document.addCreationDate();
document.addTitle("My Title");

com.itextpdf.text.html.simpleparser.HTMLWorker htmlWorker =
new com.itextpdf.text.html.simpleparser.HTMLWorker(document);
htmlWorker.parse(new StringReader(str.toString()));

document.close();
fos.close();

并且工作正常。

但不考虑 h3 和 div 中的标签样式。

enter image description here

但是如果我将我的 html 复制到 http://htmledit.squarefree.com/一切正确。

我该如何解决这个问题?

最佳答案

iText 不是最好的 Html 解析器,但您可以使用 Flying-Saucer为了这。 Flying-Saucer 建立在 iText 之上,但具有功能强大的 Xml/(X)Html 解析器。简而言之:如果你想要 html -> Pdf,Flying Saucer 是完美的选择。

以下是从字符串生成 pdf 的方法:

/*
* Note: i filled something in the title-tag and fixed the head tag (the whole body-tag was in the head)
*/
String str = "<html><head></head><body><div style=\"width:100%;height:100%;\"><h3 style=\"margin-left:5px;margin-top:40px\">First</h3><div style=\"margin-left:15px;margin-top:15px\"><title>t</title><p>sdasdasd shshshshdffgdfgd</p></div><h3 style=\"margin-left:5px;margin-top:40px\">The dream</h3><div style=\"margin-left:15px;margin-top:15px\"></div></div></body></html>";

OutputStream os = new FileOutputStream(new File("example.pdf"));

ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(str);
renderer.layout();
renderer.createPDF(os);

os.close();

但是: FS 只支持有效 Html/Xhtml/xml,所以确保它是。

关于java - iText 样式将 HTML 解析为 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13816429/

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