===============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. 面向对象编程OOP-2

    用ES6的方法 实现类的继承 //类的定义 class Animal { //ES6中新型构造器 constructor(name,age) { this.name = name; this.age= ...

  2. CPP-基础:strcpy之于C++(

    以下对strcpy函数错误的是? char atr1[]="string"; ]; char *str3; char *str4="sting"; A.strc ...

  3. python:json

    json是用来传输数据的字符串,{"key1":"values1","key2":{"key3":"value ...

  4. 查找闲置ip

    首先ping 一下该网段的广播地址,如ping 192.168.0.255 ,然后使用arp -a就可以查看到那些地址是被使用的,以及网卡的mac值.剩余的是暂时还未被使用的,当然没开机的机器就看不出 ...

  5. LeetCode(72) Edit Distance

    题目 Given two words word1 and word2, find the minimum number of steps required to convert word1 to wo ...

  6. Verilog学习笔记基本语法篇(四)·········块语句

    块语句是指将两条或者两条以上的语句组合在一起,使其在格式上更像一条语句.块语句分为两种: 1)用begin_end语句,通常用来标识顺序执行的语句,用它标识的块称作顺序块: 2)用fork_join语 ...

  7. .NET:权限管理

    题外话: 临近大四,编写各种简历的时候发现,很多电子简历上是可以链上自己在各大论坛上留下的足迹.关于这点,学习网络,拥抱开源,具有互联网思维的博主很后悔,后悔当年只会在网上查资料,不会留资料,空有才能 ...

  8. POJ 1849 树的直径 Two

    如果一个点开始遍历一棵树再回到原点那么每条边走两次. 现在是两个人从同一点出发,那么最后遍历完以后两人离得越远越好. 最后两人所处位置的路径上的边走了一次,其他边走了两次. 要使总路程最小,两人最后停 ...

  9. flask中的上下文_请求上下文和应用上下文

    前引 在了解flask上下文管理机制之前,先来一波必知必会的知识点. 面向对象双下方法 首先,先来聊一聊面向对象中的一些特殊的双下划线方法,比如__call__.__getattr__系列.__get ...

  10. 【06】GitHub WiKi

    [09]GitHub WiKi GitHub WiKi 能够帮助我们处理非结构化的页面集合,就像维基百科那样.我自己 NodeJS docs 就被我弄成 wiki 的样子. 几个页面,然后自定义侧边栏 ...