pyPDF2 merging error coercing to Unicode

693 views Asked by At

I'm trying to give pypdf some pdfs to merge and it throws a coercing to Unicode error. My code is

from PyPDF2 import PdfFileMerger, PdfFileReader

import pdfcrowd
from django.http import HttpResponse

def generate_pdf(request):
    list_of_pages = ["http://127.0.0.1:8000/page"+x+"/" for x in list("1234567")]
    pdfs = ["page"+x+".pdf" for x in list("1234567")]
    merger = PdfFileMerger()
    client = pdfcrowd.Client("username", "password")

    # set HTTP response headers
    response = HttpResponse(mimetype="application/pdf")
    response["Cache-Control"] = "max-age=0"
    response["Accept-Ranges"] = "none"
    response["Content-Disposition"] = "attachment; filename=google_com.pdf"

    for num in list("1234567"):
        html = "http://wilderness.maasaimara.com/page{0}/".format(num)
        pdf = "page{0}.pdf".format(num)
        pdf_file = client.convertURI(html)
        local = open(pdf,'w')
        local.write(pdf_file)
        local.close()
        merger.append(PdfFileReader(file(local, 'rb')))


    merger.write("document-output.pdf")
    response.write(merger)
    return response

I get the following error in Django

TypeError at /generate/

coercing to Unicode: need string or buffer, file found

Request Method:     GET
Request URL:    http://wilderness.maasaimara.com/generate/
Django Version:     1.5.11
Exception Type:     TypeError
Exception Value:    

coercing to Unicode: need string or buffer, file found

Exception Location:     /home/africa/webapps/wilderness/wilderness/wilderness/views.py in generate_pdf, line 25
Python Executable:  /usr/local/bin/python
Python Version:     2.7.8
Python Path:    

   ['/home/africa/webapps/wilderness',
   '/home/africa/webapps/wilderness/wilderness',
   '/home/africa/webapps/wilderness/lib/python2.7',
   '/home/africa/lib/python2.7/pip-1.2.1-py2.7.egg',
   '/home/africa/lib/python2.7',
   '/home/africa/lib/python2.7/site-packages',
   '/usr/local/lib/python27.zip',
   '/usr/local/lib/python2.7',
   '/usr/local/lib/python2.7/plat-linux2',
   '/usr/local/lib/python2.7/lib-tk',
   '/usr/local/lib/python2.7/lib-old',
   '/usr/local/lib/python2.7/lib-dynload',
   '/home/africa/.local/lib/python2.7/site-packages',
   '/usr/local/lib/python2.7/site-packages',
   '/usr/local/lib/python2.7/site-packages/PIL']

   Server time:     Sat, 22 Nov 2014 16:29:02 +0000
1

There are 1 answers

0
Michael Meinel On

As far as I can see,

merger.append(PdfFileReader(file(local, 'rb')))

should be

merger.append(PdfFileReader(open(pdf, 'rb'))

as local is a file handle that was already closed. But what you really want to do is to open the just written local file whose name is stored in pdf.

However, I did not try yet.