1

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?

user692942
  • 16,398
  • 7
  • 76
  • 175
flyingmath
  • 13
  • 2
  • Seems like you should be returning the binary data, not `ResponseText`. Use [`xmlhttp.ResponseBody`](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/ms753682(v=vs.85)) instead and use [`Response.BinaryWrite()`](https://learn.microsoft.com/en-us/previous-versions/iis/6.0-sdk/ms524318%28v%3dvs.90%29) to write the raw binary response. – user692942 Feb 09 '22 at 15:59
  • 1
    Yes, that did it. Thank you very much! – flyingmath Feb 09 '22 at 16:12

1 Answers1

0

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

user692942
  • 16,398
  • 7
  • 76
  • 175