iTextSharp - Table 绝对坐标

iTextSharp - Table in absolute coordinates

我正在尝试使用此 tutorial 通过 iTextSharp 在绝对坐标中定位 table。这是我的代码:

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

错误信息是

The table width must be greater than zero.

教程建议使用零宽度。我做错了什么?

您的代码中有几个错误。

在绝对位置添加table时,禁止使用BeginText()EndText(),否则会导致嵌套文本对象。正如 ISO-32000-1 中所解释的那样,您不能使用下一个 BT/ET 序列,如果您的 table 包含文本,这正是会发生的情况。由于不能在文本对象中添加 table,因此使用 SetFontAndSize().

也没有意义

话虽这么说:您需要为 table:

定义一个宽度
PdfContentByte cb = writer.DirectContent;
PdfPTable table = new PdfPTable(1);
table.TotalWidth = 400f;
table.AddCell("Test");
table.WriteSelectedRows(0, -1, 200, 50, cb);

请注意,您引用的网站也包含我是作者的 Manning Publications 出版的一本书的非法副本。