iTextSharp - 绝对坐标表

use*_*890 5 c# itext absolute coordinates

我正在尝试使用本教程使用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;

    }

}
}
Run Code Online (Sandbox Code Playgroud)

以下行生成错误消息

ObjTestTable.WriteSelectedRows(0, -1, 200, 50, cb);
Run Code Online (Sandbox Code Playgroud)

错误消息是

表格宽度必须大于零.

教程建议使用宽度为零.我究竟做错了什么?

Bru*_*gie 12

您的代码中有几个错误.

在绝对位置添加表时,禁止使用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);
Run Code Online (Sandbox Code Playgroud)

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