Thursday, February 21, 2008

Unable to cast object of type 'iTextSharp.text.Paragraph' to type 'iTextSharp.text.Table'

If you dig around the issue you will quickly discover that there are two possible solutions:

  • use <ignore> attribute
  • delete whitespaces between iTextXML tags

Luckily, another simple solution exists: the Parse method of ITextHandler accepts XmlTextReader as a parameter. You just use this feature:

XmlTextReader xmlTemplateReader = new XmlTextReader( source );
/* 
 *  this is crucial for iText to work correctly 
 *  WITHOUT <ignore> and
 *  WITH whitespaces
 *  since whitespaces are automatically removed from the xml
 *
 *  remove the line to see the exception
 */
xmlTemplateReader.WhitespaceHandling = WhitespaceHandling.None;
 
/* iTextSharp stuff follows */
ITextHandler xmlHandler = new ITextHandler( document );
xmlHandler.Parse( xmlTemplateReader );

There is also another possibility that leads to this exception - it is when the XML document contains table data that do not match the schema. For example if you have:



<itext author="Bruno Lowagie" title="curriculum vitae">
  <chapter numberdepth="0">
    <section numberdepth="0">
      <title font="Times New Roman" encoding="CP1250" size="13" align="Center" 
       leading="13">Title</title>
      <table width="100%" widths="70;70;70" cellspacing="0" cellpadding="2" columns="3" 
       borderwidth="1" left="true" right="true" top="true" bottom="true" >
        <row>
          <cell borderwidth="1" left="true" right="true" top="true" bottom="true" horizontalalign="Center" verticalalign="Default" colspan="3" grayfill="0.65">
            <phrase font="Times New Roman" encoding="CP1250" size="12" style="bold"></phrase >
          </cell>
        </row>
        SOMETEXTHERE
      </table>
    </section>
  </chapter>
</itext>
Note the misplaced "SOMETEXTHERE".

6 comments:

  1. In your example I can see that you are specifying an encoding for title tag encoding="CP1250"

    I have problem with XMLParser.Parse with not displaying some special characters.

    Can you please help me with that. I read your article on SourceForge.net.

    Did you found an solution?

    Thx

    ReplyDelete
  2. yes, we've found a solution. we put encoding attribute in EACH paragraph tag of the xml. this seems bloated but at least works correctly.

    Regards,
    Wiktor

    ReplyDelete
  3. I have tried your solution with adding attribute encoding, but I still can not see chars like (č - č - č - Lowercase C-hachek),...

    Is there any other trick? :o)

    ReplyDelete
  4. could you provide the XML file which generates incorrect pdf?

    ReplyDelete
  5. Could you give me simple example of xml where I could add header and footer of document? I tried to add these items but got exception: "Unable to cast object of type 'iTextSharp.text.Paragraph' to type 'iTextSharp.text.HeaderFooter'. Do you know what I should do?

    ReplyDelete