动态表单数据生成pdf文件上传到服务器,包括图片

1.导入jar包:

compile group: 'com.itextpdf', name: 'itext-asian', version: '5.2.0'
compile group: 'com.itextpdf', name: 'itextpdf', version: '5.5.13.2'
compile group: 'org.xhtmlrenderer', name: 'flying-saucer-pdf', version: '9.1.20'
compile group: 'com.itextpdf.tool', name: 'xmlworker', version: '5.5.13.2'

2.生成pdf文件代码:

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String date = sdf.format(new Date());
try {
    ITextRenderer renderer = new ITextRenderer();
    renderer.getSharedContext().getTextRenderer().setSmoothingThreshold(0);
    //将打印的所有信息封装为pdfHtmlDTO文件
    PDFHtmlDTO pdfHtmlDTO = getPDFHtml(id);
    //将pdfHtmlDTO生成html格式的字符串
    String html = getHtmlString(pdfHtmlDTO);
    /**
     *  html格式的字符串生成pdf文件
     */
    renderer.setDocumentFromString(html);
    //解决中文支持
    ITextFontResolver fontResolver = renderer.getFontResolver();
    //在项目中上传simsun.ttc字体文件
    String path1 = ResourceUtils.getFile("classpath:") + File.separator + "simsun.ttc";
    if ("linux".equals(getCurrentOperatingSystem())) {
        fontResolver.addFont(path1, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    } else {
        fontResolver.addFont("C:\\WINDOWS\\Fonts\\simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        fontResolver.addFont("C:\\WINDOWS\\Fonts\\arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
    }
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    renderer.layout();
    renderer.createPDF(os);
    renderer.finishPDF();
    os.flush();
    os.close();
    InputStream inputStream = new ByteArrayInputStream(os.toByteArray());
    String realPath = objectStorageService.putTempObject(tenantId + "-" + id + "-" + date, inputStream, fileExe, "flow-export-pdf");

    return realPath;
} catch (Exception e) {

    e.printStackTrace();
}

//获取当前操作系统:

public String getCurrentOperatingSystem() {
    String os = System.getProperty("os.name").toLowerCase();
    log.info("=========当前操作系统================"+os);
    return os;
}

//html文件生成pdf文件需要注意的几点:

1.html格式的字符串中必须开头必须是是:

”<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">“

动态表单数据生成pdf文件上传到服务器,包括图片

2.body中必须要标注字体,否则中文字体就无法显示:

动态表单数据生成pdf文件上传到服务器,包括图片

3.如果图片是从网络中获取的。则需要将图片转化为base64的字体:

public static String getImageBase64(String imagePath) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        URL url1 = new URL(imagePath);
        URLConnection uc = url1.openConnection();
        InputStream inputStream = uc.getInputStream();
        int j = 0;
        while ((j = inputStream.read()) != -1) {
            out.write(j);
        }
        inputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "data:image/jpg;base64," + Base64.getEncoder().encodeToString(out.toByteArray());

}

4.html格式的字符串中图片的src的值直接用base64表示:

<img style=\"width: 100px;height: 50px;margin-right: 20px;\" src='" + imageBase64 + "' />