`
fs_fly
  • 浏览: 26114 次
  • 性别: Icon_minigender_2
  • 来自: 杭州
社区版块
存档分类
最新评论

导出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.    如何写chartpdf:

 

1)    转换dojo chartsvg 文件,以便传递到server

 

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

 

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

 

3.    如何下载pdf:

 

struts.xml 中要配置,actionstreamjsp 中用window.location

 

 

代码大致如下:

 

Struts.xml file

 <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

package xx.action;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.print.PrintTranscoder;
…

@ParentPackage("export")
...

public class ExportPDFAction extends ActionSupport { 
    private InputStream pdfStream;
    private String documentNames;
…

    public String saveSVGToSession(){
        ActionContext context = ActionContext.getContext();
        Map<String, Object> session = context.getSession();
           session.put("actionSVG",actionSVG);
        return SUCCESS;
    }
    public String exportPDF() {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date currentDate = new Date();
        String pdfName=format.format(currentDate);
        documentNames="Metrics-"+pdfName+".pdf";
        Document document = new Document();
        try {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            PdfWriter writer=PdfWriter.getInstance(document, buffer);
            document.open();
            Paragraph p=new Paragraph("(Data Range: "+startDate+" to "+endDate+")");
            p.setAlignment(2);      //align right
            document.add(p);
            document.add(new Paragraph("Metrics:"));

            PdfPTable table = new PdfPTable(2);
            table.setWidths(new int[]{ 2, 2 });
            table.setWidthPercentage(100);
            PdfPCell cell;
            // row 1, cell 1
            
            cell = new PdfPCell(new Phrase("Failure Count"));
            cell.setBackgroundColor(BaseColor.CYAN);
            cell.setVerticalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            // row 1, cell 2
            cell = new PdfPCell(new Phrase("Data Count"));
            cell.setBackgroundColor(BaseColor.CYAN);
            cell.setVerticalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);    
            // row 2    
            cell = new PdfPCell(new Phrase(Long.toString(failureCount)));
            cell.setVerticalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
...

            document.add(table);
            document.add(new Paragraph("Chart: "));
            Map session = ActionContext.getContext().getSession();
            String content1=session.get("actionSVG").toString();
            InputStream inputStream = new ByteArrayInputStream(content1.getBytes());
            int width = 800;
            int height = 250;
            PdfContentByte cb = writer.getDirectContent();
            PdfTemplate template = cb.createTemplate(width, height);
            Graphics2D g2 = template.createGraphics(width,height);
            PrintTranscoder prm = new PrintTranscoder();
            TranscoderInput ti = new TranscoderInput(inputStream);
            prm.transcode(ti, null);
            PageFormat pg = new PageFormat();
            Paper pp= new Paper();
            pp.setSize(width, height);
            pp.setImageableArea(0, 0, width, height);
            pg.setPaper(pp);
            prm.print(g2, pg, 0);
            g2.dispose();
            ImgTemplate img = new ImgTemplate(template);
            document.add(img);            

            document.close();
            this.pdfStream = new ByteArrayInputStream(buffer.toByteArray());
            buffer.close();
            return SUCCESS;
        } catch (DocumentException de) {
            System.err.println(de.getMessage());
            return ERROR;
        } catch (IOException ioe) {
            System.err.println(ioe.getMessage());
            return ERROR;
        }
    }   

    public InputStream getPdfStream() {
        return pdfStream;
    }
    public void setPdfStream(InputStream pdfStream) {
        this.pdfStream = pdfStream;
    }
…
}

 

 

page side - js

function ExportToPDF() {
     var urlpath = "exportPDF!exportPDF?"   
                + "&failureCount=" + dojo.byId("failureCount").value
                + "&dataCount=" + dojo.byId("dataCount").value         
                + "&startDate=" + dojo.byId("startDate").value
                + "&endDate=" + dojo.byId("endDate").value; 

        var drawing = dijit.byId("FailStat")._chart.chartObj.surface;
        var svg1 = dojox.gfx.utils.toSvg(drawing);
        var SVGContent = svg1.results[0];
        SVGContent = SVGContent.replace(/text-anchor="left"/g, " ");       

        dojo.xhrPost({
            url:"exportPDF!saveSVGToSession",
            content:{"actionSVG": SVGContent },
            load:function (data, ioargs) {
                window.location = encodeURI(urlpath);    
            }
        });
    } 
 

 

 

 

  • 大小: 25.8 KB
分享到:
评论

相关推荐

    一个简单的ireport示例(含CHART)

    【标题】"一个简单的ireport示例(含CHART)" 涉及的主要知识点是使用iReport设计工具创建带有图表的报表。...对于初学者来说,这是一个很好的实践项目,能够提升对报表设计和数据可视化工具的掌握。

    javaweb组件2

    例如,创建一个Document对象,然后添加Paragraph、Table等元素,最后通过PdfWriter实例将内容写入PDF文件。PDFBox则是Apache的PDF处理库,提供低级别的PDF操作,如字节流解析和生成。 在实际应用中,这些组件通常...

    BIRT 中文 开发 流程

    随着报表复杂性和数据量的增加,性能优化变得至关重要。这可能涉及到优化SQL查询、减少不必要的数据处理、缓存策略以及调整报表引擎的配置。 总结,BIRT开发流程包括环境准备、项目创建、报表设计、数据绑定、样式...

    Microsoft.Office.11.0.Object.Library

    1. 数据导入导出:将数据库或其他数据源的数据导入到Excel表格,或者从Excel导出数据到其他系统。 2. 自动化报告生成:根据模板自动填充数据,生成定制化的报告。 3. 文档合并:处理多个文档,将其内容合并到一个...

    jasperReport详细教程及例子

    3. **填充数据**: 运行时,使用JasperFillManager将数据填充到.jasper文件中。 4. **导出报表**: 使用JasperExportManager将填充后的报表导出为PDF、HTML等格式。 ### 4. 示例应用 1. **数据库报表**: 从MySQL、...

    rdlc 报表Demo

    rdlc报表支持打印预览和导出功能,可将报表导出为PDF、Excel、CSV等多种格式。 **四、示例源码解析** 在提供的“报表Demo”中,你可以找到一个简单的rdlc报表应用示例,包括数据源的配置、报表控件的使用以及如何...

    Excel_VBA编程常用实例(150例).pdf

    4. 图表和数据透视表:Chart对象用于创建和修改图表,而PivotTable对象则用于操作数据透视表,便于数据分析。 5. 形状和控件:Shape对象允许你创建和编辑工作表中的图形元素,而Control对象则用于交互式的用户界面...

    jasperreport ireport开发java报表入门级教程(完整版).rar

    3. **表格(Table)**:展示多行多列数据,每个单元格可以绑定字段或表达式。 4. **图表(Chart)**:基于数据源生成图形,如柱状图、饼图、线图等。 5. **子报表(Subreport)**:在一个报表中嵌套另一个报表,用于...

    jfreeChart说明和jar包

    4. **绘制Chart**:将Chart渲染到Component上,如JPanel,或者导出为图像文件。 5. **添加到应用**:最后,将绘制好的图表组件添加到你的Java应用中,如Swing或JavaFX的应用。 JFreeChart的优点包括: - **易用性*...

    Preactor V17 UserGuide(2).pdf

    Preactor的配置文件包括命令文件(Command File)、菜单定义文件(Menu Definition File)和表格定义文件(Table Definition File)。这些文件都可以通过Preactor的配置编辑器进行编辑,并且软件提供了一套API(应用...

    SPSS tables

    2. **数据导入**:通过“File”-&gt;“Open”选择SPSS数据文件或外部数据源(如Excel、CSV等)导入到表格中。 3. **编辑表格**: - **添加行列**:点击工具栏上的“Add Row”或“Add Column”按钮,即可向表格中增加...

    Highcharts统计分析

    - **导出功能**:Highcharts支持将图表导出为图片或PDF,便于分享和打印。 5. **示例代码** 创建一个简单的折线图: ```javascript Highcharts.chart('container', { chart: { type: 'line' }, title: { ...

    jasperreportireport中文指南

    3. **表格(Table)**:展示多行多列的数据,每个单元格可以包含字段、表达式或子报表。 4. **图表(Chart)**:根据数据生成各种类型的图表,如柱状图、饼图、线图等。 5. **子报表(Subreport)**:嵌套在主报表...

    Jasper report用户手册Jasper report用户手册

    - **表格(Table)**:用于展示结构化的数据,支持行和列的操作。 - **图表(Chart)**:能够生成各种类型的图表,如柱状图、饼图、线图等,方便数据分析。 - **子报表(Subreport)**:在主报表内嵌入其他报表,...

    TransCAD菜单列表翻译[文].pdf

    TransCAD是一款强大的交通规划和数据分析软件,其菜单列表包含多个主要功能模块,便于用户进行数据操作、地图管理和分析。以下是对这些菜单项的详细解释: 1. **File**(文件):这是与文件操作相关的菜单,包括...

    RDLC报表总结

    4. 具有子报表的钻取报表:这个例子实现的功能类似Excel中的数据透视表(Pivot Table)的功能,在一个复杂的交叉表中可以进行时间和商品两个维度的向下钻取。 5. 引用外部代码块:此示例演示从另外一个类Util中读取...

    Excel imageMso自定义选项卡按钮图标汇总

    15. **PublishToPdfOrEdoc1**: 发布到PDF或电子文档,将工作簿导出为PDF或其他可打印格式。 16. **CreateFormBlankForm1, CreateFormWithMultipleItems1, AccessFormDatasheet1, AccessFormModalDialog1, ...

    jasperreport ant运行以及启动hsqldb服务

    - `PdfEncrypt`: 对PDF文件进行加密。 - `PrintService`: 直接打印输出。 - `Query`: 执行SQL查询。 - `Rotation`: 设置文本旋转角度。 - `Scriptlet`: 自定义报表逻辑,通过实现特定的方法如`beforeReportInit...

    phpword手册

    完成文档构建后,可以使用`save()`方法将其保存为不同的文件格式,如.docx、.odt、.pdf等。同时,PHPWord也支持直接输出为HTTP响应,方便在线预览或下载。 **8. 读取和解析Word文档** 除了生成文档,PHPWord还能...

Global site tag (gtag.js) - Google Analytics