How to get particular html table contents to write it in pdf using itext

前端 未结 2 610
Happy的楠姐
Happy的楠姐 2020-12-07 06:23

I have used iText to export the table contents to pdf.

Here is my code:

JSP:

<%@ page language=\"java\" contentType=\"text/html; charset=I         


        
2条回答
  •  既然无缘
    2020-12-07 07:05

    Please take a look at the examples ParseHtmlTable1 and ParseHtmlTable2. They create the following PDFs: html_table_1.pdf and html_table_2.pdf.

    The table is created like this:

    StringBuilder sb = new StringBuilder();
    sb.append("");
    sb.append("");
    sb.append("");
    sb.append("");
    sb.append("");
    sb.append("");
    for (int i = 0; i < 10; ) {
        i++;
        sb.append("");
        sb.append("");
        sb.append("");
        sb.append("");
        sb.append("");
    }
    sb.append("
    Sr. No.Text DataNumber Data
    "); sb.append(i); sb.append("This is text data "); sb.append(i); sb.append(""); sb.append(i); sb.append("
    ");

    I've taken the liberty to define the CSS like this:

    tr { text-align: center; }
    th { background-color: lightgreen; padding: 3px; }
    td {background-color: lightblue;  padding: 3px; }
    

    In another answer, it was already mentioned that your design is flawed. You should learn how to create a decent architecture. Separating data (e.g. the table) and style (e.g. the colors) is one example where you can improve.

    Now we parse the CSS and the HTML like this:

    CSSResolver cssResolver = new StyleAttrCSSResolver();
    CssFile cssFile = XMLWorkerHelper.getCSS(new ByteArrayInputStream(CSS.getBytes()));
    cssResolver.addCss(cssFile);
    // HTML
    HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
    htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
    // Pipelines
    ElementList elements = new ElementList();
    ElementHandlerPipeline pdf = new ElementHandlerPipeline(elements, null);
    HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
    CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
    // XML Worker
    XMLWorker worker = new XMLWorker(css, true);
    XMLParser p = new XMLParser(worker);
    p.parse(new ByteArrayInputStream(sb.toString().getBytes()));
    

    Now the elements list contains a single element: your table:

    return (PdfPTable)elements.get(0);
    

    You can add this table to your PDF document. This is what the result looks like:

    enter image description here

提交回复
热议问题