码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-05-31 07:57:43      阅读:809      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   java   tar   http   

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,布布扣,bubuko.com

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

标签:c   style   class   java   tar   http   

原文地址:http://www.cnblogs.com/qgc88/p/3761432.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!