按照格式导出Pdf

该代码示例展示了如何在Java中利用Freemarker模板引擎处理数据,并结合iText7库将处理后的HTML转换为PDF,同时处理了中文支持和字体设置。PdfUtil工具类提供了创建PDF的静态方法,包括根据模板文件导出到指定文件和导出到输出流。
摘要由CSDN通过智能技术生成

依赖

<!-- 生成html模板 -->
<dependency>
	<groupId>org.freemarker</groupId>
	<artifactId>freemarker</artifactId>
	<version>2.3.30</version>
</dependency>
<!--itext7 html转pdf用到的包-->
<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>html2pdf</artifactId>
	<version>3.0.1</version>
</dependency>
<!--itext7 中文支持-->
<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>font-asian</artifactId>
	<version>7.1.12</version>
</dependency>

工具类

public class PdfUtil {

    private final static String TEMPLATE_BASE_PATH = File.separator + "template" + File.separator; //模板文件默认存放位置
    public final static String OUTPUT_BASE_PATH = File.separator + "pdfOut" + File.separator; // pdf导出默认位置
    private final static String ENCODING = "UTF-8"; //指定编码
    private final static String FONT_BASE_PATH = "font" + File.separator; //存放字体资源文件的地址
    private final static String DEFAULT_FONT = "simsun.ttc"; // 默认字体资源文件([宋体][simsun.ttc])
    private final static String DEFAULT_HEITI = "STHeitibd.ttf";
    public final static String PDF_CONTENT_TYPE = "application/pdf";

    /**
     * 根据模板文件导出pdf到指定文件夹(支持html渲染)
     * @param templateFile 模板文件名称
     * @param args 参数
     * @param pdfFile 导出pdf文件全路径名+文件名
     */
    public static void createdPDF(String templateFile, Map<String, String> args, String pdfFile) {
        FileOutputStream output = null;
        try {
            // 读取模板文件,填充模板参数
            Configuration freemarkerCfg = new Configuration(Configuration.VERSION_2_3_23);
            freemarkerCfg.setTemplateLoader(new ClassTemplateLoader(PdfUtil.class, TEMPLATE_BASE_PATH));
            Template template = freemarkerCfg.getTemplate(templateFile);
            StringWriter out = new StringWriter();
            if (args != null && args.size() > 0)
                template.process(args, out);
            String html = out.toString();

            // 设置字体以及字符编码
            ConverterProperties props = new ConverterProperties();
            FontProvider fontProvider = new FontProvider();
            PdfFont sysFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
            fontProvider.addFont(sysFont.getFontProgram(), "UniGB-UCS2-H");
            fontProvider.addStandardPdfFonts();
            fontProvider.addFont(FONT_BASE_PATH + DEFAULT_FONT);
            fontProvider.addFont(FONT_BASE_PATH + DEFAULT_HEITI);
            props.setFontProvider(fontProvider);
            props.setCharset(ENCODING);

            // 转换为PDF文档
            if(pdfFile.lastIndexOf(File.separator) > 0) {
                File path = new File(pdfFile.substring(0, pdfFile.lastIndexOf(File.separator)));
                if (!path.exists())
                    path.mkdirs();
            }
            output = new FileOutputStream(pdfFile);
            PdfDocument pdf = new PdfDocument(new PdfWriter(output));
            pdf.setDefaultPageSize(PageSize.A4);
            Document document = HtmlConverter.convertToDocument(html, pdf, props);
            document.getRenderer().close();
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(output != null)
                    output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据模板文件导出pdf
     * @param templateFile 模板文件名称
     * @param args 参数
     * @param output 输出流
     */
    public static void exportPDF(String templateFile, Map<String, String> args, OutputStream output) {
        try {
            // 读取模板文件,填充模板参数
            Configuration freemarkerCfg = new Configuration(Configuration.VERSION_2_3_23);
            freemarkerCfg.setTemplateLoader(new ClassTemplateLoader(PdfUtil.class, TEMPLATE_BASE_PATH));
            Template template = freemarkerCfg.getTemplate(templateFile);
            StringWriter out = new StringWriter();
            if (args != null && args.size() > 0)
                template.process(args, out);
            String html = out.toString();

            // 设置字体以及字符编码
            ConverterProperties props = new ConverterProperties();
            FontProvider fontProvider = new FontProvider();
            PdfFont sysFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
            fontProvider.addFont(sysFont.getFontProgram(), "UniGB-UCS2-H");
            fontProvider.addStandardPdfFonts();
            fontProvider.addFont(FONT_BASE_PATH + DEFAULT_FONT);
            fontProvider.addFont(FONT_BASE_PATH + DEFAULT_HEITI);
            props.setFontProvider(fontProvider);
            props.setCharset(ENCODING);

            // 转换为PDF文档
            PdfDocument pdf = new PdfDocument(new PdfWriter(output));
            pdf.setDefaultPageSize(PageSize.A4);
            Document document = HtmlConverter.convertToDocument(html, pdf, props);
            document.getRenderer().close();
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(output != null)
                    output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        String path = "C:/package" + File.separator + new Date().getTime() + ".pdf";
        String templateName = "dutydocumenttemplate.html";
        Map<String,String> dataMap = new HashMap<>();
        dataMap.put("title","测试Pdf导出标题");
        dataMap.put("organization","测试部门");
        dataMap.put("content","<p>fasgrr</p>");
        dataMap.put("date","2023/07/11");
        dataMap.put("imgUrl", "C:/package/biaozhunban_dev/release/upload/upload/touxiang/addUser/20230707/1688714152120.jpg");
        System.out.println("开始导出");
        createdPDF(templateName,dataMap,path);
        System.out.println("导出结束");
    }
}

模板文件

<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<style>

		</style>
	</head>

	<body lang="ZH-CN" style='word-wrap:break-word;text-justify-trim:punctuation'>

		<div class="WordSection1" style='layout-grid:15.6pt'>

			<p class="MsoNormal" align="center" style='text-align:center'>
				<b>
					<span style='font-size:22.0pt'>${title}</span>
				</b>
			</p>

			<p class="MsoNormal" align="center" style='text-align:center'>${organization}
			</p>

			<p class="MsoNormal" align="left" style='text-align:left'>
				<span style='font-size:12.0pt'>${content}</span>
			</p>

			<p class="MsoNormal" align="left" style='text-align:left'>
				<span lang="EN-US" style='font-size:12.0pt'>&#160;</span>
			</p>

			<p class="MsoNormal" align="right" style='text-align:right'>
				<span style='font-size:14.0pt'>签名:
					<u>&#160;&#160;&#160;&#160;<img src=${imgUrl} width="120" height="50">&#160;&#160;&#160;&#160;</u>
				</span>
			</p>

			<p class="MsoNormal" align="right" style='text-align:right'>
				<span style='font-size:14.0pt'>日期:
					<u>
						<span lang="EN-US">&#160;&#160;&#160;&#160;${date}&#160;&#160;&#160;&#160;</span>
					</u>
				</span>
			</p>

		</div>

	</body>

</html>

字体下载地址:百度网盘 请输入提取码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值