0

我正在使用以下代码使用 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%。

谢谢

4

1 回答 1

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);
}
于 2013-07-29T13:09:53.890 回答