Ste*_*ers 4 java html-parsing pdf-parsing jsoup
我正在使用Jsoup.parse解析一段html.
其他一切都很棒,但我应该稍后在pdf转换器中解析这个HTML.
由于某种原因,Jsoup.parse删除了结束标记,而pdf-parser抛出了关于缺少关闭img标记的异常.
Can't load the XML resource (using TRaX transformer). org.xml.sax.SAXParseException;
lineNumber: 115; columnNumber: 4; The element
type "img" must be terminated by the matching end-tag "</img>"
Run Code Online (Sandbox Code Playgroud)
如何防止Jsoup.parse删除关闭的img标记?
例如这一行:
<img src="C:\path\to\image\image.png"></img>
Run Code Online (Sandbox Code Playgroud)
转向:
<img src="C:\path\to\image\image.png">
Run Code Online (Sandbox Code Playgroud)
同样的情况:
<img src="C:\path\to\image\image.png"/>
Run Code Online (Sandbox Code Playgroud)
这是代码:
private void createPdf(File file, String content) throws IOException, DocumentException {
OutputStream os = new FileOutputStream(file);
content = tidyUpHTML(content);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(content);
renderer.layout();
renderer.createPDF(os);
os.close();
}
Run Code Online (Sandbox Code Playgroud)
这是上面方法中调用的tidyUpHTML方法:
private String tidyUpHTML(String html) {
org.jsoup.nodes.Document doc = Jsoup.parse(html);
doc.select("a").unwrap();
String fixedTags = doc.toString().replace("<br>", "<br />");
fixedTags = fixedTags.replace("<hr>", "<hr />");
fixedTags = fixedTags.replaceAll(" "," ");
return fixedTags;
}
Run Code Online (Sandbox Code Playgroud)
您的PDF转换器需要xhtml(因为它需要关闭img标记).设置Jsoup以输出到xhtml(xml).
org.jsoup.nodes.Document doc = Jsoup.parse(html);
document.outputSettings().syntax( Document.OutputSettings.Syntax.xml);
doc.select("a").unwrap();
String fixedTags = doc.html();
Run Code Online (Sandbox Code Playgroud)
请参阅使用Jsoup 1.8.1将HTML转换为XHTML是否可行?