Home > database >  Classic ASP: how to show a PDF that is returned by Json
Classic ASP: how to show a PDF that is returned by Json

Time:02-10

I want to let the users download a PDF that is received back from a API after a Json request. When a user opens ShowPDF.asp the request happens and there opens a new window where the PDF is downloaded.

The problem is that the downloaded PDF is not valid; it says that the file can't be opened. The size of the file is around 500kb, so there is something in it. When I make the same request in Postman I see the content from the PDF file in the result screen and when I save it it's also around 500kb.

What is received back from the request is the actual content of the PDF file:

%PDF-1.4
3 0 obj
<</Type /Page
/Parent 1 0 R

The code:

PDF.asp

Response.AddHeader "Content-Disposition","attachment; filename=name.pdf
Response.ContentType = "application/pdf"    

PDFcontent = GetPDF(strToken) 
response.write PDFcontent

GetPDF(sToken)

public function GetPDF(sToken)
    Set xmlhttp = CreateObject("Msxml2.ServerXMLHTTP.6.0")
    xmlhttp.open "GET", "www.fakeUrl.com/rest/download", false
    xmlhttp.setRequestHeader "Authorization", "Bearer "& sToken         
    xmlhttp.setRequestHeader "Content-Type", "application/json; charset=UTF-8" 
    xmlhttp.send ""
    GetPDF = xmlhttp.responseText
end function

ShowPDF.asp

window.open('PDF.asp');

What am I missing here?

CodePudding user response:

The problem is you are treating the download of a binary file as if it was text. But luckily the fix isn't too difficult.

Adjust the

GetPDF = xmlhttp.responseText

to

GetPDF = xmlhttp.responseBody

Then change

response.write PDFcontent

to

Response.BinaryWrite PDFcontent

Useful Links

  • Related