导出table和chart数据到pdf文件

java+spring +mybatis+dojo项目中需要实现 将web 显示的table 数据和dojo chart 数据导入到pdf 文件,并支持pdf 下载 .

经过各种research,终于实现了,分享之.  

 

 

实现策略:

 

1.    如何写table 数据到pdf:

 

用itext 插件(从http://sourceforge.net/projects/itext/files/ 下载itextpdf-XX.jar包)

 

2.    如何写chart 到pdf:

 

1)    转换dojo chart 为svg 文件,以便传递到server 端

 

2)    svg 文件里面的数据可能不符合pdf 导入,需要替换

 

3)    传递到server 端,这一步,(由于下载文件必须用window.location 或是用window.open() , 而这是get 方式,参数上不能传递大量的数据,) ,用post 提交大参数数据传递到server ,server 端再将svg 内容put 到session ,用的时候再get from session

 

3.    如何下载pdf:

 

struts.xml 中要配置,action 用stream ,jsp 中用window.location

 

 

代码大致如下:

 

Struts.xml file

Xml代码 复制代码  收藏代码
  1. <package name="export" extends="json">  
  2.        <action name="exportPDF" class="xx.action.ExportPDFAction">  
  3.            <result name="success" type="stream">  
  4.                <param name="contentType">application/pdf; charset=gb2312</param>  
  5.                <param name="inputName">pdfStream</param>  
  6.                <param name="contentDisposition">attachment;filename="${documentNames}"</param>  
  7.                <param name="bufferSize">4096</param>  
  8.            </result>  
  9.        </action>  
  10. lt;/package>  
 <package name="export" extends="json">        <action name="exportPDF" class="xx.action.ExportPDFAction">            <result name="success" type="stream">                <param name="contentType">application/pdf; charset=gb2312</param>                <param name="inputName">pdfStream</param>                <param name="contentDisposition">attachment;filename="${documentNames}"</param>                <param name="bufferSize">4096</param>            </result>        </action></package>

 

 

server side - Action file

Java代码 复制代码  收藏代码
  1. package xx.action;   
  2. import com.itextpdf.text.*;   
  3. import com.itextpdf.text.pdf.*;   
  4. import org.apache.batik.transcoder.TranscoderInput;   
  5. import org.apache.batik.transcoder.print.PrintTranscoder;   
  6. …   
  7.   
  8. @ParentPackage("export")   
  9. ...   
  10.   
  11. public class ExportPDFAction extends ActionSupport {    
  12.     private InputStream pdfStream;   
  13.     private String documentNames;   
  14. …   
  15.   
  16.     public String saveSVGToSession(){   
  17.         ActionContext context = ActionContext.getContext();   
  18.         Map<String, Object> session = context.getSession();   
  19.            session.put("actionSVG",actionSVG);   
  20.         return SUCCESS;   
  21.     }   
  22.     public String exportPDF() {   
  23.         DateFormat format = new SimpleDateFormat("yyyy-MM-dd");   
  24.         Date currentDate = new Date();   
  25.         String pdfName=format.format(currentDate);   
  26.         documentNames="Metrics-"+pdfName+".pdf";   
  27.         Document document = new Document();   
  28.         try {   
  29.             ByteArrayOutputStream buffer = new ByteArrayOutputStream();   
  30.             PdfWriter writer=PdfWriter.getInstance(document, buffer);   
  31.             document.open();   
  32.             Paragraph p=new Paragraph("(Data Range: "+startDate+" to "+endDate+")");   
  33.             p.setAlignment(2);      //align right   
  34.             document.add(p);   
  35.             document.add(new Paragraph("Metrics:"));   
  36.   
  37.             PdfPTable table = new PdfPTable(2);   
  38.             table.setWidths(new int[]{ 22 });   
  39.             table.setWidthPercentage(100);   
  40.             PdfPCell cell;   
  41.             // row 1, cell 1   
  42.                
  43.             cell = new PdfPCell(new Phrase("Failure Count"));   
  44.             cell.setBackgroundColor(BaseColor.CYAN);   
  45.             cell.setVerticalAlignment(Element.ALIGN_CENTER);   
  46.             table.addCell(cell);   
  47.             // row 1, cell 2   
  48.             cell = new PdfPCell(new Phrase("Data Count"));   
  49.             cell.setBackgroundColor(BaseColor.CYAN);   
  50.             cell.setVerticalAlignment(Element.ALIGN_CENTER);   
  51.             table.addCell(cell);       
  52.             // row 2       
  53.             cell = new PdfPCell(new Phrase(Long.toString(failureCount)));   
  54.             cell.setVerticalAlignment(Element.ALIGN_CENTER);   
  55.             table.addCell(cell);   
  56. ...   
  57.   
  58.             document.add(table);   
  59.             document.add(new Paragraph("Chart: "));   
  60.             Map session = ActionContext.getContext().getSession();   
  61.             String content1=session.get("actionSVG").toString();   
  62.             InputStream inputStream = new ByteArrayInputStream(content1.getBytes());   
  63.             int width = 800;   
  64.             int height = 250;   
  65.             PdfContentByte cb = writer.getDirectContent();   
  66.             PdfTemplate template = cb.createTemplate(width, height);   
  67.             Graphics2D g2 = template.createGraphics(width,height);   
  68.             PrintTranscoder prm = new PrintTranscoder();   
  69.             TranscoderInput ti = new TranscoderInput(inputStream);   
  70.             prm.transcode(ti, null);   
  71.             PageFormat pg = new PageFormat();   
  72.             Paper pp= new Paper();   
  73.             pp.setSize(width, height);   
  74.             pp.setImageableArea(00, width, height);   
  75.             pg.setPaper(pp);   
  76.             prm.print(g2, pg, 0);   
  77.             g2.dispose();   
  78.             ImgTemplate img = new ImgTemplate(template);   
  79.             document.add(img);               
  80.   
  81.             document.close();   
  82.             this.pdfStream = new ByteArrayInputStream(buffer.toByteArray());   
  83.             buffer.close();   
  84.             return SUCCESS;   
  85.         } catch (DocumentException de) {   
  86.             System.err.println(de.getMessage());   
  87.             return ERROR;   
  88.         } catch (IOException ioe) {   
  89.             System.err.println(ioe.getMessage());   
  90.             return ERROR;   
  91.         }   
  92.     }      
  93.   
  94.     public InputStream getPdfStream() {   
  95.         return pdfStream;   
  96.     }   
  97.     public void setPdfStream(InputStream pdfStream) {   
  98.         this.pdfStream = pdfStream;   
  99.     }   
  100. …   
  101. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值