===============action===========================

//退款导出word
    public void exportWordTk() throws IOException{
         Long userId=(Long)ServletActionContext.getContext().getSession().get(Constant.SESSION_USER_ID);
        //获取生成Pdf需要的一些路径
        String tmPath=ServletActionContext.getServletContext().getRealPath("download/template");//vm 模板路径
        String wordPath=ServletActionContext.getServletContext().getRealPath("download/file");//生成word路径
        //wordPath+"/"+userId+"_"+fk+".doc"
        //数据
        Map map=new HashMap();//velocity模板中的变量
        map.put("date1",this.fk);
        map.put("date",new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()));
        String newFile=wordPath+"/tk_word_"+userId+".doc";
        File file=new File(newFile);
        if(!file.exists()){
            //设置字体,支持中文显示
            new PdfUtil().addFontAbsolutePath(ServletActionContext.getServletContext().getRealPath("dzz/pdfFont/simsun.ttf"));//这个字体需要自己去下载
            PdfUtil.createByVelocityPdf(tmPath,"tk_word.vm", wordPath+"/tk_word_"+userId+".pdf", map);//导出PDF
            PdfUtil.createByVelocityDoc(tmPath,"tk_word.vm",newFile, map);//导出word
        }
        sendMsgAjax("dzz/download/file/tk_word_"+userId+".doc");
    }

=================vm 文件模板(tk_word.vm)=====================

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <style type="text/css">
    body, button, input, select, textarea {
    color: color:rgb(0,0,0);
    font: 14px/1.5 tahoma,arial,宋体,sans-serif;
    }
    p{
    margin:0;padding:0;
    }
    .title{
    border-bottom:1px solid rgb(0,0,0);
    margin:0;
    padding:0;
    width:85%;
    height:25px;
    }
    li{
    list-style:none;
    }
    .li_left li{
        text-align:left;
        line-height:47px;
         font-size:14pt;
    }
    .li_left{
        width:610px;
    }
    .fnt-21{
    font-size:16pt;
    }
    table{
    width:90%;
    /*argin-left:25px;*/
    }
    div_cls{
        width:100%;
        text-align:center;
    }
    </style>
  </head>
 
  <body style="font-family: songti;width:100%;text-align:center;">
 <div style="text-align:center;"><b class="fnt-21">&nbsp;&nbsp;本组评审结果清单</b> </div>
  <table  border="1" cellpadding="0" cellspacing="0" style="width:90%;margin-left:25px;">
    <tr>
      <td style="width:20%" align="center">申报单位</td>
      <td style="width:10%" align="center">申报经费(万元)</td>

</tr>
   
  </table>
      <br/>
      <div>
          <ul style="float:right;margin-right:40px;">
              <li>$date</li><!--获取后天封装的数据-->
          </ul>
      </div>
  </body>
</html>

====================工具类======================

package com.qgc.dzz.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.struts2.ServletActionContext;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;

public class PdfUtil {
    private static List<String> fonts = new ArrayList();//字体路径

 /**
     * 使用vm导出word
     * @param localPath VM 模板路径
     * @param templateFileName vm 模板名称
     * @param docPath 生成文件的路径,包含文件如:d://temp.doc
     * @param map 参数,传递到vm
     * @return
     */
      public static boolean createByVelocityDoc(String localPath, String templateFileName, String docPath, Map<String, Object> map)
      {
        try
        {
            createFile(localPath,templateFileName,docPath, map);
          return true;
        } catch (Exception e) {
        e.printStackTrace();
            
        }
        return false;
      }
      
    /**
     * 导出pdf
     * @param localPath VM 模板路径
     * @param templateFileName vm 模板名称
     * @param pdfPath 生成文件的路径,包含文件如:d://temp.pdf
     * @param map 参数,传递到vm
     * @return
     */
      public static boolean createByVelocityPdf(String localPath, String templateFileName, String pdfPath, Map<String, Object> map)
      {
        try
        {
        
              
          String htmlPath = pdfPath + UUID.randomUUID().toString() + ".html";

         createFile(localPath, templateFileName, htmlPath, map);//生成html 临时文件

         HTML2OPDF(htmlPath, pdfPath, fonts);//html转成pdf

         File file = new File(htmlPath);
         file.delete();

          return true;
        } catch (Exception e) {
        e.printStackTrace();
            
        }
        return false;
      }
      
      /**
       * 合并PDF
       * @param writer
       * @param document
       * @param reader
       * @throws DocumentException
       */
    public void addToPdfUtil(PdfWriter writer, Document document,
            PdfReader reader) throws DocumentException {

int n = reader.getNumberOfPages();

Rectangle pageSize = document.getPageSize();

float docHeight = pageSize.getHeight();

float docWidth = pageSize.getWidth();

for (int i = 1; i <= n; i++) {

document.newPage();

PdfImportedPage page = writer.getImportedPage(reader, i);

Image image = Image.getInstance(page);

float imgHeight = image.getPlainHeight();

float imgWidth = image.getPlainWidth();

if (imgHeight < imgWidth) {

float temp = imgHeight;

imgHeight = imgWidth;

imgWidth = temp;

image.setRotationDegrees(90.0F);

}

if ((imgHeight > docHeight) || (imgWidth > docWidth)) {

float hc = imgHeight / docHeight;

float wc = imgWidth / docHeight;

float suoScale = 0.0F;

if (hc > wc)

suoScale = 1.0F / hc * 100.0F;

else {

suoScale = 1.0F / wc * 100.0F;

}

image.scalePercent(suoScale);

}

image.setAbsolutePosition(0.0F, 0.0F);

document.add(image);

}
    }

/**
     * html 转成 pdf 方法
     * @param htmlPath html路径
     * @param pdfPath pdf路径
     * @param fontPaths 字体路径
     * @throws Exception
     */
    public static void HTML2OPDF(String htmlPath, String pdfPath,
            List<String> fontPaths)

throws Exception

{

String url = new File(htmlPath).toURI().toURL().toString();//获取生成html的路径

OutputStream os = new FileOutputStream(pdfPath);//创建输出流
        
        ITextRenderer renderer = new ITextRenderer();//itext 对象
        
        ITextFontResolver fontResolver = renderer.getFontResolver();//字体
//        //支持中文显示字体
//        fontResolver.addFont(ServletActionContext.getServletContext().getRealPath("dzz/pdfFont/simsun_0.ttf"),    
//                BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        if ((fontPaths != null) && (!fontPaths.isEmpty())) {

URL classPath = PdfUtil.class.getResource("/");

for (String font : fontPaths) {

if (font.contains(":"))

fontResolver.addFont(font, "Identity-H", false);

else {

fontResolver.addFont(classPath + "/" + font, "Identity-H",
                            false);

}

}

}

renderer.setDocument(url);//设置html路径

renderer.layout();

renderer.createPDF(os);//html转换成pdf

System.gc();

os.close();

System.gc();

}

public static boolean createFile(String localPath, String templateFileName,
            String newFilePath, Map<String, Object> map)

{

try

{

VelocityEngine engine = new VelocityEngine();

engine.setProperty("file.resource.loader.path", localPath);//指定vm路径

Template template = engine.getTemplate(templateFileName, "UTF-8");//指定vm模板

VelocityContext context = new VelocityContext();//创建上下文对象

if (map != null)

{

Object[] keys = map.keySet().toArray();

for (Object key : keys) {

String keyStr = key.toString();

context.put(keyStr, map.get(keyStr));//传递参数到上下文对象

}

}

PrintWriter writer = new PrintWriter(newFilePath, "UTF-8");//写入参数到vm
        
            template.merge(context, writer);

writer.flush();

writer.close();

return true;

} catch (Exception e) {

e.printStackTrace();

}
        return false;

}

public static Font FONT = getChineseFont();

public static BaseFont BSAE_FONT = getBaseFont();

/**
     * 支持显示中文
     * @return
     */
    public static Font getChineseFont() {

BaseFont bfChinese = null;

try {

bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H",
                    false);

} catch (DocumentException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

Font fontChinese = new Font(bfChinese);

return fontChinese;

}

public static BaseFont getBaseFont() {

BaseFont bfChinese = null;

try {

bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H",
                    false);

} catch (DocumentException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return bfChinese;

}
    
      public void addFontAbsolutePath(String path)
      {
        this.fonts.add(path);
      }

public void addFontClassPath(String path)
      {
        this.fonts.add(path);
      }

public List<String> getFonts() {
        return this.fonts;
      }

public void setFonts(List<String> fonts) {
        this.fonts = fonts;
      }

}

Java使用IText(VM模版)导出PDF,IText导出word(二)的更多相关文章

  1. Java使用IText(VM模版)导出PDF

    Java使用IText(VM模版)导出PDF: public String createPDF(ProjectManageBase projectManageBase) { Map map = new ...

  2. 《java核心技术:卷1》PDF版 和 Word版下载

    链接:https://pan.baidu.com/s/1OcpdZ4wfeo55xeJQQBHXRg 提取码:hds0

  3. iText导出PDF(图片,水印,页眉,页脚)

    项目需要导出PDF,导出的内容包含图片和文本,而且图片的数量不确定,在网上百度发现大家都在用iText,在官网发现可以把html转换为PDF,但是需要收费,那就只能自己写了. 在开始之前先在网上百度了 ...

  4. React项目实现导出PDF的功能

    在做web项目中,有时候会遇到pdf导出的需求,现根据之前在公司的React项目中遇到的导出PDF需求,整理一个demo出来. 导出PDF需要用到两个依赖包:html2canvas.jspdf 1.安 ...

  5. java利用itext导出pdf

    项目中有一功能是导出历史记录,可以导出pdf和excel,这里先说导出pdf.在网上查可以用那些方式导出pdf,用itext比较多广泛. 导出pdf可以使用两种方式,一是可以根据已有的pdf模板,进行 ...

  6. java动态导出PDF(利用itext)

    项目基于ssm框架,使用itext动态导出pdf文件: 1.引入两个jar包:itextpdf-5.5.5.jar.itext-asian-5.2.0.jar 说明: 1.itextpdf-5.5.5 ...

  7. Java利用IText导出PDF(更新)

    我很久以前写的还是上大学的时候写的:https://www.cnblogs.com/LUA123/p/5108007.html ,今天心血来潮决定更新一波. 看了下官网(https://itextpd ...

  8. java根据模板导出PDF(利用itext)

    一.制作模板     1.下载Adobe Acrobat 9 Pro软件(pdf编辑器),制作模板必须使用该工具. 2.下载itextpdf-5.5.5.jar.itext-asian-5.2.0.j ...

  9. flying-saucer + iText + Freemarker实现pdf的导出, 支持中文、css以及图片

    前言 项目中有个需求,需要将合同内容导出成pdf.上网查阅到了 iText , iText 是一个生成PDF文档的开源Java库,能够动态的从XML或者数据库生成PDF,同时还可以对文档进行加密,权限 ...

随机推荐

  1. Dubbo服务的搭建

    dubbo框架主要作用是基于RPC的远程调用服务管理,但是注册中心是用的zookeeper,搭建dubbo,首先要安装zookeeper,配置zookeeper... 实现功能如图所示:(存在2个系统 ...

  2. java在线聊天项目0.3版本 制作客户端窗体,实现发送按钮和回车发送信息功能,使用ActionListener监听事件中actionPerformed方法(用内部类和匿名内部类两种方法)

    方法一,使用匿名内部类的监听方法,因方法一致代码稍冗余 package com.swift; import java.awt.BorderLayout; import java.awt.Color; ...

  3. Spring框架针对dao层的jdbcTemplate操作crud之query查询数据操作

    查询目标是完成3个功能: (1)查询表,返回某一个值.例如查询表中记录的条数,返回一个int类型数据 (2)查询表,返回结果为某一个对象. (3)查询表,返回结果为某一个泛型的list集合. 一.查询 ...

  4. iOS利用UIDocumentInteractionController和Quick Look打开或预览文档

    在App的开发过程中,我们避免不了要打开软件中的文件,例如:Excel文件,Word文件,图片文件等不同格式的文件或者想要通过第三方的App来打开这些文件,那么我们就要用到UIDocumentInte ...

  5. CF-1082(渣渣只做了前三个)

    链接:http://codeforces.com/contest/1082 A. Vasya and Book 题意: n,x,y,d 一本电子书有n页,每一次翻动只能往前或者往后翻d页.求x-> ...

  6. TUN/TAP/VETH

    TUN/TAP虚拟网络设备为用户空间程序提供了网络数据包的发送和接收能力.他既可以当做点对点设备(TUN),也可以当做以太网设备(TAP). TUN/TAP虚拟网络设备的原理: 在Linux内核中添加 ...

  7. 四:SQL语句介绍

    前言:介绍SQL语句及其大致的分类 一:SQL语句介绍(Structured SQL Lanage) 结构化的查询语言 是一种特殊的编程语言 是一种数据库查询和程序设计语言 用于存取数据及查询.更新和 ...

  8. JS原生增删,判断class是否存在方法

    function hasClass(obj, cls) { if (obj.className) { return obj.className.match(new RegExp('(\\s|^)' + ...

  9. bash初识,特性,用法/网站

    目录 一.Bash初识 Bash Shell介绍 Bash Shell的作用 Bash 两种方式 命令提示符 二.Shell的基本语法 三.Shell的基本特性 1.命令补全 tab 2. Linux ...

  10. subprocess模块windows系统命令和linux系统命令

    windows系统 查看所有进程 tasklist 查找指定进程 tasklist | findstr pycharm 程序名称 PID(大写) 数量 大小 python exe 2640 conso ...