Java使用IText(VM模版)导出PDF,IText导出word(二)
===============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"> 本组评审结果清单</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(二)的更多相关文章
- Java使用IText(VM模版)导出PDF
Java使用IText(VM模版)导出PDF: public String createPDF(ProjectManageBase projectManageBase) { Map map = new ...
- 《java核心技术:卷1》PDF版 和 Word版下载
链接:https://pan.baidu.com/s/1OcpdZ4wfeo55xeJQQBHXRg 提取码:hds0
- iText导出PDF(图片,水印,页眉,页脚)
项目需要导出PDF,导出的内容包含图片和文本,而且图片的数量不确定,在网上百度发现大家都在用iText,在官网发现可以把html转换为PDF,但是需要收费,那就只能自己写了. 在开始之前先在网上百度了 ...
- React项目实现导出PDF的功能
在做web项目中,有时候会遇到pdf导出的需求,现根据之前在公司的React项目中遇到的导出PDF需求,整理一个demo出来. 导出PDF需要用到两个依赖包:html2canvas.jspdf 1.安 ...
- java利用itext导出pdf
项目中有一功能是导出历史记录,可以导出pdf和excel,这里先说导出pdf.在网上查可以用那些方式导出pdf,用itext比较多广泛. 导出pdf可以使用两种方式,一是可以根据已有的pdf模板,进行 ...
- java动态导出PDF(利用itext)
项目基于ssm框架,使用itext动态导出pdf文件: 1.引入两个jar包:itextpdf-5.5.5.jar.itext-asian-5.2.0.jar 说明: 1.itextpdf-5.5.5 ...
- Java利用IText导出PDF(更新)
我很久以前写的还是上大学的时候写的:https://www.cnblogs.com/LUA123/p/5108007.html ,今天心血来潮决定更新一波. 看了下官网(https://itextpd ...
- java根据模板导出PDF(利用itext)
一.制作模板 1.下载Adobe Acrobat 9 Pro软件(pdf编辑器),制作模板必须使用该工具. 2.下载itextpdf-5.5.5.jar.itext-asian-5.2.0.j ...
- flying-saucer + iText + Freemarker实现pdf的导出, 支持中文、css以及图片
前言 项目中有个需求,需要将合同内容导出成pdf.上网查阅到了 iText , iText 是一个生成PDF文档的开源Java库,能够动态的从XML或者数据库生成PDF,同时还可以对文档进行加密,权限 ...
随机推荐
- HTTP协议重定向
HTTP重定向:服务器无法处理浏览器发送过来的请求(request),服务器告诉浏览器跳转到可以处理请求的url上.(浏览器会自动访问该URL地址,以至于用户无法分辨是否重定向了.) 重定向的返回码3 ...
- Noip2011提高组 聪明的质监员
题目传送门 讲真,既然质监员这么聪明,为什么要让我们帮他设计程序? 所以还是叫ZZ的质检员吧 其实,我最想说的,不是这个题,而是这个\(\Sigma\)(一见 \(\Sigma\) 就懵逼系列) 这个 ...
- 冒泡法排序参考(Java)
package com.swift; public class Maopao { //冒泡法 public static void main(String[] args) { int[] arr= { ...
- C\C++对于字符串输入处理
1.scanf scanf以%s格式符读入字符串,会以空格为结束,也就是无法将空格读入.如果换成%c就可以读入,但是无法一次性读入一整行字符. 2.fgets 显然,fgets是一个读取带空格字符串的 ...
- 【贪心】「poj1328」Radar Installation
建模:二维转一维:贪心 Description Assume the coasting is an infinite straight line. Land is in one side of coa ...
- MySQL-简要说明
分类 安装发展顺序分为: 网状型数据库 层次型数据库 关系型数据库 面向对象数据库 主流:关系型数据库 关系型数据库 事务transaction: 多个操作被当作一个整体对待 • ACID: ...
- Linux菜鸟起飞之路【二】Linux基本常识
一.Unix操作系统基本常识 1.什么是Unix? Unix是一个计算机操作系统,是一个用来协调.管理和控制计算机硬件与软件资源的控制程序. 2.Unix操作系统的特点? 多用户与多任务.多用户表示在 ...
- perl学习之:匹配修饰符/s /m
m 是将字符串作为多行处理,s是将字符串作为单行处理,如果是s在字符串中出现的\n就相当于普通字符. 6.6. Matching Within Multiple Lines6.6.1. Problem ...
- Linux三剑客之sed详解(2)
一.sed 分组替换(),\1 实例:I am a oldboy teacher. 吧oldboy 提取出来 二.特殊符号&代表被替换的字符串 实例:批量替换文件名 把stu_102999_1 ...
- mysql 审核引擎 goInception 的基本使用
官网地址 github.com 安装 git clone https://github.com/hanchuanchuan/goInception.git cd goInception 修改配置 开启 ...