iTextSharp - 在绝对坐标中的表格

5

我正在尝试使用这个教程来使用iTextSharp在绝对坐标中定位表格。这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

namespace iTextSharpQuestion
{
    class Program
{
    static void Main(string[] args)
    {
        System.IO.FileStream fs = new FileStream(@"C:\Temp\" + "First PDF document.pdf", FileMode.Create);
        Document document = new Document(PageSize.LETTER, 25, 25, 30, 30);
        document.SetPageSize(iTextSharp.text.PageSize.LETTER.Rotate());
        PdfWriter writer = PdfWriter.GetInstance(document, fs);
        document.Open();
        PdfContentByte cb = writer.DirectContent;
        BaseFont f_cn = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
        cb.BeginText();
        cb.SetFontAndSize(f_cn, 9);

        PdfPTable ObjTestTable = TestTable();
        ObjTestTable.WriteSelectedRows(0, -1, 200, 50, cb);

        cb.EndText();
        // Close the document
        document.Close();
        // Close the writer instance
        writer.Close();
        // Always close open filehandles explicity
        fs.Close();
    }
    public static PdfPTable TestTable()
    {
        PdfPTable table = new PdfPTable(3);
        PdfPCell cell = new PdfPCell(new Phrase("Header spanning 3 columns"));
        cell.Colspan = 3;
        cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
        table.AddCell(cell);
        table.AddCell("Col 1 Row 1");
        table.AddCell("Col 2 Row 1");
        table.AddCell("Col 3 Row 1");
        table.AddCell("Col 1 Row 2");
        table.AddCell("Col 2 Row 2");
        table.AddCell("Col 3 Row 2");
        return table;

    }

}
}

以下行会生成错误信息。
ObjTestTable.WriteSelectedRows(0, -1, 200, 50, cb);

错误信息为:

表格宽度必须大于零。

教程建议使用宽度为零。我做错了什么?
1个回答

13

你的代码中有几个错误。

当您在绝对位置添加表格时,禁止使用 BeginText()EndText(),因为这会导致嵌套文本对象。如 ISO-32000-1 中所述,您不能嵌套 BT/ET 序列,如果您的表格包含文本,则情况就是这样。由于您无法在文本对象内添加表格,因此使用 SetFontAndSize() 也没有意义。

话虽如此:您需要为表格定义宽度:

PdfContentByte cb = writer.DirectContent;
PdfPTable table = new PdfPTable(1);
table.TotalWidth = 400f;
table.AddCell("Test");
table.WriteSelectedRows(0, -1, 200, 50, cb);
注意,您所提到的网站包含一本由Manning Publications出版的书籍的非法副本,而我是这本书的作者。

1
我知道有盗版电子书的存在,但这是我第一次见到将其转换为 HTML 在线阅读。 - Paulo Soares
谢谢你,布鲁诺!我很抱歉引用了盗版资源。你代码的最后一行应该是 table.WriteSelectedRows(0, -1, 200, 50, cb);,对吧? - user1700890

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接