feiyu02
2022-10-21 f22c4b9230808fed4fec80c435eccb4c833349a0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
package cn.flightfeather.supervision.common.pdf
 
import com.itextpdf.html2pdf.ConverterProperties
import com.itextpdf.html2pdf.HtmlConverter
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider
import com.itextpdf.io.font.PdfEncodings
import com.itextpdf.kernel.font.PdfFontFactory
import com.itextpdf.layout.font.FontProvider
import freemarker.template.Configuration
import org.apache.pdfbox.pdmodel.PDDocument
import org.apache.pdfbox.rendering.PDFRenderer
import java.io.*
import javax.imageio.ImageIO
import javax.servlet.http.HttpServletResponse
 
 
/**
 * @Description: 生成PDF工具类
 */
object GeneratePdfUtil {
    private val TEMPORARY_CONTRACT_HTML = (Thread.currentThread().contextClassLoader?.getResource("/")?.path ?: "src/main/resources/") + "templates/temporary.html"
 
    private val SIMSUN_FILE = (Thread.currentThread().contextClassLoader?.getResource("/")?.path ?: "src/main/resources/") + "font/"
 
    private var cfg: Configuration? = null
 
    @Throws(Exception::class)
    fun generateContract(param: DynamicParam): List<String> {
        // 生成html合同
        generateHTML(param.templatePath, param.templateName, param.param)
        // 根据html合同生成pdf合同
        generatePDF(param.outPath + param.outName)
        // 根据pdf生成图片
        val picPaths = generatePic(param.outPath + param.outName)
        // 删除临时html格式合同
        removeFile(TEMPORARY_CONTRACT_HTML)
        return picPaths
    }
 
    /**
     * @Description 生成html格式
     */
    @Throws(Exception::class)
    private fun generateHTML(templatePath: String, templateName: String, paramMap: Map<String, Any>) {
        if (cfg == null) {
            cfg = Configuration(Configuration.VERSION_2_3_31)
            cfg?.defaultEncoding = "UTF-8"
            /**
             * 1.setClassForTemplateLoading(this.getClass(), "/HttpWeb");
             * 基于类路径,HttpWeb包下的framemaker.ftl文件
             * 2.setDirectoryForTemplateLoading(new File("/template"));
             * 基于文件系统,template目录下的文件
             * 3.setServletContextForTemplateLoading(request.getSession().getServletContext(), "/template");
             * 基于Servlet Context,指的是基于WebRoot下的template下的framemaker.ftl文件
             */
            val file = File(templatePath)
            if (!file.exists()) {
                file.mkdirs()
            }
            cfg?.setDirectoryForTemplateLoading(file)
        }
 
        // templateName.ftl为要装载的模板
        val template = cfg?.getTemplate(templateName)
        val outHtmFile = File(TEMPORARY_CONTRACT_HTML)
        val out: Writer = BufferedWriter(OutputStreamWriter(FileOutputStream(outHtmFile), "utf-8"))
        // 将参数输出到模版,并操作到HTML上
//        val env = template?.createProcessingEnvironment(paramMap, out)
//        env?.outputEncoding = "utf-8"
//        env?.process()
        template?.process(paramMap, out)
        out.close()
    }
 
    /**
     * @Description 根据html生成pdf
     */
    @Throws(Exception::class)
    private fun generatePDF(pdfUrl: String) {
        val htmFile = File(TEMPORARY_CONTRACT_HTML)
        val pdfFile = File(pdfUrl)
        if (!pdfFile.parentFile.exists()) {
            pdfFile.parentFile.mkdirs()
        }
        println(pdfUrl)
//        val url = htmFile.toURI()
//        val os: OutputStream = FileOutputStream(pdfFile)
//        val renderer = ITextRenderer()
//        renderer.setDocument(url)
//        val fontResolver = renderer.fontResolver
//        // 解决中文支持问题
//        fontResolver.addFont(SIMSUM_FILE, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED)
//        renderer.layout()
//        renderer.createPDF(os)
//        os.close()
        val p = ConverterProperties()
        println("------------------------------>>>>>>>${SIMSUN_FILE}")
//        p.charset = "UTF-8"
        p.fontProvider = FontProvider().apply {
//            addStandardPdfFonts()
//            addDirectory(SIMSUN_FILE)
            addSystemFonts()
        }
        HtmlConverter.convertToPdf(htmFile, pdfFile, p)
    }
 
    /**
     * @Description 根据pdf生成图片
     */
    @Throws(Exception::class)
    private fun generatePic(pdfUrl: String): List<String> {
        val picPaths = mutableListOf<String>()
 
        val pdfFile = File(pdfUrl)
        if (!pdfFile.exists()) {
            throw FileNotFoundException("$pdfUrl 文件不存在")
        }
        val doc = PDDocument.load(pdfFile)
        val renderer = PDFRenderer(doc)
        val pageCount = doc.numberOfPages
        for (i in 0 until pageCount) {
            val outputPath = pdfUrl.replace(".pdf", "(${i}).jpg");
            val outputFile = File(outputPath)
            picPaths.add(outputPath)
            // dpi,图片像素点,dpi越高图片体积越大,216很清晰,105体积稳定
            val image = renderer.renderImageWithDPI(i, 216f)
            // 格式为JPG
            ImageIO.write(image, "jpg", outputFile)
        }
 
        doc.close()
 
        return picPaths
    }
 
    /**
     * @Description 移除文件
     */
    private fun removeFile(fileUrl: String) {
        val file = File(fileUrl)
        file.delete()
    }
 
    @Throws(Exception::class)
    fun returnPdfStream(response: HttpServletResponse, pathName: String?) {
        response.contentType = "application/pdf"
        val file = File(pathName)
        if (file.exists()) {
            val `in` = FileInputStream(file)
            val out: OutputStream = response.outputStream
            val b = ByteArray(1024 * 5)
            var n: Int
            while (`in`.read(b).also { n = it } != -1) {
                out.write(b, 0, n)
            }
            out.flush()
            `in`.close()
            out.close()
        }
    }
}