iTextSharp.tool.xml.XMLWorkerHelper.GetInstance()。ParseXHtml无效

时间:2015-06-18 13:02:28

标签: c# itextsharp

我正在使用iTextSharp版本:5.5.6; iTextSharp XML Worker版本:5.5.6

我从Here获得了一些代码,但在运行代码后,PDF文件将永远不会打开

  

:文件已损坏,无法修复。本地\ EWHvxm9t5 ++

     

的htmlText =“\ r \ n \ r \ n \ r \ n \ r \ n \ r \ n   \ r \ n \ r \ n \ r \ n \ r \ n \ r \ n \ r \ n \ n    \ r \ n项目\ r \ n说明\ r \ n
  LotNo \ r \ n修订版\ r \ n NamePlatSN \ r \ n \ n
  DateCreated \ r \ n CreatedBy \ r \ n \ r \ n \ r \ n \ n   \ r \ n \ r \ n 100-817412-001 \ r \ n X500-G02 -   ENV DWG \ r \ n 15020008 \ r \ n B
  \ r \ n测试123 \ r \ n 4/9/2015 12:00:00   AM \ r \ n ULTRATCS \ xma \ r \ n \ r \ n \ r \ n \ n   \ r \ n \ r \ n \ r \ n \ r \ n \ r \ n \ r \ n“

HTML字符串(格式更好)如下所示:

<!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>

以下是代码:

 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");
        }       
    }
}

有什么问题?

1 个答案:

答案 0 :(得分:4)

(通过评论发现)

在致电doc.Close()之前,您需要致电buf = memStream.ToArray();。这让我们的iTextSharp知道你已经完成了它应该刷新任何缓冲区并编写PDF预告片。