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

public String createPDF(ProjectManageBase projectManageBase) {

Map map = new HashMap();// velocity模板中的变量

try {

//模版vm的路径

String tmPath = ServletActionContext.getServletContext()

.getRealPath(“/pdf/vm”);

String pdfPath = ServletActionContext.getServletContext()

.getRealPath(“/pdf”);//用于生成pdf,存放pdf的路径

String facePath = pdfPath + "/test.vm.pdf";// 生成的pdf

//查询数据库的数据

ProjectManageBase projectBase = (ProjectManageBase) commonDao.findByHql("from ProjectManageBase”).get(0);

map.put("projectBase", projectBase);

Projectjfys jfys = new Projectjfys();

jfys.setLiuShuiHao(projectBase.getLiushuihao());

List<Projectjfys> jfyses =

this.commonDao.findByHql("from Projectjfys”)

map.put("jfys", jfyses);// 查询经费

// 生成pdf

pdfHandler.createByVelocity(tmPath, PdfConstant.KEPU_FACE,

facePath, map);

} catch (Exception e) {

e.printStackTrace();

}

/**

* 把一个map转为json字符串,map内对象可以是字符串也可以一个个bean

* @param m 一个map

* @return

*/

public String changeMapToStr(Map m){

if(m.equals(null)||null == m){

return null;

}else{

JSONArray json = JSONArray.fromObject(m);

return json.toString();

}

}

}

package com.gz.tools.pdf.util;

import com.gz.tools.pdf.CN_font.FontChinese;

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.PdfImportedPage;

import com.lowagie.text.pdf.PdfReader;

import com.lowagie.text.pdf.PdfWriter;

import java.io.File;

import java.io.FileOutputStream;

import java.io.OutputStream;

import java.net.URI;

import java.net.URL;

import java.util.List;

import org.xhtmlrenderer.pdf.ITextFontResolver;

import org.xhtmlrenderer.pdf.ITextRenderer;

public class PDFUtil

{

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);

}

}

public static Font toChieseFont(Font font)

{

Font newFont = null;

if (font == null) {

newFont = FontChinese.FONT;

} else {

newFont = new Font(FontChinese.BSAE_FONT, font.getSize(), font.getStyle(), font.getColor());

if (font.getFamilyname() != null) {

newFont.setFamily(font.getFamilyname());

}

}

return newFont;

}

public void HTML2OPDF(String htmlPath, String pdfPath, List<String> fontPaths)

throws Exception

{

String url = new File(htmlPath).toURI().toURL().toString();

OutputStream os = new FileOutputStream(pdfPath);

ITextRenderer renderer = new ITextRenderer();

ITextFontResolver fontResolver = renderer.getFontResolver();

if ((fontPaths != null) && (!fontPaths.isEmpty())) {

URL classPath = getClass().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);

renderer.layout();

renderer.createPDF(os);

System.gc();

os.close();

System.gc();

}

}

package com.gz.tools.velocity;

 

import java.io.PrintWriter;

import java.util.Map;

import java.util.Set;

import org.apache.velocity.Template;

import org.apache.velocity.VelocityContext;

import org.apache.velocity.app.VelocityEngine;

 

public class VelocityUtil

{

  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);

 

      Template template = engine.getTemplate(templateFileName, "UTF-8");

 

      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");

 

      template.merge(context, writer);

 

      writer.flush();

 

      writer.close();

 

      return true;

    } catch (Exception e) {

      e.printStackTrace();

    }return false;

  }

}

 

 

 

 

 

package com.gz.tools.pdf.CN_font;

 

import com.lowagie.text.DocumentException;

import com.lowagie.text.Font;

import com.lowagie.text.pdf.BaseFont;

import java.io.IOException;

 

public class FontChinese

{

  public static Font FONT = getChineseFont();

  public static BaseFont BSAE_FONT = getBaseFont();

 

  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;

  }

 

  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;

  }

}

 

 

 

 

 

VM模版(test.vm)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>

<head>

<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:90%;

height:25px;

}

li{

list-style:none;

}

.li_left li{

text-align:left;

line-height:50px;

font-size:14pt;

}

.li_left{

width:588px;

overflow:auto;

}

.fnt-21{

font-size:16pt;

}

table{

width:95%;

}

div_cls{

width:100%;

text-align:center;

}

</style>

</head>

<body style="font-family: songti;width:100%;text-align:center;">

<table cellpadding="0" cellspacing="0"  align="center" id="base" class="fnt-21">

<tr>

<td colspan="2" height="40">

</td>

</tr>

<tr>

<td width="30%" height="40" align="right" valign="top">

<span style="letter-spacing: 2px;">项目名称:</span>

</td>

<td width="70%" valign="top" align="left">

<p class="title">$projectBase.projectName</p>

</td>

</tr>

<tr>

<td colspan="2" height="40">

</td>

</tr>

<tr>

<td width="30%" height="40" align="right" valign="top">

<span style="letter-spacing: 2px;"> 项目类别:</span>

</td>

<td width="70%" valign="top" align="left">

<p class="title">$projectBase.typeFirst </p>

</td>

</tr>

<tr>

<td colspan="2" height="40">

</td>

</tr>

<tr>

<td width="30%" height="40" align="right" valign="top">

<span style="letter-spacing: 2px;">承担单位:</span>

</td>

<td width="70%" valign="top" align="left">

<p class="title">$projectOrg.danweimingcheng</p>

</td>

</tr>

<tr>

<td colspan="2" height="40">

</td>

</tr>

<tr>

<td width="30%" height="40" align="right" valign="top">

<span style="letter-spacing: 2px;">合作单位:</span>

</td>

<td width="70%" valign="top" align="left">

<p class="title">$projectOrg.hzdwmc1</p>

</td>

</tr>

<tr>

<td colspan="2" height="40">

</td>

</tr>

<tr>

<td width="30%" height="40" align="right" valign="top">

<span style="letter-spacing: 2px;"> 项目代号:</span>

</td>

<td width="70%" valign="top" align="left">

<p class="title">$projectBase.typeSecond</p>

</td>

</tr>

<tr>

<td colspan="2" height="40">

</td>

</tr>

<tr>

<td width="30%" height="40" align="right" valign="top">

<span style="letter-spacing: 2px;"> 申请日期:</span>

</td>

<td width="70%" valign="top" align="left">

<p class="title">$projectBase.isAcceptance</p>

</td>

</tr>

<tr>

<td colspan="2" height="20">

</td>

</tr>

</table>

<br/>

<div>

<table height="489" border="1" cellpadding="0" cellspacing="0">

<tr>

<td colspan="5" align="left"><br />

(一)总体经费预算表 </td>

</tr>

<tr>

<td width="57" height="44" align="center">序号</td>

<td width="157" align="center">开支科目</td>

<td width="170" align="center">区科普经费(元)</td>

<td width="136" align="center">配套资金(元) </td>

<td align="center">说明(必填) </td>

</tr>

#foreach($obj in $jfys)

#if($obj.ishj!=1)

<tr>

<td width="57" height="36" align="center">$obj.px</td>

<td width="157" align="center">$obj.kmkzname</td>

<td width="170" align="center">

#if($obj.qkpjf!=-1)

$obj.qkpjf

#{else}

&nbsp;

#end

</td>

<td width="136" align="center">

#if($obj.ptjf!=-1)

$obj.ptjf

#{else}

&nbsp;

#end

</td>

<td align="center">$obj.sm

</td>

</tr>

#{else}

<tr>

<td width="57" height="36" align="center">$obj.px</td>

<td width="157" align="center">$obj.kmkzname</td>

<td width="170" align="center">

#if($obj.hjqkpjf!=-1)

$obj.hjqkpjf

#{else}

&nbsp;

#end

</td>

<td width="136" align="center">

#if($obj.hjptjf!=-1)

$obj.hjptjf

#{else}

&nbsp;

#end

</td>

<td width="560" align="center"></td>

</tr>

#end

#end

<tr>

<td height="26" colspan="5" align="left"><p>(二)申报单位配套资金情况说明及其配套承诺 </p></td>

</tr>

<tr>

<td height="250" colspan="5" style="overflow:hidden;" align="left">

<div style="height:250px;width:95%;margin-left:10px;overflow:hidden;line-height:30px;word-break:break-all;">

$jfys[0].zjsm

</div>

<p style="right:150px;margin-top:-50px;position:absolute;"> (单位公章)<br/><br/> 年   月   日  </p><br/>

</td>

</tr>

<tr>

<td colspan="5" align="left"  height="26"><p>(三)申报单位的主管部门意见 </p></td>

</tr>

<tr>

<td height="130" colspan="5" style="overflow:hidden;text-align:left">

<div style="height:120px;width:95%;margin-left:10px;overflow:hidden;line-height:30px;word-break:break-all;">

$jfys[0].zbyj

</div>

<p style="right:150px;margin-top:-50px;position:absolute;"> (单位公章)<br/><br/> 年   月   日  </p><br/>

</td>

</tr>

</table>

</div>

<br/>

<p style="text-align:left;"><b class="fnt-21">八、项目组人员情况</b> </p>

<div class="div_cls">

<table border="1" cellspacing="0" cellpadding="0">

<tr>

<td width="100%" height="45" colspan="7" align="left">

(一)项目负责人 </td>

</tr>

<tr>

<td width="32" align="center">序号</td>

<td width="85" align="center">姓名</td>

<td width="156" align="center">工作单位</td>

<td width="68" align="center">职务/职称 </td>

<td width="87" align="center">从事专业</td>

<td width="97" align="center">任务分工</td>

<td width="84" align="center">签名</td>

</tr>

#foreach($obj in $projectZyqkfzr)

<tr>

<td width="32"><p align="center">$obj.px</p></td>

<td width="85"><p align="center">$obj.xm</p></td>

<td width="156"><p align="center">$obj.dw</p></td>

<td width="68"><p align="center">$obj.zw</p></td>

<td width="87"><p align="center">$obj.zy</p></td>

<td width="97"><p align="center">$obj.fg</p></td>

<td width="84"><p align="center">$obj.qm</p></td>

</tr>

#end

<tr>

<td width="100%" height="32" colspan="7" align="left">(二)项目主要成员</td>

</tr>

<tr>

<td width="32"  align="center">序号</td>

<td width="85" align="center">姓名</td>

<td width="156" align="center">工作单位</td>

<td width="68" align="center">职务/职称 </td>

<td width="87" align="center">从事专业</td>

<td width="97" align="center">任务分工</td>

<td width="84" align="center">签名</td>

</tr>

#foreach($obj in $projectZyqkzy)

<tr>

<td width="32"><p align="center">$obj.px</p></td>

<td width="85"><p align="center">$obj.xm</p></td>

<td width="156"><p align="center">$obj.dw</p></td>

<td width="68"><p align="center">$obj.zw</p></td>

<td width="87"><p align="center">$obj.zy</p></td>

<td width="97"><p align="center">$obj.fg</p></td>

<td width="84"><p align="center">$obj.qm</p></td>

</tr>

#end

</table>

</div>

</body>

</html>

 

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

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

    ===============action=========================== //退款导出word    public void exportWordTk() throws IOE ...

  2. JAVA使用itext根据模板生成PDF文档

    1.制作PDF模板 网址打开:https://www.pdfescape.com/open/ 我们这里先在线上把基础的内容用word文档做好,然后转成PDF模板,直接上传到网站上,这样方便点 假设我们 ...

  3. 【Java】itext根据模板生成pdf(包括图片和表格)

    1.导入需要的jar包:itext-asian-5.2.0.jar itextpdf-5.5.11.jar. 2.新建word文档,创建模板,将文件另存为pdf,并用Adobe Acrobat DC打 ...

  4. PDF模板报表导出(Java+Acrobat+itext)

    1. 首先要安装Adobe Acrobat,装好之后用Acrobat从一个word,excel或者pdf中转换一个pdf模板,我做的模板很简单,直接写一个简单的word再生成一个pdf表单,之后编辑文 ...

  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根据模板导出PDF(利用itext)

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

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

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

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

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

随机推荐

  1. Java长存!12个Java长久占居主要地位的原因

    Java长存!12个Java长久占居主要地位的原因 我们很容易就会遗忘那些曾经在猿群中大热而又被各种新技术掩盖直至堙灭的技术的价值.就拿COBOL这个老猿们当年所用的神器来说,就跟条死鱼一样被现代猿基 ...

  2. Es6里面的解析结构

    <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>& ...

  3. JavaScript-条件循环

    JavaScript-条件循环 条件判断语句 if 语句 - 只有当指定条件为 true 时,使用该语句来执行代码 if (表达式){    当条件为 true 时执行的代码} if...else 语 ...

  4. java_日期和时间

    1.System类中的currentTimeMillis:1970年1.1到现在的毫秒数 public class DateTest { public static void main(String[ ...

  5. dos command

    dos command md 创建目录 rd 删除目录 cd\ 返回到根目录 cd.. 返回到上一级目录 cd 进入指定目录 dir 列出当前目录下的文件夹及文件 echo 文件内容>文件名称. ...

  6. JSON parse error: Can not construct instance of model.Class: no suitable constructor found

    reference:http://blog.csdn.net/qq_33642117/article/details/51909346 当类中没有定义构造函数时,系统会指定给该类加上一个空参数的构造函 ...

  7. Python Socket详细介绍

    Socket 类型 套接字格式: socket(family,type[,protocal]) 使用给定的地址族.套接字类型.协议编号(默认为0)来创建套接字. socket类型 描述 socket. ...

  8. cmd启动MySQL服务器发生错误

    Mysql net start mysql启动,提示发生系统错误 5 拒绝访问  原文:https://blog.csdn.net/angel_guoo/article/details/7919037 ...

  9. java 图片合成文字或者awt包下的对话框引入自定义字体库

    成就卡图片字体问题:1.下载 xxx.ttf 文件2.mkdir /usr/local/jdk1.6.0_11/jre/lib/fonts/fallback.     在jre/lib/fonts 下 ...

  10. Redis主从配置与数据备份还原

    一.主从配置: 1.下载: wget http://download.redis.io/releases/redis-4.0.9.tar.gz tar xzf redis-4.0.9.tar.gz c ...