SVG转PDF后编码、字体异常及元素重叠问题排查求助
iText v8.0.1 SVG转PDF问题排查方案
一、字体未生效问题
- iText不会自动加载系统字体,SVG里指定的Tahoma、Verdana必须手动注册到字体工厂:
- 找到本地字体文件路径(Windows下一般是
C:\Windows\Fonts\tahoma.ttf、C:\Windows\Fonts\verdana.ttf),用PdfFontFactory.register()完成注册,同时指定字体别名对应SVG里的font-family值。 - 配置
SvgConverterProperties时添加自定义FontProvider,把注册的字体包含进去,还要指定UTF-8字符集避免编码问题。
- 找到本地字体文件路径(Windows下一般是
- 检查SVG的font-family写法:确保拼写正确、大小写一致,比如不要写成小写
tahoma而SVG里是Tahoma。 - PDF属性显示Ansi是因为默认编码,注册字体时指定
PdfEncodings.IDENTITY_H编码,能更好支持UTF-8字符。
示例代码:
// 注册本地字体 PdfFontFactory.register("C:/Windows/Fonts/tahoma.ttf", "Tahoma"); PdfFontFactory.register("C:/Windows/Fonts/verdana.ttf", "Verdana"); // 配置字体提供者 FontProvider fontProvider = new DefaultFontProvider(false, false, false); fontProvider.addRegisteredFonts(); // 设置SVG转换属性 SvgConverterProperties properties = new SvgConverterProperties(); properties.setFontProvider(fontProvider); properties.setCharset(StandardCharsets.UTF_8); // 执行转换 PdfDocument pdfDoc = new PdfDocument(new PdfWriter("output.pdf")); Document doc = new Document(pdfDoc); Image svgImg = SvgConverter.convertToImage(new FileInputStream("input.svg"), properties); doc.add(svgImg); doc.close();
二、元素重叠问题
- 先验证SVG本身:在浏览器里打开SVG文件,确认渲染正常,要是SVG本身布局就有重叠,转PDF后问题会延续。
- 匹配页面尺寸与SVG viewBox:获取SVG的viewBox属性,动态设置PDF页面的宽高,避免强制缩放导致元素错位。
- 检查px转pt的逻辑:1px等于0.75pt,确保你的FontConverter类转换公式正确,且覆盖了所有文本元素的字体单位转换。
- 禁用自动缩放:在
SvgConverterProperties里设置setScaleToPage(false),强制按SVG原始尺寸渲染。
示例页面配置代码:
// 解析SVG获取viewBox InputStream svgStream = new FileInputStream("input.svg"); SvgParser svgParser = new SvgParser(svgStream); SvgDocument svgDoc = svgParser.parse(); Rectangle viewBox = svgDoc.getViewBox(); // 设置PDF页面匹配viewBox尺寸 PdfDocument pdfDoc = new PdfDocument(new PdfWriter("output.pdf")); pdfDoc.setDefaultPageSize(new PageSize(viewBox.getWidth(), viewBox.getHeight())); Document doc = new Document(pdfDoc); // 禁用自动缩放 SvgConverterProperties properties = new SvgConverterProperties(); properties.setScaleToPage(false); Image svgImg = SvgConverter.convertToImage(svgStream, properties); doc.add(svgImg); doc.close();
内容的提问来源于stack exchange,提问作者Tommy
相关产品推荐
相关产品推荐

