1

I am looking for creating internal APIs for me that would generate pdfs as API call and use chalice to deploy it as serverless. So far I have code that I am stuck with 500 error that I can not debug:

from chalice import Chalice, Response

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.lib.pagesizes import landscape

from io import BytesIO

app = Chalice( app_name = 'printago' )


@app.route( '/' )
def index( ) :

    buff = BytesIO( )
    # p = canvas.Canvas( 'someName.pdf', pagesize = landscape( letter ) )
    p = canvas.Canvas( buff, pagesize = landscape( letter ) )

    p.setFont( 'Helvetica', 40, leading = None )
    p.drawCentredString( 415, 300, 'Hallo YOU' )
    p.showPage( )
    p.save( )

    pdf = buff.getvalue( )
    buff.close( )

    return Response( pdf, status_code = 200, headers = { 'Content-Type' : 'application/pdf' } )

What am I doing wrong?

I have virtual environment for this project, installed reportlab via pip in it, and after turning on debugging there is error Unable to import module

'app': No module named reportlab.pdfgen

And I was able to pass "No module" error by adding reportlab to requirments.txt file, however after this there is other error related to JSON serialization and utf-8

An error occurred during JSON serialization of response: 'utf8' codec can't decode byte 0x93 in position 10: invalid start byte

I would like to add that is working as expected when tested locally with command chalice local

bensiu
  • 24,660
  • 56
  • 77
  • 117

1 Answers1

0

We also got the can't decode byte 0x93 in position 10: invalid start byte error, which turned out to be a header put in the generated PDF itself by reportlab. The first two lines of the PDF when opened in vim look like this:

%PDF-1.4
%<93><8c><8b><9e> ReportLab Generated PDF document http://www.reportlab.com

Our workaround was to change the way that we send the PDF out to the client in our python-based cgi script:

import codecs
print(codecs.open("/full/path/to/some.pdf", "r", encoding="utf-8", errors="ignore").read())

and the key there was the errors="ignore" ... which is ugly and bad and we've made this a priority to replace.

  • Who are "we"? Are you together with OP? – Elis Byberi Nov 08 '17 at 18:54
  • Not with the OP, no. We are staff at a research university supporting a research group that have a python-based cgi workflow hosted with us. We upgraded the Apache httpd and python they (the research group) use, which caused the PDF problem to be user-visible, and in chasing down that problem we found this question. – Cristóbal Palmer Nov 08 '17 at 19:14