iText 中文无法显示
/** * 导出PDF工具com.lowagie.itext测试 * * @param response * @throws IOException * @throws DocumentException */ @RequestMapping(value = "/emp/download/pdf", method = RequestMethod.GET) public void downloadPdf(HttpServletResponse response) throws IOException, DocumentException { // 设置编码 response.setCharacterEncoding("utf-8"); //设置响头部 response.setHeader("Content-Type","application/pdf"); //设置文件下载的默认名称 StringBuilder filename = new StringBuilder("attachment;filename="); filename.append("employee["+new SimpleDateFormat("yyyyMMdd").format(new Date())+"].pdf"); response.setHeader("Content-Disposition", String.valueOf(filename)); //相关中文字体显示配置 //第一种:使用iTextAsian.jar包中的字体 BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); Font font = new Font(baseFont); //第二种:使用Windows系统字体 BaseFont baseFont_zh = BaseFont.createFont("C:\\Windows\\Fonts\\STFANGSO.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); Font font_zh = new Font(baseFont_zh); //第三种:使用资源字体,也就是自己下载的字体 BaseFont baseFont_resources = BaseFont.createFont("\\SIMYOU.TIF",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED); Font font_resources = new Font(baseFont_resources); Document document = new Document(); PdfWriter.getInstance(document, response.getOutputStream()); document.open(); List<Emp> all = empService.findAll(); for (Emp emp : all) { PdfPTable pdfPTable = new PdfPTable(5); PdfPCell pdfPCell = new PdfPCell(); //注意这里 new Paragraph()
//第一个参数是内容,第二个参数是字体,这里font_zh对应的是Windows下的字体库的某种字体
//下同
pdfPCell.setPhrase(new Paragraph(String.valueOf(emp.getEmpId()),font_zh)); pdfPTable.addCell(pdfPCell); document.add(pdfPTable); pdfPCell = new PdfPCell(); pdfPCell.setPhrase(new Paragraph(emp.getEmpName(),font_zh)); pdfPTable.addCell(pdfPCell); document.add(pdfPTable); pdfPCell = new PdfPCell(); pdfPCell.setPhrase(new Paragraph(emp.getEmpGender(),font_zh)); pdfPTable.addCell(pdfPCell); document.add(pdfPTable); pdfPCell = new PdfPCell(); pdfPCell.setPhrase(new Paragraph(emp.getEmail(),font_zh)); pdfPTable.addCell(pdfPCell); document.add(pdfPTable); pdfPCell = new PdfPCell(); pdfPCell.setPhrase(new Paragraph(emp.getDepartment(),font_zh)); pdfPTable.addCell(pdfPCell); document.add(pdfPTable); } document.close(); ServletOutputStream outputStream = response.getOutputStream(); outputStream.flush(); outputStream.close(); }
LiveGreen(LC)
本文来自博客园,作者:可可西里(lemon),转载请注明原文链接:https://www.cnblogs.com/ldl326308/p/10961616.html
分类:
Java
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现