【问题标题】:iTextSharp - Table in absolute coordinatesiTextSharp - 绝对坐标表
【发布时间】:2020-08-26 23:09:35
【问题描述】:

我正在尝试使用这个tutorial 来使用 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);

错误信息是

表格宽度必须大于零。

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

【问题讨论】:

    标签: c# itext coordinates absolute


    【解决方案1】:

    您的代码中有几个错误。

    在绝对位置添加表格时,禁止使用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 出版的一本书的非法副本,我是该书的作者。

    【讨论】:

    • 我知道电子书的盗版,但这是我第一次看到转换为 html 以在线阅读。
    • 谢谢你,布鲁诺!很抱歉引用了盗版资源。你代码的最后一行应该是table.WriteSelectedRows(0, -1, 200, 50, cb); 不是吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多