当前位置:   article > 正文

html 转pdf

html 转pdf
package com.cudatec.infra.se.controller;

import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;

/**
* @program: infra-acm
* @description:
* @author: xuwenjie
* @create: 2020-09-25 10:33
**/
public class TestController {

    public static void main(String[] args) {
        String outputFile = "test.pdf";
        InputStream inputStream = null;
        Document doc = null;
        try {
            OutputStream out = new FileOutputStream(outputFile);
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            ITextRenderer renderer = new ITextRenderer();
            inputStream = new ByteArrayInputStream(buildContent().getBytes("utf-8"));
            doc =builder.parse(inputStream);
            renderer.setDocument(doc, null);
            renderer.layout();
            renderer.createPDF(out, true);
            out.flush();
            out.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

        public static String buildContent() throws IOException {
        //加载邮件html模板
        String fileName = "demo.html";
        InputStream inputStream = ClassLoader.getSystemResourceAsStream(fileName);
        BufferedReader fileReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        try {
            while ((line = fileReader.readLine()) != null) {
            buffer.append(line);
            }
        } catch (Exception e) {
            //日志异常
        } finally {
            inputStream.close();
            fileReader.close();
        }
            String value = buffer.toString();
            //可以对value操作
            return value;
        }
}

  • 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

//依赖

<!--html 转 pdf -->
	<dependency>
		<groupId>org.xhtmlrenderer</groupId>
		<artifactId>flying-saucer-pdf</artifactId>
		<version>9.0.7</version>
	</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/304750
推荐阅读
相关标签
  

闽ICP备14008679号