1

Struggling with this problem in iText with PdfContentByte. When I try to create new page I'm using below code-

           canvas = writer.getDirectContent();
           canvas.saveState();


           canvas.stroke();
           canvas.restoreState();
         ...
            canvas.endText();
            itextDocument.newPage();

            setUpperFontAndSize(canvas);
            canvas.beginText();

The issue is occurring at the time of calling endText(). Is there any solution for it??

Sai prateek
  • 11,842
  • 9
  • 51
  • 66
  • can you post code from creating canvas to `canvas.endText();`? – Jordi Castilla Jan 08 '15 at 08:13
  • The exception is thrown because you would otherwise create a PDF that contains illegal syntax as demonstrated in the following question: [PDFs generated using itextsharp giving error at the time of first print command](http://stackoverflow.com/questions/21301497/pdfs-generated-using-itextsharp-giving-error-at-the-time-of-first-print-command) This is a question that was selected for [The Best iText Questions on StackOverflow](https://leanpub.com/itext_so). – Bruno Lowagie Jan 08 '15 at 08:39

2 Answers2

3

The OP says

The issue is occurring at the time of calling endText()

According to the source code of that method, the exception in question indicates that there was no matching beginText() call before.

A text object begins with the BT operator and ends with the ET operator, as shown in the Example, and described in Table 107.

EXAMPLE

BT
…Zero or more text operators or other allowed operators…
ET

... text objects cannot be statically nested ...

mkl
  • 90,588
  • 15
  • 125
  • 265
  • Ah, we answered almost simultaneously ;-) – Bruno Lowagie Jan 08 '15 at 08:36
  • @BrunoLowagie ;) Fortunately `IllegalPdfSyntaxException: Unbalanced begin/end text operators` is easier to assess than `IllegalPdfSyntaxException: Unbalanced save/restore state operators`... – mkl Jan 08 '15 at 08:49
2

Your code snippet is not complete. We see that you use:

canvas.endText();

As such, that statement is illegal and it is normal that you get an exception, because you can only use endText() after you have first used:

canvas.beginText();

In your code snippet, we only see beginText() after you have triggered endText().

Also be aware that a BT/ET text object (an object that you create when you introduce a beginText()/endText() sequence) "lives" on a page. A text object can not "span" multiple pages.

For instance, this would be illegal:

canvas.beginText();
// do stuff
document.newPage();
canvas.endText();

The BT/ET pair should occur on the same page:

canvas.beginText();
// do stuff
canvas.endText();
document.newPage();
Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165