itextpdf导出PDF

/**
     * 上传word文档到OSS
     * //图片生成导出WORD参照 https://blog.csdn.net/xionglangs/article/details/115750066?spm=1001.2014.3001.5501
     * @param dataStatisticsTask
     * @param energyManagementStatisticsVo
     * @param fileName
     * @return
     */
    public Tuple2<String, String> exportWordPdf(DataStatisticsTask dataStatisticsTask, EnergyManagementStatisticsVo energyManagementStatisticsVo, String fileName) throws IOException, DocumentException {
        Map<String, Object> params = Maps.newHashMap();
        params.put(EnergyManagementStatisticsVo.DATA_DATE, DatetimeUtil.formatDate(new Date(), DatetimeUtil.TIME_FORMAT_Y_M_D));
        params.put(EnergyManagementStatisticsVo.PLATE_NO, dataStatisticsTask.getPlateNo());
        params.put(EnergyManagementStatisticsVo.BEGIN_DATE, DatetimeUtil.formatDate(dataStatisticsTask.getBeginDate(), DatetimeUtil.DATE_FORMAT_YMD_LONG));
        params.put(EnergyManagementStatisticsVo.END_DATA, DatetimeUtil.formatDate(dataStatisticsTask.getEndDate(), DatetimeUtil.DATE_FORMAT_YMD_LONG));
        params.put(EnergyManagementStatisticsVo.WHOLE_VEHICLE, energyManagementStatisticsVo.getWholeVehicleVo());
        int height = getHeight(energyManagementStatisticsVo.getWholeVehicleVo().getMotorPowerDistributionList());
        params.put(EnergyManagementStatisticsVo.WHOLE_MOTOR_POWER_HEIGHT, height);
        params.put(EnergyManagementStatisticsVo.WHOLE_MOTOR_POWER, generatePicture(energyManagementStatisticsVo.getWholeVehicleVo().getMotorPowerDistributionList(), EnergyManagementStatisticsVo.WHOLE_MOTOR_POWER_IMAGE, "功率/W", "次数/%", "占比", height));
        height = getHeight(energyManagementStatisticsVo.getWholeVehicleVo().getAccessoryPowerDistributionList());
        params.put(EnergyManagementStatisticsVo.WHOLE_ACCESSORY_POWER_HEIGHT, height);
        params.put(EnergyManagementStatisticsVo.WHOLE_ACCESSORY_POWER, generatePicture(energyManagementStatisticsVo.getWholeVehicleVo().getAccessoryPowerDistributionList(), EnergyManagementStatisticsVo.WHOLE_ACCESSORY_POWER_IMAGE, "功率/W", "次数/%", "占比", height));
        params.put(EnergyManagementStatisticsVo.FUEL_CELL_SYSTEM, energyManagementStatisticsVo.getFuelCellSystemVo());
        height = getHeight(energyManagementStatisticsVo.getFuelCellSystemVo().getOffTimeList());
        params.put(EnergyManagementStatisticsVo.FUEL_CELL_OFF_TILE_HEIGHT, height);
        params.put(EnergyManagementStatisticsVo.FUEL_CELL_OFF_TILE, generatePicture(energyManagementStatisticsVo.getFuelCellSystemVo().getOffTimeList(), EnergyManagementStatisticsVo.FUEL_CELL_OFF_TILE_IMAGE, "时间/min", "次数/%", "占比", height));
        height = getHeight(energyManagementStatisticsVo.getFuelCellSystemVo().getOperatingPointList());
        params.put(EnergyManagementStatisticsVo.FUEL_CELL_OPERATING_POINT_HEIGHT, height);
        params.put(EnergyManagementStatisticsVo.FUEL_CELL_OPERATING_POINT, generatePicture(energyManagementStatisticsVo.getFuelCellSystemVo().getOperatingPointList(), EnergyManagementStatisticsVo.FUEL_CELL_OPERATING_POINT_IMAGE, "电流/A", "次数/%", "占比", height));
        height = getHeight(energyManagementStatisticsVo.getFuelCellSystemVo().getGrossPowerDistributionList());
        params.put(EnergyManagementStatisticsVo.FUEL_CELL_AVERAGE_GROSS_POWER_HEIGHT, height);
        params.put(EnergyManagementStatisticsVo.FUEL_CELL_AVERAGE_GROSS_POWER, generatePicture(energyManagementStatisticsVo.getFuelCellSystemVo().getGrossPowerDistributionList(), EnergyManagementStatisticsVo.FUEL_CELL_AVERAGE_GROSS_POWER_IMAGE, "功率/W", "次数/%", "占比", height));
        params.put(EnergyManagementStatisticsVo.BATTERY, energyManagementStatisticsVo.getBatteryVo());
        height = getHeight(energyManagementStatisticsVo.getBatteryVo().getRunPointList());
        params.put(EnergyManagementStatisticsVo.BATTERY_RUN_POINT_HEIGHT, height);
        params.put(EnergyManagementStatisticsVo.BATTERY_RUN_POINT, generatePicture(energyManagementStatisticsVo.getBatteryVo().getRunPointList(), EnergyManagementStatisticsVo.BATTERY_RUN_POINT_IMAGE, "功率/W", "次数/%", "占比", height));
        height = getHeight(energyManagementStatisticsVo.getBatteryVo().getSocList());
        params.put(EnergyManagementStatisticsVo.BATTERY_SOC_HEIGHT, height);
        params.put(EnergyManagementStatisticsVo.BATTERY_SOC, generatePicture(energyManagementStatisticsVo.getBatteryVo().getSocList(), EnergyManagementStatisticsVo.BATTERY_SOC_IMAGE, "占比/%", "次数/%", "占比", height));
        params.put(EnergyManagementStatisticsVo.STACK_LIFE_PREDICTION, energyManagementStatisticsVo.getStackLifePredictionVo());
        params.put(EnergyManagementStatisticsVo.BATTERY_LIFE_PREDICTION, energyManagementStatisticsVo.getBatteryLifePredictionVo());
        params.put(EnergyManagementStatisticsVo.PARTS_LIFE_PREDICTION, energyManagementStatisticsVo.getPartsLifePredictionVo());
        String binPath = this.getClass().getResource("/").getPath() + "/bin";
        try {
            WordUtil.exportWord(binPath + "/ENERGY.docx", internalReportFilePath, fileName + ".docx", params);
        } catch (Exception e) {
            LOGGER.warn("Failed to generate file", e);
            return null;
        }
        String contentStr = PdfGenerator.getRendererContent("ENERGY.html", params, binPath);
        //开始生产pdf文件
        PdfGenerator.generatePlus(contentStr, new FileOutputStream(internalReportFilePath + File.separator + fileName + ".pdf"), params);
        String iReportDirName = "http://" + "rfdmas" + "." + "oss-cn-shenzhen.aliyuncs.com" + "/" + "rfdmas-master/fat-report-files/internal/";
        return new Tuple2<>(iReportDirName + fileName + ".docx", iReportDirName + fileName + ".pdf");
    }
package com.utils;

import cn.afterturn.easypoi.entity.ImageEntity;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.Pipeline;
import com.itextpdf.tool.xml.XMLWorker;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.tool.xml.html.CssAppliersImpl;
import com.itextpdf.tool.xml.html.Tags;
import com.itextpdf.tool.xml.net.FileRetrieve;
import com.itextpdf.tool.xml.net.ReadingProcessor;
import com.itextpdf.tool.xml.parser.XMLParser;
import com.itextpdf.tool.xml.pipeline.css.CSSResolver;
import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
import com.itextpdf.tool.xml.pipeline.end.PdfWriterPipeline;
import com.itextpdf.tool.xml.pipeline.html.AbstractImageProvider;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;
import com.itextpdf.tool.xml.pipeline.html.ImageProvider;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * @author Andrew.zheng
 * @version 2020/10/19
 * @className PdfGenerator
 * @Description
 */
public class PdfGenerator {
    private static final Logger LOGGER = LoggerFactory.getLogger(PdfGenerator.class);

    /**
     * @param templateName 模板文件路径
     * @param model        渲染的数据
     * @return 选然后的字符串
     * @throws Exception
     */
    public static String getRendererContent(String templateName, Map model, String temDir) {
        try {
            // 初始化FreeMarker ( 模板库 )
            Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
            cfg.setDirectoryForTemplateLoading(new File(temDir)); // 指定模板根目录文件
            cfg.setDefaultEncoding("UTF-8"); //指定默认字符集
            cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            cfg.setLogTemplateExceptions(false);
            // 提取模板 (template)
            Template tp = cfg.getTemplate(templateName);

            //开始以字符串形式返回渲染的结果
            StringWriter stringWriter = new StringWriter();
            BufferedWriter writer = new BufferedWriter(stringWriter);
            tp.process(model, writer);
            String htmlStr = stringWriter.toString();
            writer.flush();
            writer.close();
            return htmlStr;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("渲染失败!");
        }
    }


    public static void generatePlus(String htmlStr, OutputStream out, Map<String, Object> map) throws IOException, DocumentException {

        final String charsetName = "UTF-8";

        Document document = new Document(PageSize.A4, 90, 90, 70, 70);
        PdfWriter writer = PdfWriter.getInstance(document, out);
        document.open();

        writer.setPageEvent(new PDFBuilder());
//        // 加入水印
//        PdfContentByte waterMar = writer.getDirectContentUnder();
//        // 开始设置水印
//        waterMar.beginText();
//        // 设置水印透明度
//        PdfGState gs = new PdfGState();
//        // 设置填充字体不透明度为0.4f
//        gs.setFillOpacity(0.1f);
//        try {
//            // 设置水印字体参数及大小                                  (字体参数,字体编码格式,是否将字体信息嵌入到pdf中(一般不需要嵌入),字体大小)
//            waterMar.setFontAndSize(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED), 60);
//            // 设置透明度
//            waterMar.setGState(gs);

//            // 设置水印对齐方式 水印内容 X坐标 Y坐标 旋转角度
//            waterMar.showTextAligned(Element.ALIGN_RIGHT, "suyun", 300, 1000, 45);
//
//            // 设置水印对齐方式 水印内容 X坐标 Y坐标 旋转角度
//            waterMar.showTextAligned(Element.ALIGN_RIGHT, "suyun", 500, 850, 45);
//
//            // 设置水印对齐方式 水印内容 X坐标 Y坐标 旋转角度
//            waterMar.showTextAligned(Element.ALIGN_RIGHT, "suyun", 700, 700, 45);

//            // 设置水印颜色
//            waterMar.setColorFill(BaseColor.GRAY);
//            //结束设置
//            waterMar.endText();
//            waterMar.stroke();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            waterMar = null;
//            gs = null;
//        }

        //创建字体支持,防止乱码
        FontProvider fontProvider = new XMLWorkerFontProvider() {
            @Override
            public Font getFont(String fontname, String encoding, float size, final int style) {
                Font font = null;
                try {
//                                FontUtils.getFont(path,"simhei.ttf","黑体", java.awt.Font.PLAIN, 12f)
                    final String path = PdfGenerator.class.getResource("/").getPath() + "/bin/SIMSUN.TTC";
                    LOGGER.debug("PdfGenerator path:" + path);

                    // 方案一:使用本地字体(本地需要有字体)
                    BaseFont bf = BaseFont.createFont(path + ",0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                    // 方案二:使用jar包:iTextAsian,这样只需一个jar包就可以了
//                    BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
                    font = new Font(bf, size, style);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return font;
            }
        };

        // html内容解析
        HtmlPipelineContext htmlContext = new HtmlPipelineContext(new CssAppliersImpl(fontProvider)) {
            @Override
            public HtmlPipelineContext clone() throws CloneNotSupportedException {
                HtmlPipelineContext context = super.clone();
                try {
                    ImageProvider imageProvider = this.getImageProvider();
                    context.setImageProvider(imageProvider);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                return context;
            }
        };
        // 图片解析
        htmlContext.setImageProvider(new AbstractImageProvider() {
            String rootPath = PdfGenerator.class.getResource("/").getPath();

            @Override
            public String getImageRootPath() {
                return rootPath;
            }

            @Override
            public Image retrieve(String src) {
                if (StringUtils.isEmpty(src)) {
                    return null;
                }
                try {
                    ImageEntity imageEntity = (ImageEntity) map.get(src);
                    if (imageEntity == null) {
                        return null;
                    }
                    Image image = Image.getInstance(imageEntity.getData());
                    // 图片显示位置
                    image.setAbsolutePosition(400, 400);
                    if (image != null) {
                        store(src, image);
                        return image;
                    }
                } catch (Throwable e) {
                    LOGGER.warn("Picture path:" + src);
                    e.printStackTrace();
                }
                return super.retrieve(src);
            }
        });


        htmlContext.setAcceptUnknown(true).autoBookmark(true).setTagFactory(Tags.getHtmlTagProcessorFactory());

        // css解析
        CSSResolver cssResolver = XMLWorkerHelper.getInstance().getDefaultCssResolver(true);
        cssResolver.setFileRetrieve(new FileRetrieve() {
            @Override
            public void processFromStream(InputStream in,
                                          ReadingProcessor processor) throws IOException {
                try {
                    InputStreamReader reader = new InputStreamReader(in, charsetName);
                    int i = -1;
                    while (-1 != (i = reader.read())) {
                        processor.process(i);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            // 解析href
            @Override
            public void processFromHref(String href, ReadingProcessor processor) throws IOException {
                InputStream is = PdfGenerator.class.getResourceAsStream("/" + href);
                try {
                    InputStreamReader reader = new InputStreamReader(is, charsetName);
                    int i = -1;
                    while (-1 != (i = reader.read())) {
                        processor.process(i);
                    }
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        });

        HtmlPipeline htmlPipeline = new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer));
        Pipeline<?> pipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
        XMLWorker worker = null;
        worker = new XMLWorker(pipeline, true);
//        htmlStr = htmlStr.replace("<br>", "").replace("<hr>", "").replace("<img>", "").replace("<param>", "")
//                .replace("<link>", "");
        XMLParser parser = new XMLParser(true, worker, Charset.forName(charsetName));
        try {
            InputStream inputStream = new ByteArrayInputStream(htmlStr.getBytes());
            parser.parse(inputStream, Charset.forName("UTF-8"));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        document.close();
    }

}

注意:Windows默认GBK,PDF中文导出乱码或者不显示,解决办法设值JVM参数,编码为UTF-8,这时候控制台会乱码,测试之后改回来就可以了。

itextpdf导出PDF

模板制作:

1、打开制作的docx;

2、另存为筛选过的网页,后缀为html;

3、修改生成的html,修改mate元素信息,属性添加双引号,删除无效的引用;

参照模板路径:https://download.csdn.net/download/xionglangs/16727380

上一篇:ImageToPDF--图片转pdf文件


下一篇:java使用itextpdf插件生成pdf