【问题标题】:iTextSharp 5.4.2 : Fixing the width of a column in a tableiTextSharp 5.4.2:固定表格中列的宽度
【发布时间】:2023-03-30 14:55:02
【问题描述】:

我正在使用以下代码使用 iTextSharp 库版本 5.4.2 生成 PDF 文档。

// Create a Document object
        var document = new Document(PageSize.A4, 50, 50, 25, 25);

        // Create a new PdfWriter object, specifying the output stream
        var output = new MemoryStream();
        var writer = PdfWriter.GetInstance(document, output);

        // Open the Document for writing
        document.Open();



    //Gets System.Web.UI.WebControls.Table
    //Returns HTML table with 4 coulms

        var flowsheetTable = GetTable(report);


        var stringWriter = new StringWriter();
        using (var htmlWriter = new HtmlTextWriter(stringWriter))
        {
            flowsheetTable.RenderControl(htmlWriter);
        }


        List<IElement> htmlarraylist = HTMLWorker.ParseToList(new StringReader(stringWriter.ToString()), null);
        for (int k = 0; k < htmlarraylist.Count; k++)
        {
            document.Add((IElement)htmlarraylist[k]);
        }


        document.Close();

        Response.ContentType = "application/pdf";
        Response.AddHeader("Content-Disposition", "attachment;filename=Receipt-test.pdf");
        Response.BinaryWrite(output.ToArray());

GetTable() 方法返回一个有 4 列的 System.Web.UI.WebControls.Table。 有没有办法固定表格中第一列的宽度。我希望第一列占总宽度的 40%。

谢谢

【问题讨论】:

  • 样式表不能在 html 到 pdf 中工作(宽度)。你能提供 html 代码吗?

标签: .net c#-4.0 pdf-generation itextsharp


【解决方案1】:

当您循环浏览IElement 对象的集合时,您可以单独投射、检查和修改每个对象。在你的情况下,你可能想做这样的事情:

//Sample table with four columns
var sampleTable = "<table><tr><td>A</td><td>B</td><td>C</td><td>D</td></tr></table>";

//Parse sample HTML to collection if IElement objects
List<IElement> htmlarraylist = HTMLWorker.ParseToList(new StringReader(sampleTable), null);

//Declare variables for use below
IElement ele;
PdfPTable t;

//Loop through the collection
for (int k = 0; k < htmlarraylist.Count; k++) {

    //Get the individual item (no cast should be needed)
    ele = htmlarraylist[k];

    //If the item is a PdfPTable
    if (ele is PdfPTable) {

        //Get and cast it
        t = ele as PdfPTable;

        //Set the widths (40%/20%/20%/20%)
        t.SetWidths(new float[] { 4, 2, 2, 2 });

    }

    //Regardless of what was done above, add the object to our document
    document.Add(ele);
}

【讨论】:

  • 谢谢您的回复。有没有办法使用 CSS 类。我所知道的是我们需要在单个标签上应用 CSS 类。因此,如果我在

    标签上应用某种样式,所有

    标签都将使用相同的样式。有什么方法可以在单个行/列上应用样式。

  • HTMLWorker stackoverflow.com/a/5322787/231316 中使用样式表请参阅此内容。此外,HTMLWorker 已被弃用,取而代之的是 XMLWorker。强烈建议您使用较新的类,因为这是所有积极开发的重点。
  • 感谢您的快速回复。实际上,我之前确实遇到过这个链接stackoverflow.com/questions/5321779/…,但它们将样式应用于各个标签。所以如果我将一些样式应用于

    标签,相同的样式将应用于所有标签,我正在寻找一种方法,如果一个元素用于样式,那么只有它应该被应用

  • 以上链接是每个标签的规则,因此H1 的处理方式将不同于P。但是你也可以使用 CSS 类,看这个链接stackoverflow.com/a/8184565/231316
猜你喜欢
  • 1970-01-01
  • 2014-02-10
  • 2018-09-05
  • 1970-01-01
  • 2015-01-07
  • 2011-05-10
  • 2014-08-03
相关资源
最近更新 更多