iTextSharp AddText causing 'An error exists on this page'
The resulting PDF document gets 'An error exists on this page.' when opened in Acrobat Adobe Reader. Any ideas as to why this occurs? It was happening in both an older version of iTextSharp and the 5.1.1 version that I tried today.
Test code:
static void PDFErrorOnPage()
{
Document document = new Document(PageSize.LETTER);
float fMarginLeft = 15.822f; // 0.21975 inch
float fMarginRight = 15.822f; // 0.21975 inch
float fMarginTop = 36.0f; // 0.5 inch
float fMarginBottom = 36.0f; // 0.5 inch
float fLabelSpacingHorizontal = 10.08f;
float fLabelWidth = 186.732f;
float fLabelHeight = 72.0f;
float fLabelPadding = 5.0f;
float fLabelPaddingLeft = 20.0f;
float fLabelPaddingBottom = 5.0f;
float fLabelPaddingTop = 0.0f;
int nRow = 0;
int nCol = -1;
bool bDebug = true;
try
{
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
Font font = new Font(bf, 8, Font.NORMAL, BaseColor.BLACK);
Font fontBold = new Font(bf, 8, Font.BOLD, BaseColor.BLACK);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("d:\\tempjunk\\test.pdf", FileMode.Create));
document.SetMargins(fMarginLeft, fMarginRight, fMarginTop, fMarginBottom);
document.Open();
PdfContentByte cb = writer.DirectContent;
for (int i = 0; i < 26; i++)
{
nCol++;
if (nCol > 2)
{
nCol = 0;
nRow++;
}
if (nRow > 9)
{
nRow = 0;
document.NewPage();
Console.WriteLine("document.NewPage()");
}
float fLabelBottomLeftX = fMarginLeft + (nCol * fLabelSpacingHorizontal) + (nCol * fLabelWidth);
float fLabelBottomLeftY = fMarginBottom + ((9 - nRow) * fLabelHeight);
if (bDebug)
{
cb.SetRGBColorStroke(0x00, 0x00, 0xFF);
cb.Rectangle(fLabelBottomLeftX, fLabelBottomLeftY, fLabelWidth, fLabelHeight);
cb.Stroke();
}
cb.BeginText();
ColumnText ct = new ColumnText(cb);
ct.SetSimpleColumn(
fLabelBottomLeftX + fLabelPaddingLeft,
fLabelBottomLeftY + fLabelPaddingBottom,
fLabelBottomLeftX + fLabelWidth - (fLabelPaddingLeft + fLabelPadding),
fLabelBottomLeftY + fLabelHeight - (fLabelPaddingBottom + fLabelPaddingTop),
12.0f,
PdfContentByte.ALIGN_LEFT);
ct.AddText(new Chunk("One\nTwo\nThree\nFour\nFive", font));
ct.Go();
cb.EndText();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + " " + ex.StackTrace);
}
finally
{
if (document != null)
document.Clos开发者_Python百科e();
}
}
You need to move the BeginText and EndText methods so that they only apply to your text. The following works for me:
ColumnText ct = new ColumnText(cb);
ct.SetSimpleColumn(
fLabelBottomLeftX + fLabelPaddingLeft,
fLabelBottomLeftY + fLabelPaddingBottom,
fLabelBottomLeftX + fLabelWidth - (fLabelPaddingLeft + fLabelPadding),
fLabelBottomLeftY + fLabelHeight - (fLabelPaddingBottom + fLabelPaddingTop),
12.0f,
PdfContentByte.ALIGN_LEFT);
cb.BeginText();
ct.AddText(new Chunk("One\nTwo\nThree\nFour\nFive", font));
cb.EndText();
ct.Go();
精彩评论