首页 > 解决方案 > C# PDF表格在错误的位置添加行

问题描述

[由于对答案的误解而编辑]

我正在用 C# 做一个简单的程序,用 iText7 创建 PDF 文件。在此 PDF 中,我添加了一个表格,其第一个单元格从文件中的某个位置开始。

我不知道我是否正确设置了位置,但是每次我添加另一个单元格时tab.StartNewRow(),生成的新表都会重新定位,将最后一个单元格作为位置参考,将先前添加的单元格从该点向上放置,而我想添加单元格从那时起。

我应该使用哪种方法?那是我的代码:以前我使用设置第一个表格单元格的位置tab1.SetFixedPosition(20, heigh, width);

然后,为了添加其他单元格:

if (mylistbox.Items.Count > 0)
  {
     tab1.AddCell("FIRST CELL");
     tab1.StartNewRow();
     for (int i = 0; i < mylistbox.Items.Count; i++)
        {
          tab1.AddCell(mylistbox.Items[i].ToString());
          tab1.StartNewRow();
        }
        doc.Add(tab1);
  }

[编辑#2]为了更好地解释我的问题

我必须放置 5 个表格,它们必须从某个点向下增长,在文档中以相同的距离、相同的高度和宽度放置。这张图片解释了它应该如何产生:

pdf示例

标签: c#winformsitextwindows-forms-designeritext7

解决方案


在 WPF 应用程序中,我有ListBox5 个项目,编号从 1 到 5。这应该与 WinForms 非常相似。

CreatePercentArray的大小等于一行中的列数。

一篇关于表格的有趣文章:链接

  private void CreateListBoxTable(Document pdfDoc)
        {
            // Create an array where each item has an equal width, and use the entire pdf width
            // The CreatePercentArray takes a size which is equal to the amount of columns in a row
            // By using percentages, they will automatically adapt
            // Use CreatePointArray for exacter measurements
            var table = new Table(UnitValue.CreatePercentArray(2)).UseAllAvailableWidth();

            if (!MyListBox.Items.IsEmpty)
            {
                foreach (var listBoxItem in MyListBox.Items)
                {
                    table.AddCell(((ListBoxItem) listBoxItem).Content.ToString());
                }
            }
            // Adds table to document
            pdfDoc.Add(table);
            // Closes document
            pdfDoc.Close();
        }

输出


推荐阅读