/** * 导出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)