博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
利用velocity模板以及itext生成pdf
阅读量:4439 次
发布时间:2019-06-07

本文共 3986 字,大约阅读时间需要 13 分钟。

利用velocity模板以及itext生成pdf

我整理的源码:http://download.csdn.net/download/u012174571/8748897

首先是velocity的使用:

         1.下载:http://velocity.apache.org/download.cgi

         2.导入包:velocity-1.7.jar、commons-lang-2.4.jar、commons-collections-3.2.1.jar这三个包导入工程中。

         3.用法演示:

         新建一个文件:hello.vm放在根目录下,

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<style>

*{font-family: SimSun;}

</style>

</head>

<body>

    <p>

       ${name}

    </p>

  

   ${date}

</body>

</html>

 

 

 

新建一个测试类TestVelocity

import java.io.StringWriter;

import java.util.Date;

 

import org.apache.velocity.Template;

import org.apache.velocity.VelocityContext;

import org.apache.velocity.app.VelocityEngine;

 

 

public class TestVelocity {

 

   public static void main(String[] args) throws Exception {

      //初始化并取得Velocity引擎

      VelocityEngine ve = new VelocityEngine();

      ve.init();

 

      //取得velocity的模版

      Template t = ve.getTemplate("src/hello.vm");

 

      //取得velocity的上下文context

      VelocityContext context = new VelocityContext();

 

      //vm中写入信息

      context.put("name", "Liang");

      context.put("date", (new Date()).toString());

 

 

      StringWriter writer = new StringWriter();

 

      //把数据填入上下文

      t.merge(context, writer);

 

     

      String out = writer.toString();

      System.out.println(writer.toString());

 

   }

   public static String get() throws Exception{

      //初始化并取得Velocity引擎

            VelocityEngine ve = new VelocityEngine();

            ve.init();

 

            //取得velocity的模版

            Template t = ve.getTemplate("src/hello.vm","UTF-8");

            //velocity 在给路劲时会比较麻烦,

           

            //取得velocity的上下文context

            VelocityContext context = new VelocityContext();

 

 

            StringWriter writer = new StringWriter();

 

            //把数据填入上下文

            t.merge(context, writer);

 

            //输出流

            String out = writer.toString();

            return out;

   }

}

 

 

 

 

4.运行输出结果:

<html>

<head>

<meta http-equiv="Content-Type"content="text/html; charset=UTF-8" />

<style>

*{font-family:SimSun;}

</style>

</head>

<body>

    <p>

       Liang

    </p>

         Thu May 28 14:23:22 CST 2015

</body>

</html>

 

 

其次itext的使用

下载包:需要两个包:(最好都下最新的,不然不支持中文)

         1.itext核心包: http://sourceforge.net/projects/itext/files/

         2.xml包:http://sourceforge.net/projects/xmlworker/files/

其中有用的是:itext下的itextpdf-5.5.6.jar

                              xml下的xmlworker-5.5.6.jar

在E盘创建一个html;写上些东西(先不要写中文)

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.Reader;

import java.io.StringReader;

import java.nio.charset.Charset;

 

 

import com.itextpdf.text.Document;

import com.itextpdf.text.DocumentException;

import com.itextpdf.text.pdf.PdfWriter;

import com.itextpdf.tool.xml.XMLWorkerHelper;

 

public class Test  {

 

   public static final String HTML = "E:/MyHtml.html";

    public static final String DEST = "E:/hero.pdf";

 

    /**

     * Creates a PDF with the words "Hello World"

     * @param file

     * @throws IOException

     * @throws DocumentException

     */

    public void createPdf(String file) throws Exception {

        // step 1

        Document document = new Document();

        // step 2

        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));

        // step 3

        document.open();

        String value = TestVelocity.get();

        @SuppressWarnings("deprecation")

        Reader reader = null;

        reader = new StringReader(value);

       

        // step 4

//        XMLWorkerHelper.getInstance().parseXHtml(writer, document, reader);

        XMLWorkerHelper.getInstance().parseXHtml(writer, document,

             new FileInputStream(HTML) , Charset.forName("UTF-8"));

        // step 5

        document.close();

    }

 

    /**

     * Main method

     */

    public static void main(String[] args) throws Exception{

        File file = new File(DEST);

        file.getParentFile().mkdirs();

        new Test().createPdf(DEST);

    }

}

 

     

ok可以去e盘找pdf了。

 

 

 

 

两者合并:

         上边代码中的

 String value = TestVelocity.get();

        @SuppressWarnings("deprecation")

        Reader reader = null;

        reader = new StringReader(value);

       

        // step 4

//       XMLWorkerHelper.getInstance().parseXHtml(writer, document, reader);

就是去找velocity并交给itex生成pdf;将注解放开,把这段  XMLWorkerHelper.getInstance().parseXHtml(writer,document,

             new FileInputStream(HTML) , Charset.forName("UTF-8"));

注解掉,ok再生成的pdf就是hello.vm中的内容了;

 

 

中文处理:itext对中文支持不是很好,但是高版本的jar包已经可以支持中文了。在vm中添加样式:<style>

*{font-family: SimSun;}

</style>

把所有的文字都指定为宋体(最好这个字体,我试过有的字体会少一些字);字体记得要往服务器加哦,服务器一般是linux的没有中文字体哦!

转载于:https://www.cnblogs.com/taocong/p/5939443.html

你可能感兴趣的文章
as3事件流机制彻底理解
查看>>
Selenium webdriver操作日历控件
查看>>
Pascal程序练习-与7无关的数
查看>>
Linux:cut命令...未完待续
查看>>
微信小程序从零开始开发步骤(一)搭建开发环境
查看>>
SQL*Net more data to client
查看>>
Tcpdump使用方法总结
查看>>
PX4地面站QGroundControl在ubuntu下的安装
查看>>
react实现svg实线、虚线、方形进度条
查看>>
Redis笔记(六):Java中使用Redis
查看>>
正则表达式高级用法【原】
查看>>
深入理解JavaScript系列(33):设计模式之策略模式
查看>>
Unity中Invoke函数基础用法
查看>>
PSP
查看>>
20165208 2017-2018-2 《Java程序设计》第九周学习总结
查看>>
Masonry的使用
查看>>
关于户口
查看>>
Web
查看>>
函数名应用,闭包,装饰器初识
查看>>
JavaScript Date Format
查看>>