<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">package com.bcxin.backend.domain.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.bcxin.backend.core.utils.FtpUtils;
import com.bcxin.backend.domain.configs.FileModeConfig;
import com.bcxin.backend.domain.utils.ftp.FtpUtil;
import com.bcxin.backend.domain.utils.ftp.UploadResult;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.openhtmltopdf.extend.FSSupplier;
import com.openhtmltopdf.outputdevice.helper.BaseRendererBuilder;
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.helper.W3CDom;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StopWatch;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.FileTime;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PDFUtils {
    private static final Logger logger = LoggerFactory.getLogger(PDFUtils.class);
    private static Map&lt;String, String&gt; tempHtmlMap = Maps.newHashMap();

    //鍒濇鍔犺浇瀛椾綋娴佺紦瀛�
    private static FSSupplier&lt;InputStream&gt; fSSupplier = null;
    public static void generatePdfByOpenhtmltopdf(String tempUrl, String pdfPath, Object formData) throws IOException {
        String htmlContent = tempHtmlMap.get(tempUrl);
        if (StringUtils.isEmpty(htmlContent)) {
            htmlContent = HttpUtil.get(tempUrl);
            tempHtmlMap.put(tempUrl, htmlContent);
        }
        String formStr = JSON.toJSONString(formData);
        Map&lt;String, String&gt; map = com.alibaba.fastjson.JSONObject.parseObject(formStr, Map.class);
        String zDay = map.get("zDay").substring(0, 2);
        htmlContent = htmlContent.replace("${zYear}", map.get("zYear")).replace("${zMonth}", map.get("zMonth")).replace("${zDay}", zDay);
        htmlContent = format(htmlContent, formData);
        //鍔犺浇html鏂囦欢
        org.jsoup.nodes.Document document = Jsoup.parse(htmlContent);
        document.outputSettings().syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.html);
        //灏嗚浆鎹㈠悗鐨刾df鏂囦欢鏀惧埌涓存椂鐩綍
        try (OutputStream os = new FileOutputStream(pdfPath)) {
            PdfRendererBuilder builder = new PdfRendererBuilder();
            // 浼樺寲娓叉煋杩囩▼锛屽噺灏戜笉蹇呰鐨勫鐞嗘楠わ紝浠庤€屽姞蹇玃DF鐢熸垚鐨勯€熷害
            //  builder.useFastMode();
            builder.withUri(pdfPath);
            builder.toStream(os);
            builder.withW3cDocument(new W3CDom().fromJsoup(document), "");
            //寮曞叆鎸囧畾瀛椾綋锛屾敞鎰忓瓧浣撳悕闇€瑕佸拰css鏍峰紡涓寚瀹氱殑瀛椾綋鍚嶇浉鍚�
            builder.useFont(getFSSupplier("STSongti-SC-Regular.TTF"), "STSongti-SC-Regular");
//            builder.useDefaultPageSize(180,135, BaseRendererBuilder.PageSizeUnits.MM);

            builder.run();
        }
    }

    private static String format(String content, Object formData) {
        JSONObject data = JSONObject.fromObject(formData);
        String pattern = "\\$\\{(.+?)\\}";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(content);
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            String key = m.group(1);
            Object value = data.get(key);
            m.appendReplacement(sb, value == null ? "" : value.toString());
        }
        m.appendTail(sb);
        return sb.toString();
    }

    private static FSSupplier&lt;InputStream&gt; getFSSupplier(String path) {
        if (fSSupplier == null) {
            fSSupplier = new FSSupplier&lt;InputStream&gt;() {
                @Override
                public InputStream supply() {
                    try {
                        Resource resource = new ClassPathResource(path);
                        return resource.getInputStream();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return null;
                }
            };
        }
        return fSSupplier;
    }

    /**
     * &lt;b&gt; done鍦板潃鏂囦欢杞瓨鍒癴tp &lt;/b&gt;
     * 闇€瑕佹敞鎰�
     * 1.鏂囦欢鍒濆瀛樺湪鏈嶅姟鍣ㄧ洰褰曚笂锛歅ropertyUtil.getPath()
     * 2.鏂囦欢杞瓨ftp鐩綍涓婏細FileModeConfig.getFilePath()
     * 3.鍙ftp瀹屾垚鏂囦欢杞瓨灏卞垹闄ueue銆乨one鐩綍瀵瑰簲鏂囦欢鑺傜渷绌洪棿
     *
     * @author ZXF
     * @create 2022/11/11 0011 14:07
     * @version
     * @娉ㄦ剰浜嬮」 &lt;/b&gt;
     */
    public static String uploadFtpFile(String pdfPath,String rootPath) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        String uploadFilePath = null;
        JSONObject json = new JSONObject();

        StringBuilder sb = new StringBuilder();

        try {
            String outFilePath = rootPath + pdfPath;
            //璇诲彇涓存椂鐩綍涓婄殑鏂囦欢鍒癴tp瀵瑰簲鐩綍
            File outFile = new File(outFilePath);
            File[] fo = outFile.listFiles();

            if (fo == null || fo.length == 0) {
                logger.error("鎵€鍦ㄧ洰褰�({})鐨勬枃浠跺垪琛ㄤ负绌�", outFile);
                return null;
            }

            List&lt;String&gt; successList = new ArrayList&lt;&gt;();
            List&lt;String&gt; failList = new ArrayList&lt;&gt;();

            uploadFilePath = (StrUtil.isEmpty(FileModeConfig.getFilePath()) ? "" : FileModeConfig.getFilePath()) + "/uploads/" + pdfPath.split("/uploads/")[1];
            List&lt;UploadResult&gt; list = FtpUtil.upload(uploadFilePath, fo);


            //褰撹繛鎺ユ柇浜嗭紝杩斿洖鍊肩疆null锛岄噸鏂颁笂浼犱竴閬�
            if (list == null) {
                sb.append(String.format("鑾峰彇鍒扮殑uploadFilePath=%s;list=null;",uploadFilePath));
                uploadFilePath = (StrUtil.isEmpty(FileModeConfig.getFilePath()) ? "" : FileModeConfig.getFilePath()) + "/uploads/" + pdfPath.split("/uploads/")[1];
                list = FtpUtil.upload(uploadFilePath, fo);

                sb.append(String.format("閲嶆柊鑾峰彇鐨剈ploadFilePath=%s;",uploadFilePath));
            }

            if (!CollectionUtils.isEmpty(list)) {
                sb.append(String.format("閲嶆柊鑾峰彇鐨剈ploadFilePath.list=%s;",list.size()));
                for (UploadResult result : list) {
                    if (result.isResult()) {
                        logger.info("======&gt;鏂囦欢涓婁紶FTP鎴愬姛({})", result.getFileName());
                        //鎴愬姛鐨勬枃浠舵妸鏂囦欢鍚嶇О鍔犲叆鍒皊uccessFile涓�,鍒拌繖閲岃鏄庤繖娆″惊鐜垚鍔熶簡
                        successList.add(result.getFileName());
                    } else {
                        logger.error("======&gt;鏂囦欢涓婁紶FTP澶辫触({})", result.getFileName());
                        failList.add(result.getFileName());
                    }
                }

                String successFile = String.join(",", successList);
                String failFile = String.join(",", failList);
                json.put("success", successFile);
                json.put("fail", failFile);
            }else {
                sb.append("閲嶆柊鑾峰彇鐨剈ploadFilePath.list=EMPTY;");
            }
        } catch (Exception e) {
            logger.error("======&gt;涓婁紶ftp澶辫触:{}", uploadFilePath, e);
        } finally {
            stopWatch.stop();
            logger.error("鎵цuploadFtpFile鐨勮窡韪俊鎭�:{}; 鎬昏€楁椂{}绉�", sb, stopWatch.getTotalTimeSeconds());
        }

        return json.toString();
    }

    /**
     * &lt;b&gt; done鍦板潃鏂囦欢杞瓨鍒�/uploads/pdf/dianziqianzhang/鏃ユ湡锛�2024-10-21锛� &lt;/b&gt;
     * 闇€瑕佹敞鎰�
     * 1.鏂囦欢鍒濆瀛樺湪鏈嶅姟鍣ㄧ洰褰曚笂锛歅ropertyUtil.getPath()
     * 2.鏂囦欢杞瓨ftp鐩綍涓婏細FileModeConfig.getFilePath()
     * 3.鍙鏃ユ湡鐩綍瀹屾垚鏂囦欢杞瓨灏卞垹闄ueue銆乨one鐩綍瀵瑰簲鏂囦欢鑺傜渷绌洪棿
     *
     * @author ZXF
     * @create 2022/11/11 0011 14:07
     * @version
     * @娉ㄦ剰浜嬮」 &lt;/b&gt;
     */
    public static String uploadDayFile(String pdfPath,String rootPath) {

        String outFilePath = rootPath + pdfPath;
        String dayFilePath = outFilePath.replace("/out", "/"+DateUtil.today());
        File dayFile = new File(dayFilePath);
        if (!dayFile.exists()) {
            dayFile.mkdirs();
        }
        //璇诲彇涓存椂鐩綍涓婄殑鏂囦欢鍒癴tp瀵瑰簲鐩綍
        File outFile = new File(outFilePath);
        File[] fo = outFile.listFiles();
        List&lt;String&gt; successList = new ArrayList&lt;&gt;();
        List&lt;String&gt; failList = new ArrayList&lt;&gt;();
        if(fo==null || fo.length==0){
            System.err.println("=======&gt;涓婁紶ftp 鏂囦欢锛歰ut鐩綍娌℃湁鏈夋晥鏂囦欢&lt;=======");
            return null;
        }

        JSONObject json = new JSONObject();
        try {
            Path filePath;FileTime lastModifiedTime;Instant lastModifiedInstant;Instant now;Duration duration;
            for(int i = 0; i &lt; fo.length; i++){
                String fileName = fo[i].getName();
                String oPath = outFilePath + "/" + fileName;
                filePath = Paths.get(oPath);
                lastModifiedTime = Files.getLastModifiedTime(filePath);
                lastModifiedInstant = Instant.ofEpochMilli(lastModifiedTime.toMillis());
                now = Instant.now();
                duration = Duration.between(lastModifiedInstant, now);
                //澶т簬1鍒嗛挓娌℃湁杩涜鍙樻洿鐨勬枃浠舵墠鍓垏
                if (duration.toMinutes() &gt; 1) {
                    Files.move(Paths.get(oPath), Paths.get(dayFilePath + "/" + fileName), StandardCopyOption.REPLACE_EXISTING);
                    successList.add(fileName);
                }
            }
            String successFile = String.join(",", successList);
            String failFile = String.join(",", failList);
            json.put("success",successFile);
            json.put("fail",failFile);
        }catch (Exception e){
            System.err.println("=======&gt;涓婁紶ftp澶辫触浜嗭細"+e.getMessage()+"&lt;=======");
        }
        return json.toString();
    }
}
</pre></body></html>