You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apache Velocity模板生成PDF时土耳其语字符缺失问题求助

Apache Velocity模板生成PDF时土耳其语字符缺失问题求助

嘿各位,我最近在做一个用Velocity模板生成PDF的功能,碰到个棘手的编码问题,想请大家帮忙看看!

情况是这样的:我需要把Velocity模板渲染后转成PDF,但生成的PDF里土耳其语的一些特殊字符(比如İ、ş、ı)直接不见了,举个例子:

原本应该显示的文本:
This text must've been İmza Sahibi:
$sincomModelData.imza_sahibi
bu belgeyle aşağıda belirtilen
aracın

但PDF里那些特殊字符都没了,只剩其他内容。我已经在加载模板的时候指定了UTF-8编码:

Template t = ve.getTemplate("templates/helloworld.vm", "UTF-8");

但奇怪的是,像ö、ü这类字符能正常显示,偏偏İ、ş、ı这些就不行,有没有大佬知道怎么调整才能让所有土耳其语字符都正确编码并显示在PDF里呀?

下面是我完整的转换代码,从Velocity模板渲染到HTML转XHTML再转PDF的流程:

VelocityEngine ve = new VelocityEngine();
System.out.println(sincomModel);

/* next, get the Template */
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class",
ClasspathResourceLoader.class.getName());
ve.init();

System.out.println(vehicleDto);

Template t = ve.getTemplate("templates/helloworld.vm", "UTF-8");

VelocityContext context = new VelocityContext();
context.put("sincomModelData", sincomModel);
context.put("tanitim_numFirst", tanitim_numFirst);
context.put("tanitim_numSec", tanitim_numSec);
context.put("vehicleDate",vehicleDto.getDate());
context.put("vehicleRenk",vehicleDto.getRenk());
context.put("yakitIc",yakitIc);
context.put("yakitDis",yakitDis);

StringWriter writer = new StringWriter();
t.merge(context, writer);

ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos = xhtmlToPdf(writer.toString());

HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_PDF);
header.set(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=" + fileName.replace(" ", "_"));
header.setContentLength(baos.toByteArray().length);

return new HttpEntity<byte[]>(baos.toByteArray(), header);
}

private static String htmlToXhtml(String html) {
Document document = Jsoup.parse(html);
document.outputSettings().syntax(Document.OutputSettings.Syntax.xml);
return document.html();
}

private ByteArrayOutputStream xhtmlToPdf(String xhtml) throws IOException {
String xhtml_son = htmlToXhtml(xhtml);
ITextRenderer iTextRenderer = new ITextRenderer();
iTextRenderer.setDocumentFromString(xhtml_son);
iTextRenderer.layout();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
iTextRenderer.createPDF(baos);
return baos;
}

感谢大家的帮忙!

备注:内容来源于stack exchange,提问作者Altan Mehmet Türkmen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 13:12:46