freemarker 生成pdf


1 导入依赖

<!-- freemarker 读取html模板文件 -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.28</version>
        </dependency>
        <!-- xml 将html模板文件转换成pdf -->
        <dependency>
            <groupId>org.xhtmlrenderer</groupId>
            <artifactId>flying-saucer-pdf</artifactId>
            <version>9.1.16</version>
        </dependency>

2 编写test.ftl文件

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title></title>
    <style type="text/css">
    body {
    font-family: FangSong;
    }
    </style>
</head>
<body>
<p>${name}:</p>
<p style="text-indent: 2em">哈哈哈</p>
</body>
</html>

3  PdfController

@ApiOperation("pdf生成")
    @PostMapping(value = "pdfCreate")
    public void pdfCreate(@RequestBody Map map) throws IOException {
        pdfService.pdfCreate(map);
    }

4  PdfServiceImpl

@Override
    public void pdfCreate(Map map) throws IOException {
        PdfUtil.pdfCreate(map,"test.ftl");
    }

5  PdfUtil 工具类

public class PdfUtil {
    public static void pdfCreate(Map map,String templateFtlName) throws IOException {
        // 创建一个FreeMarker实例, 负责管理FreeMarker模板的Configuration实例
        Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        // 指定FreeMarker模板文件的位置
        configuration.setClassForTemplateLoading(PdfUtil.class, "/template");
        ITextRenderer renderer = new ITextRenderer();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        StringWriter writer = new StringWriter();
        String fileName = String.valueOf(System.currentTimeMillis()) + ".pdf";
        File file = new File("src/main/resources/template/result/" + fileName);
        OutputStream outputStream = new FileOutputStream(file);

        try {
            // 设置 css中 的字体样式(暂时仅支持宋体和黑体) 必须,不然中文不显示
            ITextFontResolver fontResolver = renderer.getFontResolver();
            fontResolver.addFont("src/main/resources/template/font/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            fontResolver.addFont("src/main/resources/template/font/SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            fontResolver.addFont("src/main/resources/template/font/MSYH.TTC", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            fontResolver.addFont("src/main/resources/template/font/MSYHBD.TTC", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            fontResolver.addFont("src/main/resources/template/font/MSYHL.TTC", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            fontResolver.addFont("src/main/resources/template/font/SIMLI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            // 设置模板的编码格式
            configuration.setEncoding(Locale.CHINA, "UTF-8");
            // 获取模板文件
            Template template = configuration.getTemplate(templateFtlName, "UTF-8");
            // 将数据输出到html中
            template.process(map, writer);
            writer.flush();
            String html = writer.toString();
            // 把html代码传入渲染器中
            renderer.setDocumentFromString(html);

            // 设置模板中的图片路径 (这里的images在resources目录下) 模板中img标签src路径需要相对路径加图片名 如<img src="images/xh.jpg"/>
//            String url = PdfUtil.class.getClassLoader().getResource("static/images").toURI().toString();
//            renderer.getSharedContext().setBaseURL(url);
            renderer.layout();
            renderer.createPDF(out, false);
            out.flush();
            renderer.finishPDF();
            out.writeTo(outputStream);
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }
}

 

using System;
using MySql.Data.MySqlClient;

namespace mysql
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            MySqlConnection mysql = getMySqlConnect();
            //查询
            String sqlSearch = "select * from user";
            //插入
            String sqlInsert = "INSERT INTO USER(name,password) VALUES('user1', '123456')";
            //更新
            String sqlUpdate = "UPDATE user SET num = 1 where id = 12";
            //删除
            String sqlDelete = "delete from user where id = 9";
            MySqlCommand mySqlCommand = new MySqlCommand(sqlSearch, mysql);
            mysql.Open();
            getResult(mySqlCommand);
            insert(new MySqlCommand(sqlInsert, mysql));
            delete(new MySqlCommand(sqlDelete, mysql));
            mysql.Close();
        }
        //数据库链接
        public static MySqlConnection getMySqlConnect()
        {
            String mysqlStr = "Database=time;Data Source=47.116.66.21;User Id=root;Password=123456;pooling=false;CharSet=utf8;port=3306";
            return new MySqlConnection(mysqlStr);
        }
        //建立执行命令语句对象
        public static MySqlCommand GetMySqlCommand(String sqlStr, MySqlConnection mySqlConnection)
        {
            return new MySqlCommand(sqlStr, mySqlConnection);
        }
        //查询并获得结果集并遍历
        public static void getResult(MySqlCommand mySqlCommand)
        {
            MySqlDataReader reader = mySqlCommand.ExecuteReader();
            try
            {
                while (reader.Read())
                {
                    if (reader.HasRows)
                    {
                        Console.WriteLine("=============");
                        Console.WriteLine(reader.GetValue(0).ToString() + reader.GetValue(1).ToString() + reader.GetValue(2).ToString() +
                            reader.GetValue(3).ToString() + reader.GetValue(4).ToString() + reader.GetValue(5).ToString() +
                            reader.GetValue(6).ToString() + reader.GetValue(7).ToString());
                    }
                }
            }
            catch (Exception)
            {
                Console.WriteLine("查询失败");
            }
            finally
            {
                reader.Close();
            }
        }
        //插入数据
        public static void insert(MySqlCommand mySqlCommand) {
            try
            {
                mySqlCommand.ExecuteNonQuery();
            }
            catch(Exception e) {
                Console.WriteLine(e.Message);
                Console.WriteLine("插入失败");
            }
        }
        //更新数据
        public static void update(MySqlCommand mySqlCommand)
        {
            try
            {
                mySqlCommand.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("更新失败");
            }
        }
        //删除数据
        public static void delete(MySqlCommand mySqlCommand)
        {
            try
            {
                mySqlCommand.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("删除失败");
            }
        }
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM