iTextSharp解析HTML到508兼容的PDF表格

时间:2015-03-27 22:17:10

标签: c# pdf-generation itextsharp section508

以下代码将从HTML创建PDF。问题是当文档被标记时,TH标记作为TD被写入PDF。反正有没有让PDF中的标签显示为TH?

          string html = @"<table>
                            <tr>
                                <TH> header1 </TH>
                                <TH> header2 </TH>
                                <TH> header3 </TH>
                            </tr>
                            <tr>
                                <td> col 1</td>
                                <td> col 2</td>
                                <td> col 3</td>
                            </tr>
                        </table>";

        FileStream fs = new FileStream(@"C:\\test.pdf", FileMode.Create);
        TextReader reader = new StringReader(html);

        Document document = new Document(PageSize.A4, 30, 30, 30, 30);

        PdfWriter writer = PdfWriter.GetInstance(document, fs);
        writer.SetTagged();

        writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_7);

        document.Open();


        XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, reader);
        document.Close();

        fs.Close();`

2 个答案:

答案 0 :(得分:2)

我们添加了正确的TH元素标记。这些更改将包含在下一个iText XMLWorker版本中。 通常不采用XMLWorker来生成正确标记的PDF。但是XMLWorker使用基本的iText Core标记逻辑,TD是所有类型表格单元的默认角色。

答案 1 :(得分:0)

您正在使用的版本不支持您想要的功能。

请查看today's update of the TableData class in XML Worker

@@ -97,6 +99,10 @@
                 if (direction != PdfWriter.RUN_DIRECTION_DEFAULT) {
                     cell.setRunDirection(direction);
                 }
+
+        if (HTML.Tag.TH.equalsIgnoreCase(tag.getName())) {
+            cell.setRole(PdfName.TH);
+        }
         try {
             HtmlPipelineContext htmlPipelineContext = getHtmlPipelineContext(ctx);
             cell = (HtmlCell) getCssAppliers().apply(cell, tag, htmlPipelineContext);

这可以解决您在iText中遇到的问题。它现在计划移植到iTextSharp。修复将在下一个版本中。