【问题标题】:How to get particular html table contents to write it in pdf using itext如何获取特定的 html 表格内容以使用 itext 将其写入 pdf
【发布时间】:2014-08-23 05:29:13
【问题描述】:

我已经使用 iText 将表格内容导出为 pdf。

这是我的代码:

JSP:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Export to Excel - Demo</title>
<script src="scripts.js"></script>
<script language="javascript"> 
function exportToExcel()
{

    $("#datatoexport").val($("#customers").html()); 
    $('#myForm').submit();      
}
</script>
</head>
<body>
  <form id="myForm" action="Sample" method="post">
  <div id="customers">
    <table id="exportTableSelector" align="left" border="2">
        <thead>
            <tr bgcolor="lightgreen">
                <th>Sr. No.</th>
                <th>Text Data</th>
                <th>Number Data</th>
            </tr>
        </thead>
        <tbody>
            <%
                for (int i = 0; i < 10; i++) {
            %>
            <tr bgcolor="lightblue">
                <td align="center"><%=i + 1%></td>
                <td align="center">This is text data <%=i%></td>
                <td align="center"><%=i * i%></td>
            </tr>
            <%
                }
            %>
        </tbody>
    </table>
    </div>
    <br><br>
    <p>
    some text
    </p>

    <textarea name="datatoexport" id="datatoexport"></textarea>


    <a href="" onclick="exportToExcel();" target="_blank">Export to Excel</a>
   </form>
</body>
</html>

小服务程序:

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * Servlet implementation class Sample
 */
public class Sample extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Sample() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        System.out.println("Inside doGet");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        System.out.println("Inside doPost");

        try {
            // Get the text that will be added to the PDF
            String text = request.getParameter("datatoexport");


            if (text == null || text.trim().length() == 0) {
                 text = "You didn't enter any text.";
            }
            // step 1
            Document document = new Document();
            // step 2
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PdfWriter.getInstance(document, baos);
            // step 3
            document.open();
            // step 4
            document.add(new Paragraph(text));
            // step 5
            document.close();

            // setting some response headers
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control",
                "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            // setting the content type
            response.setContentType("application/pdf");
            // the contentlength
            response.setContentLength(baos.size());
            // write ByteArrayOutputStream to the ServletOutputStream
            OutputStream os = response.getOutputStream();
            baos.writeTo(os);
            os.flush();
            os.close();
        }
        catch(DocumentException e) {
            throw new IOException(e.getMessage());
        }
    }



}

使用了itextpdf-5.1.0.jar 这是我的 JSP 页面。

如果我单击“导出到 Excel”按钮,它会显示类似 pdf 的文件

从jsp获取字符串时,

String text = request.getParameter("datatoexport");

我得到的内容与 table td tr... 相同,而不是实际值。 有什么帮助吗?

【问题讨论】:

  • 您需要使用对象模型来呈现 PDF 文档中的数据。 PDFPTable我认为是要添加表的对象的名称。

标签: java html jsp servlets itext


【解决方案1】:

因为行 $("#datatoexport").val($("#customers").html());其中 Jquery 方法 .html 从 html 表中检索整个 html。从 html 表中提取文本并不容易,您需要在 jquery 中使用解析函数,如这篇文章:Getting text from td cells with jQuery

您发布的示例并不是请求服务器处理文本的最佳形式,请查看How to use Servlets and Ajax?

【讨论】:

  • user3152748写的应用程序的设计确实有缺陷。他应该重新考虑并回到绘图板上。不过,我将回答如何将 HTML 表格转换为 PDF 的问题。
【解决方案2】:

请查看示例ParseHtmlTable1ParseHtmlTable2。他们创建以下 PDF:html_table_1.pdfhtml_table_2.pdf

表是这样创建的:

StringBuilder sb = new StringBuilder();
sb.append("<table border=\"2\">");
sb.append("<tr>");
sb.append("<th>Sr. No.</th>");
sb.append("<th>Text Data</th>");
sb.append("<th>Number Data</th>");
sb.append("</tr>");
for (int i = 0; i < 10; ) {
    i++;
    sb.append("<tr>");
    sb.append("<td>");
    sb.append(i);
    sb.append("</td>");
    sb.append("<td>This is text data ");
    sb.append(i);
    sb.append("</td>");
    sb.append("<td>");
    sb.append(i);
    sb.append("</td>");
    sb.append("</tr>");
}
sb.append("</table>");

我冒昧地定义了这样的 CSS:

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

在另一个答案中,已经提到您的设计存在缺陷。你应该学习如何创建一个体面的架构。分离数据(例如表格)和样式(例如颜色)是您可以改进的一个示例。

现在我们像这样解析 CSS 和 HTML:

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()));

现在elements 列表包含一个元素:您的表格:

return (PdfPTable)elements.get(0);

您可以将此表格添加到您的 PDF 文档中。结果是这样的:

【讨论】:

  • 不要只是对答案投反对票,至少应该有礼貌地解释它有什么问题。
  • 你说错了。这就是为什么投反对票。但是您的工作受到赞赏.. 正确回答它
  • 我不会用苛刻的话来伤害人。我用这些话来教那些否则不会听的人。这就是我的老师教我的方式,虽然我在学习的时候不喜欢我的老师,但我现在很感激他们。他们教会了我很好,我非常感谢他们教会我的方式。
猜你喜欢
  • 2010-11-16
  • 2017-12-10
  • 2022-08-04
  • 1970-01-01
  • 2013-07-20
  • 2010-10-22
  • 2013-12-04
  • 1970-01-01
  • 2011-10-23
相关资源
最近更新 更多