[英]Preventing Jsoup.parse from removing the closing </img> tag
我正在使用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>"
如何防止Jsoup.parse刪除關閉的img標記?
例如這一行:
<img src="C:\path\to\image\image.png"></img>
轉向:
<img src="C:\path\to\image\image.png">
同樣的情況:
<img src="C:\path\to\image\image.png"/>
這是代碼:
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();
}
這是上面方法中調用的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;
}
您的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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.