c# - 加载 PDF 文档时出错 - iTextSharp PDF

标签 c# html asp.net pdf itext

我在 ASP.NET C# 中使用 iTextSharp 生成一个 PDF 文件。

我尝试为多个元素生成一个标题 + 表格。在我想开始一个新页面的每个元素之后。我使用 doc.NewPage() 执行此操作,但是当我生成 PDF 文件时,打开文件时出现以下错误:

Error loading the PDF document

当我尝试在最新版本的 Google Chrome 中打开 PDF 文件时出现此错误。当我尝试在 Adob​​e Reader 中打开文件时,出现以下错误消息:

There was an error opening this document. The file is damaged and could not be repaired.

PDF文件的大小也只有1kb...

这是我生成文件的代码:

//Create a byte array that will eventually hold our final PDF
//must be outside of the foreach loop (and everything else), because we store every single generated table in here for the final pdf!!
Byte[] bytes;

List<TableObject> myTables = getTables();
TableObject currentTable = new TableObject();

//Boilerplate iTextSharp setup here
//Create a stream that we can write to, in this case a MemoryStream
using (MemoryStream ms = new MemoryStream())
{
    //Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
    using (Document doc = new Document(PageSize.A4, 10f, 10f, 10f, 0f))
    {
        //Create a writer that's bound to our PDF abstraction and our stream
        PdfWriter writer = PdfWriter.GetInstance(doc, ms);

        //Open the document for writing
        doc.Open();

        //writer.CloseStream = false;
        //loop all tableobjects inside the document & the instance of PDFWriter itself! 
        foreach (TableObject to in myTables.ToList())
        {
            //Get the data from database corresponding to the current tableobject and fill all the stuff we need!
            DataTable dt = getDTFromID(to._tableID);
            Object[] genObjects = new Object[5];
            genObjects = gen.generateTable(dt, currentTable._tableName, currentTable._tableID.ToString(), currentTable, true);

            StringBuilder sb = (StringBuilder)genObjects[1];
            String tableName = sb.ToString();
            Table myGenTable = (Table)genObjects[0];
            //String table contains a valid html string, which works in the generate function for a single page document
            String table = genObjects[2].ToString();

            using (StringReader srHtml = new StringReader(table))
            {
                //Parse the HTML
                iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
            }

            //this will probably render a whole new page at the end of the file!! need to be fixed later!!!
            //doc.NewPage();
        }

        //After all of the PDF "stuff" above is done and closed but **before** we
        //close the MemoryStream, grab all of the active bytes from the stream
        bytes = ms.ToArray();

        doc.Close();
    } 
}

//Now we just need to do something with those bytes.
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=ShiftReport_complete.pdf");
Response.BinaryWrite(bytes);

如何解决这个问题,以便在打开 PDF 文件时摆脱错误消息?

最佳答案

您的代码像这样完成创建 PDF:

    bytes = ms.ToArray();

    doc.Close();

这是错误的顺序!在 doc.Close() 期间,将写入挂起的 PDF 对象和 PDF 预告片。当您在此之前获取 byte[] 时,您的结果 PDF 缺少这些部分。

简单地反过来做:

    doc.Close();
    bytes = ms.ToArray();

关于c# - 加载 PDF 文档时出错 - iTextSharp PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34608328/

相关文章:

c# - 如何设置 XAML 组合框的选定值?

c# - 如何使用 OData 按 GUID 正确过滤我的数据集?

jquery - 同时隐藏/显示给 div

javascript - angularjs延迟加载应用程序直到指定条件

javascript - AJAX 版网页。我如何携带初始数据?

c# - 向前移动物体是乘法而不是加法

c# - 在 C# 中仅将类型作为参数传递

html - ContentEditable 上可靠的跨浏览器信息

c# - Identity isAuthenticated cookie

c# - 将自定义 CSS 应用于 ASP.NET 中的 Crystal Reports