Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 加载PDF文档时出错-iTextSharp PDF_C#_Html_Asp.net_Pdf_Itextsharp - Fatal编程技术网

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

C# 加载PDF文档时出错-iTextSharp PDF,c#,html,asp.net,pdf,itextsharp,C#,Html,Asp.net,Pdf,Itextsharp,我在ASP.NET C#中使用iTextSharp生成了一个PDF文件 我尝试为几个元素生成一个标题+表格。在每个元素之后,我想开始一个新的页面。我使用doc.NewPage()执行此操作,但在生成PDF文件时,打开文件时出现以下错误: //Create a byte array that will eventually hold our final PDF //must be outside of the foreach loop (and everything else), because

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

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

//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文档时出错

当我尝试在最新版本的Google Chrome中打开PDF文件时,我遇到了这个错误。当我尝试在Adobe Reader中打开文件时,会收到以下错误消息:

打开此文档时出错。文件已损坏,无法修复

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
//必须在foreach循环(以及所有其他循环)之外,因为我们将生成的每个表都存储在这里,以获得最终的pdf!!
字节[]字节;
List myTables=getTables();
TableObject currentTable=新建TableObject();
//样板文件在这里设置
//创建一个我们可以写入的流,在本例中是一个MemoryStream
使用(MemoryStream ms=new MemoryStream())
{
//创建一个iTextSharp文档,该文档是PDF的抽象,但**不是**PDF
使用(文档文档=新文档(PageSize.A4、10f、10f、10f、0f))
{
//创建一个绑定到PDF抽象和流的编写器
PdfWriter writer=PdfWriter.GetInstance(doc,ms);
//打开文档进行写作
doc.Open();
//writer.CloseStream=false;
//循环文档中的所有tableobjects&PDFWriter自身的实例!
foreach(myTables.ToList()中的TableObject to)
{
//从对应于当前tableobject的数据库中获取数据,并填充我们需要的所有内容!
DataTable dt=getDTFromID(to.\u tableID);
Object[]genObjects=新对象[5];
genObjects=gen.generateTable(dt,currentTable.\u tableName,currentTable.\u tableID.ToString(),currentTable,true);
StringBuilder sb=(StringBuilder)基因对象[1];
字符串tableName=sb.ToString();
表myGenTable=(表)基因对象[0];
//String表包含一个有效的html字符串,该字符串在单页文档的generate函数中工作
String table=GenObject[2].ToString();
使用(StringReader srHtml=新StringReader(表))
{
//解析HTML
iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer、doc、srHtml);
}
//这可能会在文件末尾呈现一个全新的页面!!需要稍后修复!!!
//doc.NewPage();
}
//在上述所有PDF“内容”完成并关闭后,但**在**之前,我们
//关闭MemoryStream,从流中获取所有活动字节
字节=ms.ToArray();
doc.Close();
} 
}
//现在我们只需要对这些字节做点什么。
Response.ContentType=“application/pdf”;
AppendHeader(“内容处置”、“附件;文件名=ShiftReport_complete.pdf”);
响应。二进制写入(字节);

如何解决此问题,以便在打开PDF文件时消除错误消息?

您的代码完成PDF的创建,如下所示:

    bytes = ms.ToArray();

    doc.Close();
这是错误的顺序!在
doc.Close()
期间,将写入挂起的PDF对象和PDF尾部。在抓取之前的
字节[]
时,您的结果PDF缺少这些片段

只需换一种方式:

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

我用谷歌ChromeV47.0.2526.106试用过它,但也用AdobeReader试用过。Adobe Reader发出以下错误消息:
打开此文档时出错。文件已损坏,无法修复。
请查看此链接并尝试一下@编码器我认为问题在于生成方法,因为保存的文件只有几个字节。。(它只有15个字节)。如果您认为这可能是问题所在,请尝试检查一下。你自己会知道的我在pdf文件中只生成一个表时使用了完全相同的代码,没有foreach循环,而且工作正常,这让人困惑。有没有可能是
myTables.ToList()
导致了这个问题?多么愚蠢的错误。。。谢谢你的提示。它现在工作得很好!你知道我如何旋转每一页吗?e、 g.第1页:肖像,第2页:景观你知道我如何旋转每一页吗这是一个新问题,因此应作为一个单独的问题提出。不过,一个快速提示是:在通过
doc.NewPage()
或其他方式启动新页面之前,请使用
doc.SetPageSize(…)