Java+Spring Boot使用iText生成PDF时泰卢固语不显示求助
解决iText生成PDF时泰卢固语显示空白的问题
泰卢固语显示空白的核心原因是你当前使用的字体不包含泰卢固语字符集,iText无法渲染未被字体覆盖的Unicode字符。以下是具体解决步骤:
关键修正点
- 必须使用支持泰卢固语的字体文件(比如Google的Noto Sans Telugu,或者系统自带的泰卢固字体)
- 字体编码必须指定为
BaseFont.IDENTITY_H,这是支持复杂脚本(如泰卢固语)的必要编码 - 避免重复操作响应输出流的错误
修改后的代码示例
public class PdfTelugu { public void export(HttpServletRequest request, HttpServletResponse response, School school) throws DocumentException, ParseException, IOException { // 设置响应头,确保浏览器正确识别PDF response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "inline; filename=school_details.pdf"); Document doc = new Document(); PdfWriter writer = PdfWriter.getInstance(doc, response.getOutputStream()); doc.open(); PdfPTable table = new PdfPTable(3); table.setWidthPercentage(100.0f); table.setWidths(new float[] {1.5f, 11.6f, 10.0f }); // 加载支持泰卢固语的字体,这里以Noto Sans Telugu为例 // 注意:需要把字体文件放在项目资源目录下,比如src/main/resources/fonts/NotoSansTelugu-Regular.ttf String fontPath = "/fonts/NotoSansTelugu-Regular.ttf"; BaseFont baseFont = BaseFont.createFont( getClass().getResource(fontPath).getPath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED ); Font teluguFont = new Font(baseFont, 11, Font.NORMAL); // 添加表格内容 PdfPCell c1 = new PdfPCell(new Phrase("1", teluguFont)); c1.setVerticalAlignment(Element.ALIGN_CENTER); c1.setPaddingBottom(12f); table.addCell(c1); c1 = new PdfPCell(new Phrase("పాఠశాల పేరు", teluguFont)); c1.setVerticalAlignment(Element.ALIGN_CENTER); c1.setPaddingBottom(12f); table.addCell(c1); c1 = new PdfPCell(new Phrase("School Name", teluguFont)); c1.setVerticalAlignment(Element.ALIGN_CENTER); c1.setPaddingBottom(12f); table.addCell(c1); doc.add(table); doc.close(); // 这里不需要重新获取输出流,doc.close()已经会刷新并关闭流 } }
额外注意事项
- 确保字体文件路径正确,若使用系统字体,可直接传入字体名称(比如Windows下的"Vani",Linux下的"Noto Sans Telugu"),但嵌入字体更稳妥,避免不同环境字体缺失
Character.UnicodeScript.TELUGU只是用于检测字符所属脚本,不能直接解决字体渲染问题,核心还是要加载对应字体- 不要重复获取响应输出流,
PdfWriter已经绑定了response.getOutputStream(),doc.close()会自动处理流的刷新和关闭,重复操作会导致异常
内容的提问来源于stack exchange,提问作者lakshman Kommula
相关产品推荐
相关产品推荐

