把html导出为excel或者word文档
[b]1.jsp页面简单导出[/b]
导出为excel:

<% response.setContentType("application/vnd.ms-excel;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Disposition","attachment;filename=test.xls");  //这里的filename  如果是中文的话,需要先把中文转成utf8编码%>

导出为word:

<% response.setContentType("application/msword;charset=UTF-8"); response.setHeader("Content-Disposition","attachment;filename=test.doc");    %>

[b]2.pdf 导出[/b]

步骤1: 写出html模板 muban.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=GBK" /><title>无标题文档</title><style type="text/css">div *{font-size:10px;}</style></head>

<body style="width:900px; margin:auto ;padding-top:15px;"><table cellspacing="0" border="1" cellpadding="0" width="80%">  <tr>        <td width="45%">         <p id="post">#邮政编码</p>         <p id="addr">#地址</p>            <p id="addr2">#具体地址(几号楼几单元几室)</p>            <p userName="userName">#userName      亲启</p>        </td>        <td >          <img src="ad.jpg" />        </td>    </tr></table>

<h3 style="padding-left:280px;">债权转让及受让协议</h3><div><p userName="userName">尊敬的   #userName   先生 ,您好!</p><p id="date">通过宜信公司信用评估与筛选,推荐您  #date  通过受让他人既有的个人间借贷合同的方式,出借资金给如下借款人,</p><p>详见《债权列表》,在您接受该批债权转让并按时支付对价的情况下,预期您的出借获益情况如下: 货币单位:人民币(元)</p>

<table cellspacing="0" border="1" cellpadding="0" > <tr id="lenderAcountInfo">       <th style='width:100px;align:center;'>出借编号</th>        <th style='width:100px;align:center;'>资金出借及<br/>回收方式</th>        <th style='width:100px;align:center;'>初始出借日期</th>        <th style='width:100px;align:center;'>初始出借金额</th>        <th style='width:100px;align:center;'>下一个报告日</th>        <th style='width:100px;align:center;'>下一个报告期借款人<br/>应还款额</th>        <th style='width:100px;align:center;'>账户管理费</th>        <th style='width:100px;align:center;'>预计下一个报告日您的<br/>资产总额</th>    </tr></table>

</div></body></html>

步骤2: 写出 Pdf 类,这个类用于生成你想要的pdf文件,包括往模板内填充数据,以及导出!

import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.OutputStream;

import org.jsoup.Jsoup;import org.jsoup.nodes.Document;import org.jsoup.nodes.Element;import org.jsoup.select.Elements;import org.xhtmlrenderer.pdf.ITextRenderer;

public class Pdf {    private Document document;    private String fileTemplete;

    public Pdf() {        super();  }

/** * 通过构造方法获取pdf类的基本模板样式 * @param fileTemplete * @throws Exception */ public Pdf(String fileTemplete) throws Exception {        super();      //初始化document     document = this.getHTMLTemplete(fileTemplete);   }

 public void createPdf() throws Exception {        String outputFile = "test.pdf";        OutputStream os = new FileOutputStream(outputFile);      ITextRenderer renderer = new ITextRenderer();

      //得到最终html对象      String html = document.html();       //设置pdf内容     renderer.setDocumentFromString(html);     // 解决图片的相对路径问题        renderer.getSharedContext().setBaseURL("file:/E:/");        //设置pdf样式     renderer.layout();        //最终生成pdf     renderer.createPDF(os);

     os.close();       System.out.println("生成成功!");

   }

 /**    * 获取模板    * @param templeteName    * @return    * @throws Exception  */   public  Document getHTMLTemplete(String templeteName) throws Exception {      String path = Test.class.getResource("/").getPath();       File file = new File(path + templeteName);      Document document = Jsoup.parse(file, "GBK");      return document;  }

   /**    * 设置用户名   * @param userName    */   public void setUserName(String userName) {        Elements es = document.getElementsByAttribute("userName");     for(Element e:es){            String s=e.html();           String[] text=s.split("#userName");            if(text.length==2){             s=text[0]+userName+text[1];            }else if(text.length==1)                s=userName+text[0];         e.html(s);

      } }

 /**    * 设置邮编    * @param post    */   public void setPost(String post) {        Element e = document.getElementById("post");       e.html(post); } /**    * 设置地址    * @param addr    */   public void setAddr( String addr) {       Element e = document.getElementById("addr");       e.html(addr); } /**    * 设置详细地址  * @param addr2   */   public void setAddr2( String addr2) {     Element e = document.getElementById("addr2");      e.html(addr2);    } /**    * 设置日期    * @param date    */   public void setDate( String date) {       Element e = document.getElementById("date");       String s=e.html();       String[] text=s.split("#date");        if(text.length==2){         s=text[0]+date+text[1];        }else if(text.length==1)            s=date+text[0];     e.html(s);    } /**    * 设置出借人账户收益信息     * @param info    */   public void setLenderAccountInfo(String info){        Element e = document.getElementById("lenderAcountInfo");       e.after(info);    }

   public Document getDocument() {       return document;  }

 public void setDocument(Document document) {      this.document = document;    }

 public String getFileTemplete() {     return fileTemplete;  }

 public void setFileTemplete(String fileTemplete) {        this.fileTemplete = fileTemplete;    }}

步骤3:测试类PdfTest

import junit.framework.TestCase;

public class PdfTest extends TestCase {

    @Override    protected void setUp() throws Exception {     super.setUp();    }

   @Override    protected void tearDown() throws Exception {      super.tearDown(); }

   public void testPdf() throws Exception{

     Pdf pdf=new Pdf("/muban.html"); //使用哪个模板       //以下部分为往模板内填数据        pdf.setPost("100000");      pdf.setUserName("张伟");//填用户名        pdf.setAddr("北京市朝阳区红领巾南路朝阳园");//设置地址        pdf.setAddr2("9号楼1单元801室");//设置具体地址     pdf.setDate("2010-08-10");//设置日期参数      String info="<tr>" +                "<td>8808010100029781-005</td>" +              "<td >宜信宝</td>" +              "<td>宜信宝2010-08-12</td>" +             "<td>1,200,000.00</td>" +              "<td>2010-08-30</td>" +                "<td>64,368.82</td>" +             "<td>0.00</td>" +              "<td>1,207,499.14</td>" +              "</tr>";      pdf.setLenderAccountInfo(info);       //生成pdf       pdf.createPdf();

    }}

最后,jar包,放出供各位下载!

[b]3.由于最近的项目只有导出word功能,没有导出pdf功能,而又不想再做导出pdf的工作,于是使用word直接转换成pdf的方式获得pdf文件[/b]
提供2种方案:

3.1 使用jacob.不过有使用前提,必须先把jar包中的dll文件放到jre/bin下.同时安装adobe acrobat7.0以上版本的软件.再配置下adobe的虚拟打印机,即可.之后运行java类,代码很简单,如下(拷贝自别人):

/** *//*** * @version 1.00, 2007-4-9*  */import java.io.File;import com.jacob.activeX.ActiveXComponent;import com.jacob.com.ComThread;import com.jacob.com.Dispatch;import com.jacob.com.Variant;/* * 注意word转pdf要安装虚拟打印机,且要配置 * 使用jacob框架,把dll文件放到jre/bin目录下 */public class WordToPdf {    private ActiveXComponent wordCom = null; 

    private Object wordDoc = null; 

    private final Variant False = new Variant(false); 

    private final Variant True = new Variant(true); 

    /** 

      * 打开word文档 

      *   

      * @param filePath word文档

      * @return 返回word文档对象 

      */ 

    public boolean openWord(String filePath) { 

        //建立ActiveX部件 

        wordCom = new ActiveXComponent("Word.Application"); 

        try { 

            //返回wrdCom.Documents的Dispatch 

            Dispatch wrdDocs = wordCom.getProperty("Documents").toDispatch(); 

            //调用wrdCom.Documents.Open方法打开指定的word文档,返回wordDoc 

            wordDoc = Dispatch.invoke(wrdDocs, "Open", Dispatch.Method, 

                    new Object[] { filePath }, new int[1]).toDispatch(); 

            return true; 

        } catch (Exception ex) { 

            ex.printStackTrace(); 

        } 

        return false;

    } 

    /** 

      * 关闭word文档 

      */ 

    public void closeWord(boolean saveOnExit) {

        if (wordCom!=null) {

            //关闭word文件

            //Dispatch.call(wordDoc, "Close", new Variant(saveOnExit));

            wordCom.invoke("Quit",new Variant[]{});

            //wordCom.invoke("Quit",new Variant[0]);

            wordCom=null;

            //释放在程序线程中引用的其它com,比如Adobe PDFDistiller

            ComThread.Release();

        }

    } 

    /** 

      * 将word文档打印为PS文件后,使用Distiller将PS文件转换为PDF文件

      *   

      * @param   sourceFilePath 

      *          源文件路径

      * @param   destinPSFilePath 

      *          首先生成的PS文件路径

      * @param   destinPDFFilePath 

      *          生成PDF文件路径 

      */ 

    public void docToPDF(String sourceFilePath, String destinPSFilePath, 

                    String destinPDFFilePath) { 

        if (!openWord(sourceFilePath)) { 

            closeWord(true); 

            return; 

        } 

        //建立Adobe Distiller的com对象 

        ActiveXComponent distiller = new ActiveXComponent("PDFDistiller.PDFDistiller.1");

        try { 

            //设置当前使用的打印机,我的Adobe Distiller打印机名字为 "Adobe PDF" 

            wordCom.setProperty("ActivePrinter", new Variant("Adobe PDF"));

            //设置printout的参数,将word文档打印为postscript文档。现在只使用了前5个参数,假如要使用更多的话可以参考MSDN的office开发相关api 

            //是否在后台运行 

            Variant Background = False; 

            //是否追加打印 

            Variant Append = False; 

            //打印所有文档 

            int wdPrintAllDocument = 0; 

            Variant Range = new Variant(wdPrintAllDocument); 

            //输出的postscript文件的路径 

            Variant OutputFileName = new Variant(destinPSFilePath); 

            Dispatch.callN((Dispatch) wordDoc, "PrintOut", new Variant[] { 

                            Background, Append, Range, OutputFileName }); 

            System.out.println("由word文档打印为ps文档成功!"); 

            //调用Distiller对象的FileToPDF方法所用的参数,具体内容参考Distiller Api手册 

            //作为输入的ps文档路径 

            Variant inputPostScriptFilePath = new Variant(destinPSFilePath); 

            //作为输出的pdf文档的路径 

            Variant outputPDFFilePath = new Variant(destinPDFFilePath); 

            //定义FileToPDF方法要使用adobe pdf设置文件的路径,在这里没有赋值表示并不使用pdf配置文件 

            Variant PDFOption = new Variant(""); 

            //调用FileToPDF方法将ps文档转换为pdf文档 

            Dispatch.callN(distiller, "FileToPDF", new Variant[] { 

                            inputPostScriptFilePath, outputPDFFilePath, PDFOption }); 

            System.out.println("由ps文档转换为pdf文档成功!"); 

        } catch (Exception ex) { 

            ex.printStackTrace(); 

        } finally { 

            closeWord(true); 

        } 

    } 

    public static void main(String[] argv) { 

            WordToPdf d2p = new WordToPdf();            d2p.docToPDF("f:\\1043_王燕春_lender账单_2010-06-15_1.doc", "f:\\1043_王燕春_lender账单_2010-06-15_1.ps", "f:\\1043_王燕春_lender账单_2010-06-15_1.pdf");//            boolean   success   =   (new   File("D:\\test.ps")).delete();//            if(success){//                System.out.println("删除打印机文件成功");//            }

    } }

3.2 但是由于公司服务器在linux上跑,jacob不适用,于是使用openOffice+jodconverter,实现很不错哦!不想再写字了,直接上工程吧,呵呵!
有些前提限制,原版说明如下:

JODConverter needs to connect to a running OpenOffice.org instance in order to perform the document conversions. 

This is different from starting the OpenOffice.org program as you would normally do. OpenOffice.org can be configured to run as a service and listen for commands on a TCP port; there are a few ways to accomplish this but the simplest one is to start it from the command line with the following options: 

  soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard 

附件中有的下载!提供io流的方式转换pdf!自创!

导出各种类型的文件的简单方法(暂时)相关推荐

  1. php 怎么查看文件类型信息,php获取文件类型和文件信息的方法

    php获取文件类型和文件信息的方法 发布于 2015-10-07 05:26:52 | 81 次阅读 | 评论: 0 | 来源: 网友投递 PHP开源脚本语言PHP(外文名: Hypertext Pr ...

  2. php 当前页面下载文件,php实现当前页面点击下载文件的简单方法

    php实现当前页面点击下载文件的简单方法 发布于 2017-08-02 17:44:21 | 80 次阅读 | 评论: 0 | 来源: 网友投递 PHP开源脚本语言PHP(外文名: Hypertext ...

  3. php 网页内容下载,php实现当前页面点击下载文件的简单方法

    php控制器中代码 public function downFile($path = ''){ if(!$path) header("Location: /"); download ...

  4. php通用下载方法,php实现当前页面点击下载文件的简单方法

    php控制器中代码 public function downFile($path = ''){ if(!$path) header("Location: /"); download ...

  5. php下载当前页面,php实现当前页面点击下载文件的简单方法

    php控制器中代码 public function downFile($path = ){ if(!$path) header(Location: /); download($path); } dow ...

  6. c语言合并jpg成pdf,JPG在线转换成PDF文件的简单方法

    在现在的工作性质中.大家不管是在工作中还是在学习中,都会用到JPG图片文件,就连我们平时朋友聊天之间,也会传送很多图片文件,但是图片文件在聊天中很方便,但是在工作中传送图片就显得很不正式了,领导都会要 ...

  7. php 实现点击下载,php实现当前页面点击下载文件的简单方法

    php控制器中代码 public function downFile($path = ''){ if(!$path) header("Location: /"); download ...

  8. JPG在线转换成PDF文件的简单方法

    在现在的工作性质中.大家不管是在工作中还是在学习中,都会用到JPG图片文件,就连我们平时朋友聊天之间,也会传送很多图片文件,但是图片文件在聊天中很方便,但是在工作中传送图片就显得很不正式了,领导都会要 ...

  9. Win7下如何用Eclipse导出jar类型的文件,并且可以用鼠标双击打开jar类型的文件的方法(解决双击后一闪而过)...

    近来在学Java,可是遇到一个问题,就是Java项目能不能像.exe文件一样,双击就能点击运行呢.后来老师讲到可以将其导出成为Jar文件,双击打开就可以了. 下面介绍一下,如何用Eclipse将Jav ...

最新文章

  1. layUI 实现自定义弹窗
  2. Spring Cloud Stream整合RabbitMQ
  3. Docker-创建一个mysql容器,并保存为本地镜像
  4. 基于JAVA+SpringBoot+Mybatis+MYSQL的在线心理测评管理系统
  5. C++数据结构与算法 动态规划
  6. 树莓派无法安装mariadb_RaspberryPi(树莓派)安装 MariaDB 数据库没有办法远程访问...
  7. feign传递多个对象_面向对象
  8. C++的string类
  9. 第一次作业 三班20
  10. 转:华为最新ARP防护
  11. 二级java考什么_​Java计算机二级考试考什么
  12. [19保研]中国科学院沈阳计算技术研究所教育中心2019年保研夏令营通知
  13. 小米笔记本电脑设置u盘启动的方法教程
  14. 淘宝【高佣卷】、【精品券】、【详情图片】
  15. 菜鸟运维笔记:小记编译安装Nginx所遇到的坑
  16. echarts 桑基图 添加标志线问题
  17. [日推荐] 『KORJO母爱小空间』妈妈带宝宝出门再也不用愁啦!
  18. bootstrap中固定table的表头
  19. [DataAnalysis]多元线性回归深入浅出-案例+模型假设+参数估计方法+模型评判方法+变量选择+多重共线性问题
  20. android8 小米5s,终于来了!小米5s、小米5s Plus将提前升级Android 8.0!

热门文章

  1. python极客学院爬虫_学习极客学院多线程爬虫课程的收获
  2. 一键重装正版Win系统
  3. 【学习笔记】笔记本电脑快速查看WiFi密码(Win11版本)
  4. 基于SSM+VUE的药品销售管理系统的设计与实现
  5. RNN和CNN(循环神经网络和卷积神经网络)
  6. Javascript中鼠标事件
  7. 项目1: 波士顿房价预测
  8. 用python输出一张九九乘法表_如何用python输出九九乘法表?有哪些方法?
  9. [美文]-- 男人和小姨子看到一辆豪华的进口轿车,小姨子竟然说……
  10. matlab代码仿真qpsk星座图,信号调制与解调,用脚本文件代码不是simulink