tasif99
tasif99

Reputation: 65

pdf file generated using reportlab , getting saved as plain text

this is the first time i'm using reportlab. i copied the exact code from django documentation. https://docs.djangoproject.com/en/2.1/howto/outputting-pdf/. When i save the file its getting saved as plain text document (text/plain), the name remains the same hello.pdf and there is no text.

p = canvas.Canvas(buffer) in this line if i write the name of file 'hello.pdf' instead of buffer and remove the buffer from the fileresponse method it works and automatically gets saved as pdf file, but i cannot prompt the user to save the file and there are two pages in the pdf.

def some_view(request):
    # Create a file-like buffer to receive PDF data.
    buffer = io.BytesIO()

    # Create the PDF object, using the buffer as its "file."
    p = canvas.Canvas(buffer)

    # Draw things on the PDF. Here's where the PDF generation happens.
    # See the ReportLab documentation for the full list of functionality.
    p.drawString(100, 100, "Hello world.")

    # Close the PDF object cleanly, and we're done.
    p.showPage()
    p.save()

    # FileResponse sets the Content-Disposition header so that browsers
    # present the option to save the file.
    return FileResponse(buffer, as_attachment=True, filename='hello.pdf')

i tried specifying the content_type='application/pdf' in the code provided by django documentation but it still gets saved as plain text document. i'm guessing the File response cannot guess the type of file from the filename argument as mentioned in django documentation.

class FileResponse(open_file, as_attachment=False, filename='', **kwargs) if open_file doesn’t have a name or if the name of open_file isn’t appropriate, provide a custom file name using the filename parameter.

The as_attachment and filename keywords argument were added. Also, FileResponse sets the Contentheaders if it can guess them.

If i use the code from 2.0 django documentation it works. is there a bug in the latest django documentation 2.1? i installed all the dependencies according to this official link https://bitbucket.org/rptlab/reportlab/src/927995d54048767531a4ad4a0648e46064b0c4c7/README.txt?at=default&fileviewer=file-view-default environment- ubuntu 18.04lts , pycharm, Python 3.5.6, reportlab 3.5.12.

Upvotes: 0

Views: 1811

Answers (1)

cuto
cuto

Reputation: 121

You need to reset the buffer position to start before returning the FileResponse:

buffer.seek(io.SEEK_SET)

Otherwise the buffer will be read starting at its end (after the canvas was written) and an empty file is returned.

This is missing in the documentation since v2.1 and should be fixed.

Upvotes: 1

Related Questions