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

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>

 

时间: 2024-10-06 12:06:30

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

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需要的一些路径        Strin

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

1.导入需要的jar包:itext-asian-5.2.0.jar itextpdf-5.5.11.jar. 2.新建word文档,创建模板,将文件另存为pdf,并用Adobe Acrobat DC打开编辑,点击右侧[准备表单]后点击[开始] 3.在需要插入数据的空白处,右击,点击[文本域],将文本域拖放到你想要的位置,更改域名称为你传入的变量名. 4.保存文件,将文件放到项目中.生成pdf代码如下: 1 public static void creatPdf(Map<String, Objec

java导出pdf文档

java导出pdf文档,多是iText实现的,可以创建pdf文档,并向文档写入内容. 1 导入包:itext-2.0.6.jar       itext必须使用的包. iTextAsian.jar      向pdf写入中文必须的包. 2 代码: package com.exp.pdf; import java.awt.Color; import java.io.FileOutputStream; import com.lowagie.text.Document; import com.lowa

利用iText 组件导出PDF

maven依赖:       <dependency>    <groupId>com.itextpdf</groupId>    <artifactId>itextpdf</artifactId>    <version>5.2.0</version>       </dependency> <!-- PDF输出中文的扩展包 -->       <dependency>    <

iText导出pdf、word、图片

一.前言 在企业的信息系统中,报表处理一直占比较重要的作用,本文将介绍一种生成PDF报表的Java组件--iText.通过在服务器端使用Jsp或JavaBean生成PDF报表,客户端采用超级连接显示或下载得到生成的报表,这样就很好的解决了B/S系统的报表处理问题. 二.iText简介 iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库.通过iText不仅可以生成PDF或rtf的文档,而且可以将XML.Html文件转化为PDF文件. iText的

利用iText导出pdf文件

一.导出pdf工具类:  package pdf; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import j

Java导出pdf文件数据

提示:导出pdf文件,需要3个jar包iText-2.1.5.jar,iTextAsian.jar,iText-rtf-2.1.4.jar. public boolean outputPdfJhsy(EntityBean data) { try { Global.getInstance().LogApp("导出pdf开始"); String pdfpath = File.get("LEAP/NSESTModule/WRModule/nsjhsyzm.pdf").ge

java 导出pdf

package hb.controller; import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import jav

java根据模板导出pdf

在网上看了一些Java生成pdf文件的,写的有点乱,有的不支持写入中文字体,有的不支持模板,有的只是随便把数据放里面生成文件,完全不考虑数据怎样放置的以及以后的维护性,想想还是自己总结一个完全版的导出pdf的工具类吧,总结一下网上的方法,加上自己的完善.具有以下特点: 综合特点: 一对一,点对点的给对应的地方写值,比如模板里面放了个name标识,在程序里把"张三"赋给name,那么输出的pdf里面name的地方就变成了张三,准确方便快捷 支持中文,可以使用自己下载的字体. 支持图片:图