如何修复PDF转换时出现的XML无效字符(Unicode:0x13)错误
解决PDF转换时XML非法字符问题
问题现象
转换含特殊字符的HTML到PDF时出现以下错误:
>>> Creation of PDF {} is invalid! Can't load the XML resource (using TRaX transformer). org.xml.sax.SAXParseException; lineNumber: 20; columnNumber: 4615; An invalid XML character (Unicode: 0x13) was found in the element content of the document. org.xml.sax.SAXParseException; lineNumber: 20; columnNumber: 4615; An invalid XML character (Unicode: 0x13) was found in the element content of the document. An invalid XML character (Unicode: 0x13) was found in the element content of the document.
相关代码
public ByteArrayInputStream createPdf(String textToConvert) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); PDDocument document = new PDDocument(); try { PdfRendererBuilder builder = new PdfRendererBuilder(); builder.defaultTextDirection(BaseRendererBuilder.TextDirection.LTR); builder.withHtmlContent(textToConvert, ""); PDFont font = PDType0Font.load(document, this.getClass().getClassLoader().getResourceAsStream("fonts/" + FontNameEnum.TT_NORMS_PRO_REGULAR.getName())); font.encode("UTF-8"); PDFontSupplier fontSupplier = new PDFontSupplier(font); builder.useFont(fontSupplier, "TTNormsPro-Regular"); builder.usePDDocument(document); PdfBoxRenderer renderer = builder.buildPdfRenderer(); renderer.createPDFWithoutClosing(); document.save(out); } catch (Exception e) { e.printStackTrace(); } finally { document.close(); } return new ByteArrayInputStream(out.toByteArray()); }
解决方案
使用\P{Print}会误删Ÿ、Ã、È这类合法UTF-8字符,正确做法是仅移除XML规范明确禁止的非法字符,保留所有合法字符。
步骤1:添加文本清理方法
实现方法过滤XML 1.0不允许的字符:
private String cleanXmlInvalidChars(String input) { // XML 1.0允许的字符范围:#x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] return input.replaceAll("[^\\x09\\x0A\\x0D\\x20-\\xD7FF\\xE000-\\xFFFD\\x10000-\\x10FFFF]", ""); }
步骤2:在PDF转换前清理文本
修改createPdf方法,传入HTML内容前先执行清理:
// 在builder.withHtmlContent前添加清理逻辑 String cleanedHtml = cleanXmlInvalidChars(textToConvert); builder.withHtmlContent(cleanedHtml, "");
这样既能移除0x13这类XML非法字符,又能保留所有合法UTF-8字符,避免误删问题。
内容的提问来源于stack exchange,提问作者vikifor
相关产品推荐
相关产品推荐

