web导出pdf

pom配置

<!--java生成pdf需要的jar包-->
        <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.6</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf.tool</groupId>
            <artifactId>xmlworker</artifactId>
            <version>5.5.6</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.itextpdf/itext-asian -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

java代码

public class PDFUtilController {

    private static final Logger logger = LogManager.getLogger(PDFUtilController.class);

    /** * 导出PDF文件 * * @param content * @param response */
    @RequestMapping("/exportPdf")
    @ResponseBody
    public void exportPdf(String content,HttpServletResponse response) {
        OutputStream os = null;
        try {
            content = "<h1>啊啊啊啊</h1><br/>默认的iText字体设置不支持中文字体,需要下载远东字体包iTextAsian.jar," +
                    "否则不能往PDF文档中输出中文字体。\n iText的安装非常方便,在http://www.lowagie.com/iText/download.html " +
                    "- download 网站上下载iText.jar文件后,只需要在系统的CLASSPATH中加入iText.jar的路径," +
                    "在程序中就可以使用iText类库了。\n 本地化测试包括繁体\n本地化測試包括繁體";
            Document document = new Document();
            ByteArrayOutputStream baos
                    = new ByteArrayOutputStream();
            PdfWriter.getInstance(document, baos);

            //处理中文乱码不显示问题
            BaseFont baseFontChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font fontChinese =  new  Font(baseFontChinese , 12 , Font.NORMAL);
            document.open();

            document.add(new Chunk(content,fontChinese));//添加文本块
            document.add(new Phrase(content,fontChinese));//添加短语
            document.add(new Paragraph(content,fontChinese));//添加段落
            document.close();

            response.reset(); //清空输出流
            response.setHeader("Content-disposition", "attachment; filename=schedule.pdf"); // 设定输出文件头
            response.setContentType("application/octet-stream"); // 定义输出类型
            response.setContentLength(baos.size());
            os = response.getOutputStream();
            baos.writeTo(os);
            os.flush();
        }catch(Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(os != null){//关闭流。防止资源未关闭,导致内存泄漏
                    os.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        }
}
相关文章
相关标签/搜索