4

I'm using iTextSharp version: 5.5.6; iTextSharp XML Worker version: 5.5.6

I got some code from Here, but after I run the code, the PDF file will never open

:The file is damaged and could not be repaired. 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 Revision\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 is wrong?

4
  • ParseXHtml method is not using for parse HTML code? Commented Jun 18, 2015 at 13:20
  • What I need to do is: I have to generate a report. In order to do that, I created a normal razor view, then try to use ParseXHtml to create a PDF report. Commented Jun 18, 2015 at 13:23
  • Try calling doc.Close() before calling buf = memStream.ToArray(); Commented Jun 18, 2015 at 13:24
  • OMG! you are genius! After I switch these two statements, it is working. Thank you very much! Commented Jun 18, 2015 at 13:29

1 Answer 1

5

(as discovered through the comments)

You need to call doc.Close() before calling buf = memStream.ToArray();. This let's iTextSharp know that you are actually done and it should flush any buffers and write the PDF trailer.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.