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