itext html转PDF一些尝试

这里写自定义目录标题


    /**
     * 生成静态文件
     * @param freeTempName 模板名称
     * @param context 数据内容
     * @param outFilePath 输出路径
     * @return true:创建成功,false:创建失败
     */
    @Override
    @Transactional(readOnly = true)
    public boolean processAndCreateHtml(String freeTempName, Context context, String outFilePath) {

        FileWriter fileWriter = null;
        try {
            File file = new File(outFilePath);
            File parent = file.getParentFile();
            // 如果pdf保存路径不存在,则创建路径
            if (!parent.exists()) {
                parent.mkdirs();
            }
            fileWriter = new FileWriter(outFilePath);
            templateEngine.process(freeTempName, context,fileWriter);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return false;
        } finally {
            try {
                if (fileWriter != null){
                    fileWriter.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(),e);
                return false;
            }
        }
        return true;
    }

    /**
     * 获取模版的创建路径
     * @return 年/月/日
     */
    @Override
    @Transactional(readOnly = true)
    public String buildHtmlOutFilePath(){
        Date date = new Date();
        return PathEnum.TEMPLATE_HTML.getPath()
                + DateUtil.year(date)
                + "/"
                + DateUtil.month(date)
                + "/"
                + DateUtil.dayOfMonth(date)
                + "/"
                + UUID.randomUUID().toString()
                + ".html";
    }

    /**
     * 获取pdf的创建路径
     * @return 年/月/日/年/月/日/uuid.pdf
     */
    @Override
    @Transactional(readOnly = true)
    public String buildPdfOutFilePath(){
        Date date = new Date();
        return PathEnum.TEMPLATE_PDF.getPath()
                + DateUtil.year(date)
                + "/"
                + DateUtil.month(date)
                + "/"
                + DateUtil.dayOfMonth(date)
                + "/"
                + UUID.randomUUID().toString()
                + ".pdf";
    }

    @Override
    @Transactional(readOnly = true)
    public String htmlToPdf(String freeTempName, Context context) {
        String htmlOutFilePath = buildHtmlOutFilePath();
        boolean createHtml = processAndCreateHtml(freeTempName, context, htmlOutFilePath);
        if (!createHtml){
            throw new BaseException(PayrollExceptionCode.DATA_NOT_FOUND);
        }

        String pdfOutFilePath = buildPdfOutFilePath();
//        boolean convert = WKHtmlToPdfUtil.convert(htmlOutFilePath, pdfOutFilePath, " ");
        try {
            Html2pdf.html2pdf(htmlOutFilePath,pdfOutFilePath);
        } catch (Exception e) {
            e.printStackTrace();
        }


        return pdfOutFilePath;
    }
}


    /**
     * 生成静态文件
     * @param freeTempName 模板名称
     * @param context 数据内容
     * @param outFilePath 输出路径
     * @return true:创建成功,false:创建失败
     */
    @Override
    @Transactional(readOnly = true)
    public boolean processAndCreateHtml(String freeTempName, Context context, String outFilePath) {

        FileWriter fileWriter = null;
        try {
            File file = new File(outFilePath);
            File parent = file.getParentFile();
            // 如果pdf保存路径不存在,则创建路径
            if (!parent.exists()) {
                parent.mkdirs();
            }
            fileWriter = new FileWriter(outFilePath);
            templateEngine.process(freeTempName, context,fileWriter);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return false;
        } finally {
            try {
                if (fileWriter != null){
                    fileWriter.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(),e);
                return false;
            }
        }
        return true;
    }
package io.ersoft.payroll.pdf.uitls;
 
 
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;

import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
 
import com.lowagie.text.pdf.BaseFont;
 
/**
 * 转换html为pdf
 * @author Uncle Liu
 *
 */
public class Html2pdf {
 
    /**
     * 将HTML转成PD格式的文件。html文件的格式比较严格
     * @param htmlFile
     * @param pdfFile
     * @throws Exception
     */
    // <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
    public static void html2pdf(String htmlFile, String pdfFile) throws Exception {
        File file = new File(pdfFile);
        File parent = file.getParentFile();
        // 如果pdf保存路径不存在,则创建路径
        if (!parent.exists()) {
            parent.mkdirs();
        }
        // step 1
        String url = new File(htmlFile).toURI().toURL().toString();
        System.out.println(url);
        // step 2
        OutputStream os = new FileOutputStream(pdfFile);
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocument(url);
 
        // step 3 解决中文支持
        ITextFontResolver fontResolver = renderer.getFontResolver();
//            fontResolver.addFont("/usr/share/fonts/chiness/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        fontResolver.addFont("/Users/user/Desktop/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        renderer.layout();
        renderer.createPDF(os);
        os.close();
 
    }
 
    public static String getCurrentOperatingSystem(){
        String os = System.getProperty("os.name").toLowerCase();
        System.out.println("---------当前操作系统是-----------" + os);
        return os;
    }
 
 
    public static void main(String[] args) {
 
        String htmlFile = "D:\\WorkSpace\\IdeaProjects\\pdf\\src\\main\\resources\\templates\\u.html";
        String pdfFile = "c:/test.pdf";
        try {
            Html2pdf.html2pdf(htmlFile, pdfFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
 
 
 
}
  Context context = new Context();
                context.setVariable("payslipInfos", payslipEmployeeInfoBos);
//                String filePath = thymeleafService.html2Pdf("payslipPdfTemplate", context);
                String filePath = thymeleafService.htmlToPdf("newPayslipPdfTemplate", context);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值