I am trying to use this tutorial to position table in absolute coordinates using iTextSharp. Here is my code:
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;
}
}
}
The following line generates error message
ObjTestTable.WriteSelectedRows(0, -1, 200, 50, cb);
The error message is
The table width must be greater than zero.
Tutorial suggests to use width zero. What am I doing wrong?
You have several errors in your code.
When you add a table at absolute positions, it is forbidden to use BeginText()
and EndText()
as that would cause nested text objects. As explained in ISO-32000-1, you can not next BT
/ET
sequences and that's exactly what will happen if your table contains text. As you can not add a table inside a text object, it also doesn't make sense to use SetFontAndSize()
.
This being said: you need to define a width for the table:
PdfContentByte cb = writer.DirectContent;
PdfPTable table = new PdfPTable(1);
table.TotalWidth = 400f;
table.AddCell("Test");
table.WriteSelectedRows(0, -1, 200, 50, cb);
Note that the site you refer too contains an illegal copy of a book published by Manning Publications of which I am the author.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With