Skip to main content
Skip table of contents

What is causing syntax errors in a page created with iText 7?

The document prints fine, so why do I get an error?

I am getting the following error when I want to print a PDF generated with iTextSharp"

"An error exists on this page. Acrobat may not display the page correctly. please contact the person who created the pdf document to correct the problem"

The document prints fine, but why do I get this error? This is my code:

 

PdfContentByte cb = writer.DirectContent;
cb.BeginText();
Font NormalFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, Color.BLACK);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance("/banner.tiff");
img.SetAbsolutePosition(35, 760);
img.ScalePercent(50);
cb.AddImage(img);
cb.SetLineWidth(2);
cb.MoveTo(20, 740);
cb.LineTo(570, 740);
cb.Stroke();
cb.BeginText();
writeText(cb, drHead["EmpName"].ToString(), 25, 745, f_cb, 14);
writeText(cb, "Employee ID:", 450, 745, f_cn, 12);
writeText(cb, drHead["EmployeeID"].ToString(), 515, 745, f_cb, 12);
cb.EndText();
cb.BeginText();
writeText(cb, "XXXX:", 25, 725, f_cb, 8);
cb.EndText();
cb.SetLineWidth(2);
cb.MoveTo(20, 675);
cb.LineTo(570, 675);
cb.Stroke();
cb.EndText();
cb.BeginText();
writeText(cb, "XXXXXXXXXXXXXXXX", 20, 140, f_cb, 12);
cb.EndText();
cb.EndText();
Please help me to know what is the issue.

 

Posted on StackOverflow on Jan 23, 2014 by Vandana


 

You have nested text blocks. That's illegal PDF syntax. I think recent versions of iTextSharp warn you about this, so I guess you're using an old version. Look for the wrong and right code snippets written in Java (C# terminology is identical). Note that there is no PdfContentByte class in iText 7. We use PdfCanvas instead:

PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
PdfPage page = pdfDoc.getPage(numerOfPage);
PdfCanvas canvas = new PdfCanvas(page);

This is wrong:

canvas.beginText();
…
canvas.beginText();
…
canvas.endText();
…
canvas.endText();

This is right:

canvas.beginText();
…
canvas.endText();
…
canvas.beginText();
…
canvas.endText();

Moreover: ISO-32000-1 tells you that some operations are forbidden inside a text block.

This is wrong:

canvas.beginText();
…
canvas.addImage();
…
canvas.endText();

This is right:

canvas.beginText();
…
canvas.endText();
…
canvas.addImage();

Finally, some operators are mandatory when creating a text block. For instance: you always need setFontAndSize() (I don't know what you're doing in writeText(), but I assume you're setting the font correctly).

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.