Search code examples
pythonpython-3.xpdfcgi

python3.x: display pdf in browser with cgi


I am upgrading some code from python2 to python3. I have the following cgi script to display a pdf in the browser. It works fine in python2, but doesn't work in python3. In python 3, there is no server error, but rather I get an error from the browser which says "Failed to load PDF document."

I believe the problem has to do with the encoding, but I am at a loss after searching for a few hours. The current CGI script is here:

#!/usr/local/bin/python3.7

filename='file.pdf'
file = open(filename,'rb')
fileData=file.read()
file.close() 

print('Content-Disposition: inline; filename="out.pdf"')
print('Content-type: application/pdf')
print('')
print(fileData)

Solution

  • The following code works for me:

    #!/usr/local/bin/python3.7
    
    filename='file.pdf'
    file = open(filename,'rb')
    fileData=file.read()
    file.close() 
    
    print('Content-Disposition: inline; filename="out.pdf"')
    print('Content-type: application/pdf')
    print('')
    sys.stdout.flush()
    sys.stdout.buffer.write(fileData)