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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM