Forcing a PDF to download in browser and Adobe error
A while back I had a request to offer two options to access a PDF file from a SharePoint site. One was to allow the PDF to open in the browser like normal and the second was to force the download prompt to the user. The second one was a little more tricky and I finally found a way to send the file in the Reponse in code and send it as an attachment and thus prompt the user to download the file. The code for that looks like this:
'Create an array that contains the contents of the file.
Dim mystream As Byte() = file.OpenBinary
'Clear the Response headers and set the response to be an attachment
Response.ClearHeaders()
Response.ContentType = "APPLICATION/PDF"
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=" & file.Name) Response.BinaryWrite(mystream)
This seemed to do the trick until the other day when I had a client call and say that when they used the download mechanism to open the file and save it to their desktop they were getting an error in Adobe Reader 7. I tested it out and found the same issue when I downloaded the file. The error said that the file was corrupted and that reader could not repair it. I could open the file just fine using Adobe Reader 8.
The solution to this issue turns out to be that I missed a line of code in the above block that must leave the PDF file unwritten and Adobe Reader 8 can repair the file but 7 can't. I found a post by Rahul that described 4 different ways to download a PDF file. In one of the ways was the way I had used to force the download. I noticed a line that said Response. End().
I added this line to my code and suddenly the PDF files were no longer corrupt and could be opened in Adobe 7 as well as 8.
The final code ended up looking like this:
'Create an array that contains the contents of the file.
Dim mystream As Byte() = file.OpenBinary
'Clear the Response headers and set the response to be an attachment
Response.ClearHeaders()
Response.ContentType = "APPLICATION/PDF"
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=" & file.Name) Response.BinaryWrite(mystream)
Response.End()
The nice thing about the above code is that the file.OpenBinary method is an SPFile method that opens a file from SharePoint as a byte array. It works really well for items like this.
Labels: Adobe error when forcing PDF download, File is corrupt and can't be repaired in Adobe Reader
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home