文件已损坏,无法修复

时间:2010-03-13 23:36:12

标签: asp.net

我正在尝试根据从ASP.net Web服务收到的二进制数据在我的ASP.net页面中显示PDF文件。下面是代码。虽然我出于某种原因从Web服务获取数据,如果我在页面加载时运行下面提到的代码,我会收到上述错误。

请帮忙

Response.Buffer = True
Response.ContentType = "application/pdf"
Response.AddHeader("Content-Disposition", "Inline")

Dim ws As New imageGenService.Service1
Dim imagebyte As Byte() = Nothing

imagebyte = ws.generateSamplePDF()

If imagebyte IsNot Nothing Then
    '"attachment; filename=Whatever.pdf"

    Dim MemStream As New System.IO.MemoryStream
    Dim doc As New iTextSharp.text.Document
    Dim reader As iTextSharp.text.pdf.PdfReader
    Dim numberOfPages As Integer
    Dim currentPageNumber As Integer
    Dim writer As iTextSharp.text.pdf.PdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, MemStream)
    doc.Open()
    Dim cb As iTextSharp.text.pdf.PdfContentByte = writer.DirectContent
    Dim page As iTextSharp.text.pdf.PdfImportedPage
    Dim rotation As Integer

    reader = New iTextSharp.text.pdf.PdfReader(imagebyte)
    numberOfPages = reader.NumberOfPages
    currentPageNumber = 0

    Do While (currentPageNumber < numberOfPages)
        currentPageNumber += 1
        doc.SetPageSize(PageSize.LETTER)
        doc.NewPage()
        page = writer.GetImportedPage(reader, currentPageNumber)
        rotation = reader.GetPageRotation(currentPageNumber)
        If (rotation = 90) Or (rotation = 270) Then
            cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(currentPageNumber).Height)
        Else
            cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0)
        End If

    Loop

    If MemStream Is Nothing Then
        Response.Write("No Data is available for output")
    Else
        Response.BinaryWrite(MemStream.GetBuffer())
    End If



End If

当我在下面的记事本中打开PDF时,我看到以下内容:

%PDF-1.4
%âãÏÓ


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
    Untitled Page
</title></head>
<body>
    <form name="form1" method="post" action="ShowPDF.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNzgzNDMwNTMzZGQpkGvp7bYOLIE6xshhcZ2kYd2baA==" />
</div>

    <div>

    </div>
    </form>
</body>
</html>

3 个答案:

答案 0 :(得分:8)

您的代码将继续在响应中呈现您的aspx网站代码,因为您尚未调用Response.End来阻止进一步处理。在完成二进制写入后添加对该方法的调用 - 您的PDF呈现代码将最终为:

    Response.ContentType = "application/pdf"
    Response.AddHeader("Content-Disposition", "Inline")
    Response.BinaryWrite(MemStream.GetBuffer())
    Response.Flush
    Response.End

修改 此外,我认为您可能无法正确创建PDF文档 - 请参阅示例this question。我认为您可能错过的重要步骤是在尝试从中读取doc.Close之前关闭文档(即,在您添加内容的循环之后立即)。

答案 1 :(得分:2)

我遇到了同样的问题。尝试了所有的建议。直到最后才尝试指定内容长度并且瞧不起!

希望这个回复在1年后有所帮助。

添加此代码:

Response.AddHeader(“Content-Length”,MemStream.GetBuffer()。Length)

答案 2 :(得分:0)

您可以尝试将content-length标头设置为等于MemoryStream的大小。另外,在调用Response.BinaryWrite后尝试调用Response.Flush。