ITextSharp.tool.xml.XMLWorkerHelper.GetInstance (). ParseXHtml doesn't work

I am using iTextSharp version: 5.5.6; iTextSharp XML Worker version: 5.5.6

I got the code here , but after running the code, the PDF file never opens

: The file is damaged and cannot be recovered. Local \ EWHvxm9t5 ++

HTMLText = "\ r \ n \ r \ n \ r \ n \ r \ n \ r \ n \ r \ n
 \ r \ n \ r \ n \ r \ n \ r \ n \ r \ n \ r \ n Item \ r \ n Description \ r \ n
LotNo \ r \ n Edition \ r \ n NamePlatSN \ r \ n
DateCreated \ r \ n CreatedBy \ r \ n \ r \ n \ r \ n
\ r \ n \ r \ n 100-817412-001 \ r \ n X500-G02 - ENV DWG \ r \ n 15020008 \ r \ n B
\ r \ n testing123 \ r \ n 4/9/2015 12:00:00 AM \ r \ n ULTRATCS \ xma \ r \ n \ r \ n \ r \ n
\ r \ n \ r \ n \ r \ n \ r \ n \ r \ n \ r \ n "

The HTML string (better formatted) looks like this:

<!DOCTYPE html>
<html lang=\"en\" >
<body>




        <table> 

   <tr> 
   <th> Item </th>
   <th> Description</th>
   <th>   LotNo</th>
   <th>Revision</th>
   <th>NamePlatSN</th>
   <th>DateCreated</th>
   <th>CreatedBy</th>

   </tr>

    <tr>
    <td> 100-817412-001</td>
     <td> X500-G02 - ENV DWG            </td>
    <td>15020008</td>
    <td> B      </td>
    <td>testing123</td>
    <td> 4/9/2015 12:00:00 AM</td>
    <td> ULTRATCS\\xma</td>

    </tr>
    </table>



</body>
</html>

      

Here is the code:

 protected ActionResult ViewPdf(object model)
        {
            // Create the iTextSharp document.          
            Document doc = new Document();
            byte[] buf;
            // Set the document to write to memory.
            MemoryStream memStream = new MemoryStream();
            PdfWriter writer = PdfWriter.GetInstance(doc, memStream);
            writer.CloseStream = false;
            doc.Open();
            string htmltext = this.RenderActionResultToString(this.View(model));      

               using (var srHtml = new StringReader(htmltext))
                 {
                            //Parse the HTML
                            XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
                            //buf  = new byte[memStream.Position];
                            //memStream.Position = 0;
                            //memStream.Read(buf, 0, buf.Length);

                            buf = memStream.ToArray(); 

                            doc.Close();
                        }       
           // System.IO.File.WriteAllBytes(@"c:\\temp\test.pdf", buf);
            // Send the binary data to the browser.
            return new BinaryContentResult(buf, "application/pdf");
        }       
    }
}

      

What's wrong?

+3


source to share


1 answer


(as discovered in the comments)



You need to make a call doc.Close()

before calling buf = memStream.ToArray();

. This will let iTextSharp know that you are actually done and it should flush any buffers and write the PDF trailer.

+4


source







All Articles