Returning PDF response

Topics: Developer Forum
Coordinator
Apr 27, 2015 at 9:24 PM
Edited Apr 27, 2015 at 9:49 PM
I have a PDF file I want to return as the result of a REST call in AVFP. I know I could do oResponse.Redirect("http://server/folder/file.pdf") but I don't want to return a link to the file but the actual PDF output directly to the browser.

My current code looks like this:
  LOCAL oFSO,oFile
  oFSO = CREATEOBJECT("Scripting.FileSystemObject")
  oFile = oFSO.getFile(pcFileName)
  oResponse.Clear()
  oResponse.Buffer = .F.
  oResponse.contentType = "application/pdf"
  oResponse.AddHeader("Pragma","public")
  oResponse.AddHeader("Cache-Control","no-cache")
  oResponse.AddHeader("Accept-Ranges","bytes")    
  oResponse.AddHeader("Content-Type","application/pdf")
  oResponse.AddHeader("Content-Length",ALLTRIM(STR(oFile.Size)))  
  oResponse.AddHeader("Content-Disposition", [attachment; filename=] + JUSTFNAME(pcFileName))
  oResponse.AddHeader("Content-Transfer-Encoding","binary")
  oResponse.BinaryWrite(FILETOSTR(pcFileName))
  oResponse.End()
  oResponse.Flush()
This causes the browser to download the file. The downloaded file has the same size of the original PDF file, but is not a valid PDF file. If I change "attachment" for "inline", then the browser tries to show the PDF unsuccessfully.

I also tried using oResponse.transmitFile(), oResponse.Write() and oResponse.OutputStream.Write(). In all these cases, the browser fails with a "time out" error.

Any ideas?


Victor Espina
Coordinator
Apr 27, 2015 at 9:45 PM
The problem is caused because, somehow, the data received at the browser is arriving as double-byte stream. If I request the PDF file directly, I get a single-byte stream. I can't find what is causing this. :(

Victor
Coordinator
Apr 28, 2015 at 12:32 AM
Edited Apr 28, 2015 at 12:33 AM
Solved!!

All I needed to do was to convert file data to binary:
oResponse.BinaryWrite(CREATEBINARY(FILETOSTR(pcFileName)))
Changing Content-Disposition from "attachment" to "inline" causes the PDF to be rendered instead of being downloaded.


Victor Espina