使用iText导出word和pdf(经典)

来源:互联网 发布:js数组前面添加元素 编辑:程序博客网 时间:2024/05/22 08:05

话不多说,直接上代码:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. package com.tgb.util;  
  2.   
  3. import java.awt.Color;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.IOException;  
  6. import java.io.OutputStream;  
  7. import java.util.List;  
  8.   
  9. import com.lowagie.text.Document;  
  10. import com.lowagie.text.DocumentException;  
  11. import com.lowagie.text.Element;  
  12. import com.lowagie.text.Font;  
  13. import com.lowagie.text.FontFactory;  
  14. import com.lowagie.text.Image;  
  15. import com.lowagie.text.PageSize;  
  16. import com.lowagie.text.Paragraph;  
  17. import com.lowagie.text.pdf.BaseFont;  
  18. import com.lowagie.text.pdf.PdfWriter;  
  19. import com.lowagie.text.rtf.RtfWriter2;  
  20. import com.tgb.entity.News;  
  21.   
  22. /** 
  23.  * IText操作类 
  24.  * @author shyh 
  25.  * 
  26.  */  
  27. public class ItextManager {  
  28.   
  29.     private Font font;  
  30.     private BaseFont bfChinese;  
  31.   
  32.     public ItextManager() throws Exception {  
  33.         // 设置中文字体  
  34.         bfChinese = BaseFont.createFont("STSong-Light""UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);  
  35.         font = new Font(bfChinese);  
  36.         font.setSize(15);  
  37.         font.setStyle(FontFactory.HELVETICA);  
  38. //      font.setStyle(Font.BOLD);//加粗  
  39.         font.setColor(new Color(0,0,0));  
  40.           
  41.     }  
  42.   
  43.     public static ItextManager getInstance() throws Exception {  
  44.         return new ItextManager();  
  45.     }  
  46.   
  47.     public void createRtfContext(List<News> newsList, List<String> imgList, OutputStream out,String type) {  
  48.         Document doc = new Document(PageSize.A4, 20202020);  
  49.         try {  
  50.             if("word".equals(type)){  
  51.                 RtfWriter2.getInstance(doc, out);  
  52.             }else if("pdf".equals(type)){  
  53.                 PdfWriter.getInstance(doc, out);  
  54.             }  
  55.             doc.open();  
  56.             News news = null;  
  57.             Paragraph title1 = null;  
  58.             for (int i = 0; i < newsList.size(); i++) {  
  59.                 news = newsList.get(i);  
  60.                 // 标题  
  61.                 Paragraph title = new Paragraph(news.getTitle(), font);  
  62.                 title.setAlignment(Element.ALIGN_LEFT);  
  63.                 doc.add(title);  
  64.   
  65.                 // 换行  
  66.                 title1 = new Paragraph("\n");  
  67.                 doc.add(title1);  
  68.   
  69.                 // 正文  
  70.                 Paragraph content = new Paragraph(news.getContent(), font);  
  71.                 content.setAlignment(Element.ALIGN_LEFT);  
  72.                 doc.add(content);  
  73.   
  74.                 // 换行  
  75.                 title1 = new Paragraph("\n");  
  76.                 doc.add(title1);  
  77.   
  78.                 // 站点  
  79.                 Paragraph site = new Paragraph(news.getSite(), font);  
  80.                 content.setAlignment(Element.ALIGN_LEFT);  
  81.                 doc.add(site);  
  82.   
  83.                 // 换行  
  84.                 title1 = new Paragraph("\n");  
  85.                 doc.add(title1);  
  86.   
  87.                 // 发布时间  
  88.                 Paragraph publishTime = new Paragraph(news.getPublishTime(), font);  
  89.                 content.setAlignment(Element.ALIGN_LEFT);  
  90.                 doc.add(publishTime);  
  91.   
  92.                 // 换行  
  93.                 title1 = new Paragraph("\n");  
  94.                 doc.add(title1);  
  95.   
  96.             }  
  97.   
  98.             Image img = null;  
  99.             for (int j = 0; j < imgList.size(); j++) {  
  100.                 // 图片  
  101.                 img = Image.getInstance(imgList.get(j));  
  102.                 float heigth = img.getHeight();  
  103.                 float width = img.getWidth();  
  104.                 int percent = getPercent2(heigth, width);  
  105.                 img.setAlignment(Image.MIDDLE);  
  106.                 img.scalePercent(percent + 3);// 表示是原来图像的比例;  
  107.                 doc.add(img);  
  108.             }  
  109.   
  110.             doc.close();  
  111.         } catch (FileNotFoundException e) {  
  112.             e.printStackTrace();  
  113.         } catch (DocumentException e) {  
  114.             e.printStackTrace();  
  115.         } catch (IOException e) {  
  116.             e.printStackTrace();  
  117.         }  
  118.     }  
  119.   
  120.     /** 
  121.      * 第一种解决方案 在不改变图片形状的同时,判断,如果h>w,则按h压缩,否则在w>h或w=h的情况下,按宽度压缩 
  122.      *  
  123.      * @param h 
  124.      * @param w 
  125.      * @return 
  126.      */  
  127.   
  128.     public static int getPercent(float h, float w) {  
  129.         int p = 0;  
  130.         float p2 = 0.0f;  
  131.         if (h > w) {  
  132.             p2 = 297 / h * 100;  
  133.         } else {  
  134.             p2 = 210 / w * 100;  
  135.         }  
  136.         p = Math.round(p2);  
  137.         return p;  
  138.     }  
  139.   
  140.     /** 
  141.      * 第二种解决方案,统一按照宽度压缩 这样来的效果是,所有图片的宽度是相等的,自我认为给客户的效果是最好的 
  142.      *  
  143.      * @param args 
  144.      */  
  145.     public static int getPercent2(float h, float w) {  
  146.         int p = 0;  
  147.         float p2 = 0.0f;  
  148.         p2 = 530 / w * 100;  
  149.         p = Math.round(p2);  
  150.         return p;  
  151.     }  
  152. }  

控制层(springmvc)

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. @RequestMapping(value="/exportword")  
  2. public String exportWord(HttpServletRequest request,HttpServletResponse response) throws Exception{  
  3.     String type = request.getParameter("type");  
  4.     response.setContentType("application/octet-stream; charset=UTF-8");    
  5.     if("word".equals(type)){  
  6.         response.setHeader("content-disposition""attachment;filename=" + new SimpleDateFormat("yyyyMMddHH:mm:ss").format(new Date()) + ".doc");  
  7.     }else if("pdf".equals(type)){  
  8.         response.setHeader("content-disposition""attachment;filename=" + new SimpleDateFormat("yyyyMMddHH:mm:ss").format(new Date()) + ".pdf");  
  9.     }  
  10.       
  11.     String svgCode = request.getParameter("svg");//highcharts图表svgCode  
  12.     String svg [] = svgCode.split("_");  
  13.     String path[] = new String[svg.length];  
  14.     OutputStream out = response.getOutputStream();  
  15.     ItextManager tm = ItextManager.getInstance();  
  16.     List<News> newsList = userService.getData();  
  17.     List<String> imageList = new ArrayList<String>();  
  18.       
  19.     if(svg!=null){  
  20.         for(int k=0;k<svg.length;k++){  
  21.             String picName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".png";  
  22.             path[k] = request.getSession().getServletContext().getRealPath("/upload/"+picName);  
  23.             imageList.add(path[k]);  
  24.             SvgPngConverter.convertToPng(svg[k], path[k]);  
  25.         }  
  26.     }  
  27.       
  28.     tm.createRtfContext(newsList,imageList,out,type);  
  29.       
  30.     out.flush();  
  31.     out.close();  
  32.     return null;  
  33. }  



业务层

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. @Override  
  2.     public List<News> getData() {  
  3.         List<News> newsList = new ArrayList<News>();  
  4.         News news1 = new News();  
  5.         news1.setTitle("标题:国泰君安*公司研究*广发证券:定增完成,如虎添翼*000776*投资银行业与经纪业行业*梁静");  
  6.         news1.setContent("正文:报告类型=公司事件点评公司简称=广发证券公司代码=000776报告日期=Thu Aug 25 09:05:29 CST 2011研究员 =梁静报告标题=定增完成,如虎添翼【报告摘要】8月25日,广发证券成功向揭阳市信宏资产、汇添富基金、上海海博鑫惠、兴业基金等10家机构定向增发4.526亿股、募集资金121.8亿元,募集资金净额120亿元。");  
  7.         news1.setSite("站点:新浪网");  
  8.         news1.setPublishTime("发布时间:2014-05-12");  
  9.           
  10.         News news2 = new News();  
  11.         news2.setTitle("标题:[申万销售夏敬慧] 基金仓位周报----开基仓位下降1.51%");  
  12.         news2.setContent("正文:理财产品部分析师: 杨鹏(18930809297) 开基仓位有所下降:本周,开放式基金平均仓位继续下降。");  
  13.         news2.setSite("站点:腾讯网");  
  14.         news2.setPublishTime("发布时间:2014-05-25");  
  15.           
  16.         newsList.add(news1);  
  17.         newsList.add(news2);  
  18.           
  19.         return newsList;  
  20.     }  

显示层

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5. <title>导出word</title>  
  6. <script type="text/javascript" src="js/jquery/jquery-1.7.1.js"></script>  
  7. <script src="js/highcharts/4.0.1/js/highcharts.js"></script>  
  8. <script src="js/highcharts/4.0.1/js/modules/exporting.js"></script>  
  9. <script type="text/javascript">  
  10.     $(function() {  
  11.         Highcharts.wrap(Highcharts.Chart.prototype, 'getSVG', function (proceed) {  
  12.             return proceed.call(this)  
  13.                 .replace(  
  14.                     /(fill|stroke)="rgba([09]+,[09]+,[09]+),([09\.]+)"/g,   
  15.                     '$1="rgb($2)" $1-opacity="$3"'  
  16.                 );  
  17.         });  
  18.           
  19.         $('#container').highcharts({  
  20.             title : {  
  21.                 text : 'Monthly Average Temperature',  
  22.                 x : -20  
  23.             //center  
  24.             },  
  25.             subtitle : {  
  26.                 text : 'Source: WorldClimate.com',  
  27.                 x : -20  
  28.             },  
  29.             xAxis : {  
  30.                 categories : [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]  
  31.             },  
  32.             yAxis : {  
  33.                 title : {  
  34.                     text : 'Temperature (°C)'  
  35.                 },  
  36.                 plotLines : [ {  
  37.                     value : 0,  
  38.                     width : 1,  
  39.                     color : '#808080'  
  40.                 } ]  
  41.             },  
  42.             tooltip : {  
  43.                 valueSuffix : '°C'  
  44.             },  
  45.             legend : {  
  46.                 layout : 'vertical',  
  47.                 align : 'right',  
  48.                 verticalAlign : 'middle',  
  49.                 borderWidth : 0  
  50.             },  
  51.             series : [ {  
  52.                 name : 'Tokyo',  
  53.                 data : [ 7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6 ]  
  54.             }, {  
  55.                 name : 'New York',  
  56.                 data : [ -0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5 ]  
  57.             }, {  
  58.                 name : 'Berlin',  
  59.                 data : [ -0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0 ]  
  60.             }, {  
  61.                 name : 'London',  
  62.                 data : [ 3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8 ]  
  63.             } ]  
  64.         });  
  65.   
  66.         $('#container_pie').highcharts({  
  67.             chart : {  
  68.                 plotBackgroundColor : null,  
  69.                 plotBorderWidth : null,  
  70.                 plotShadow : false  
  71.             },  
  72.             title : {  
  73.                 text : 'Browser market shares at a specific website, 2010'  
  74.             },  
  75.             tooltip : {  
  76.                 pointFormat : '{series.name}: <b>{point.percentage:.1f}%</b>'  
  77.             },  
  78.             plotOptions : {  
  79.                 pie : {  
  80.                     allowPointSelect : true,  
  81.                     cursor : 'pointer',  
  82.                     dataLabels : {  
  83.                         enabled : true,  
  84.                         color : '#000000',  
  85.                         connectorColor : '#000000',  
  86.                         format : '<b>{point.name}</b>: {point.percentage:.1f} %'  
  87.                     }  
  88.                 }  
  89.             },  
  90.             series : [ {  
  91.                 type : 'pie',  
  92.                 name : 'Browser share',  
  93.                 data : [ [ 'Firefox', 45.0 ], [ 'IE', 26.8 ], {  
  94.                     name : 'Chrome',  
  95.                     y : 12.8,  
  96.                     sliced : true,  
  97.                     selected : true  
  98.                 }, [ 'Safari', 8.5 ], [ 'Opera', 6.2 ], [ 'Others', 0.7 ] ]  
  99.             } ]  
  100.         });  
  101.   
  102.         $("#btn_word").on("click", function() {  
  103.             var chart_line = $("#container").highcharts();  
  104.             var chart_pie = $("#container_pie").highcharts();  
  105.             var svg_line = chart_line.getSVG();  
  106.             var svg_pie = chart_pie.getSVG();  
  107.             var svg = svg_line+"_"+svg_pie;  
  108.             $("#svg").val(svg);  
  109.             $("#form1").prop("action", "exportword.do?type=word").submit();  
  110.         });  
  111.   
  112.         $("#btn_pdf").on("click", function() {  
  113.             var chart_line = $("#container").highcharts();  
  114.             var chart_pie = $("#container_pie").highcharts();  
  115.             var svg_line = chart_line.getSVG();  
  116.             var svg_pie = chart_pie.getSVG();  
  117.             var svg = svg_line + "_" + svg_pie;  
  118.             $("#svg").val(svg);  
  119.             $("#form1").prop("action", "exportword.do?type=pdf").submit();  
  120.         });  
  121.     });  
  122. </script>  
  123. </head>  
  124. <body>  
  125.     <form id="form1" action="exportword.do" method="post">  
  126.         <div>  
  127.             <input type="hidden" name="svg" id="svg" />   
  128.             <input id="btn_word" type="button" value="导出word" />   
  129.             <input id="btn_pdf" type="button" value="导出pdf" />  
  130.         </div>  
  131.     </form>  
  132.   
  133.     <div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>  
  134.     <div id="container_pie" style="min-width: 310px; height: 400px; margin: 0 auto"></div>  
  135. </body>  
  136. </html>  


效果:




导出word:


导出Pdf:


0 0
原创粉丝点击