c# - iTextSharp - 绝对坐标表

标签 c# itext coordinates absolute

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

错误信息是

The table width must be greater than zero.

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

最佳答案

您的代码中有几个错误。

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

关于c# - iTextSharp - 绝对坐标表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28728653/

相关文章:

ios - 按纬度订购 MKAnnotationViews 数组?

c# - 如何将一个或多个 LINQ Lambda 返回记录放入列表?! C#

c# - 函数式编程中如何使用StringBuilder?

c# - 使用 Lambda 表达式从字段名称中选择不同的字段

php - SQL查询,通过给定坐标选择最近的地方

coordinates - 获取谷歌地图标记的像素坐标

c# - Windows 开发环境值得付出代价吗?

java - 如何在没有数字签名的情况下添加时间戳

java - 使用 Spring Boot 在单个 PDF 中渲染表格和图表

java - itext 中的制表符