簡體   English   中英

使用reportlab生成pdf時解決IOError並生成二維碼圖像

[英]Solving IOError while generating a pdf using reportlab and generated qr code image

我正在嘗試從文本中生成二維碼,然后插入到 reportlab pdf 中。

我的代碼:

def qr_code_as_image(text):
    from io import BytesIO
    print("In show_qr")
    img = generate_qr_code(text)
    print(img, type(img))
    i = Image(img)
    print(i, type(i))
    return i

def add_patient_header_with_qr(self):
    line1 = ("Name", self.linkedcustomer.name,
             "Age", self.linkedcustomer.age())
    line2 = ("MRD No.", self.linkedcustomer.cstid,
             "Date", self.prescription_time)
    line3 = ("No.", "#", "Doctor", self.doc.name)
    datatb = [line1, line2, line3]
    patientdetailstable = Table(datatb)
    patientdetailstable.setStyle(self.patientdetails_style)
    col1 = patientdetailstable

    checkin_url = reverse('clinicemr', args=[self.checkin.checkinno])
    qr_image = qr_code_as_image(checkin_url)
    qr_image.hAlign = 'LEFT'

    col2 = Table([[qr_image]])

    tblrow1 = Table([[col1, col2]], colWidths=None)
    tblrow1.setStyle(self.table_left_top_align)
    self.elements.append(tblrow1)

def final_generate(self, footer_content, action=None):
        with NamedTemporaryFile(mode='w+b') as temp:
            from django.http import FileResponse, Http404
            from functools import partial

            # use the temp file
            cmd = "cat " + str(temp.name)
            print(os.system(cmd))
            print(footer_content, type(footer_content))
            doc = SimpleDocTemplate(
                temp.name,
                pagesize=A4,
                rightMargin=20,
                leftMargin=20,
                topMargin=20,
                bottomMargin=80,
                allowSplitting=1,
                title="Prescription",
                author="System.com")
            frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height,
                          id='normal')
            template = PageTemplate(
                id='test',
                frames=frame,
                onPage=partial(footer, content=footer_content)
            )

            doc.addPageTemplates([template])
            doc.build(self.elements,
                      onFirstPage=partial(footer, content=footer_content),
                      onLaterPages=partial(footer, content=footer_content)
                      )

            print(f'Generated {temp.name}')

我得到以下 output:

2020-11-29 13: 06: 33, 915 django.request ERROR    Internal Server Error: / clinic/presc/k-0NGpApcg
Traceback(most recent call last):
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/lib/utils.py", line 655, in open_for_read
    return open_for_read_by_name(name, mode)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/lib/utils.py", line 599, in open_for_read_by_name
    return open(name, mode)
ValueError: embedded null byte

During handling of the above exception, another exception occurred:

Traceback(most recent call last):
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/lib/utils.py", line 658, in open_for_read
    return getBytesIO(datareader(name) if name[:5].lower() == 'data:' else urlopen(name).read())
File "/usr/lib/python3.6/urllib/request.py", line 223, in urlopen
    return opener.open(url, data, timeout)
File "/usr/lib/python3.6/urllib/request.py", line 517, in open
    req.timeout = timeout
AttributeError: 'bytes' object has no attribute 'timeout'

During handling of the above exception, another exception occurred:

Traceback(most recent call last):
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/joel/myappointments/clinic/views.py", line 6879, in GoGetPrescription
    clinicobj = clinicobj,
File "/home/joel/myappointments/clinic/views.py", line 16222, in PDFPrescriptions
    return prescription.generate_pdf(action=action, rating=True)
File "/home/joel/myappointments/clinic/views.py", line 15415, in generate_pdf
    return self.final_generate(footer_content, action=action)
File "/home/joel/myappointments/clinic/views.py", line 15447, in final_generate
    onLaterPages = partial(footer, content=footer_content)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/doctemplate.py", line 1291, in build
    BaseDocTemplate.build(self, flowables, canvasmaker=canvasmaker)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/doctemplate.py", line 1056, in build
    self.handle_flowable(flowables)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/doctemplate.py", line 912, in handle_flowable
    if frame.add(f, canv, trySplit=self.allowSplitting):
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/frames.py", line 174, in _add
    w, h = flowable.wrap(aW, h)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/tables.py", line 1206, in wrap
    self._calc(availWidth, availHeight)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/tables.py", line 641, in _calc
    W = self._calcPreliminaryWidths(availWidth)  # widths
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/tables.py", line 754, in _calcPreliminaryWidths
    new = elementWidth(value, style) or 0
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/tables.py", line 518, in _elementWidth
    w = v.minWidth()  # should be all flowables
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/tables.py", line 873, in minWidth
    style.leftPadding+style.rightPadding)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/tables.py", line 512, in _elementWidth
    if hasattr(v, 'drawWidth') and isinstance(v.drawWidth, (int, float)): return v.drawWidth
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/flowables.py", line 494, in __getattr__
    self._setup_inner()
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/flowables.py", line 455, in _setup_inner
    img=self._img
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/flowables.py", line 488, in __getattr__
    self._img=ImageReader(self._file)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/lib/utils.py", line 813, in __init__
    annotateException('\nfileName=%r identity=%s' %
                      (fileName, self.identity()))
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/lib/utils.py", line 1394, in annotateException
    rl_reraise(t, v, b)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/lib/utils.py", line 147, in rl_reraise
    raise v
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/lib/utils.py", line 777, in __init__
    self.fp=open_for_read(fileName, 'b')
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/lib/utils.py", line 660, in open_for_read
    raise IOError('Cannot open resource "%s"' % name)
OSError: Cannot open resource "b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\xd2\x00\x00\x00\xd2\x01\x00\x00\x00\x00\x17\xe2\xa3\xef\x00\x00\x01$IDATx\x9c\xed\x98An\xc4 \x10\x04k\x16\xdf\xf1\x8f\xe0gyS~\x80\x9f\x92\x1f\xe0;\xab\xde\x03\xc6\xeb\x1c"\xe5d\xd0\xda\x1c\xd0 @\xcbRk4\x9e\xee\x01\xb6\xe5$\xa9 \xe5v\xc3\x83\xbf\xd7\xe7cA\x92\x94\xc1"N\x16k\x86\xa4\xd1x\x9e\x8bA\xc8@\xc8NJ\xbe e\'\xc0]</\x07\xccb\xdb\xfas\xe9\x8eM\xefP\xac\x13b\xed\xc6e0\xccKJ\x80\xd9\xecd\x11\x90T\xfap\x19\x06\xdb\x97\x13!;\xd5v\xd3\x87\xcbH\xd8\xa4=\x14\xeb\xd3\xc0\xb7\x9be$\x9e\x9d\xea\xa5V\x89/u\xab\xca\x94F\xe2yz^\x94\xbc\x04^\xda\x8ePe{,\x9e}\xeaE\xe9\xed\xe6\xe0\xae\x17\xa0\xa6#\xf9\xb2\x9b;\xe9\x1f\xdf}:\xc6A\x80v=\xbau\xba\xd5\xcb\xef_hk7#\xf1\xec\xee_\xf0\x92\x94\x9d.\xde_\xda<\xdd\xde\x19R\xb5\xbfW\xcf\xcb\x03V3\x8b\xb4\x911\xfc\x98\xd9\xd7\xe5\xfb\xcb\x11[f\'\x96\x19\x80\xa7\x8d\xcb\xf3\x0c\xec0O\x13\xbe\xa7b\xf8\x0c\x8b\xdd\xben\xef/\xc0\xf68\xb5E#\xf1\xec\xaaGU\xac\x9d\x08\xba\xba\xdf}\x01<\xf7\xbf\x8cN\xed-\x8a\x00\x00\x00\x00IEND\xaeB`\x82'"
fileName=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\xd2\x00\x00\x00\xd2\x01\x00\x00\x00\x00\x17\xe2\xa3\xef\x00\x00\x01$IDATx\x9c\xed\x98An\xc4 \x10\x04k\x16\xdf\xf1\x8f\xe0gyS~\x80\x9f\x92\x1f\xe0;\xab\xde\x03\xc6\xeb\x1c"\xe5d\xd0\xda\x1c\xd0@\xcbRk4\x9e\xee\x01\xb6\xe5$\xa9 \xe5v\xc3\x83\xbf\xd7\xe7cA\x92\x94\xc1"N\x16k\x86\xa4\xd1x\x9e\x8bA\xc8@\xc8NJ\xbe e\'\xc0]</\x07\xccb\xdb\xfas\xe9\x8eM\xefP\xac\x13b\xed\xc6e0\xccKJ\x80\xd9\xecd\x11\x90T\xfap\x19\x06\xdb\x97\x13!;\xd5v\xd3\x87\xcbH\xd8\xa4=\x14\xeb\xd3\xc0\xb7\x9be$\x9e\x9d\xea\xa5V\x89/u\xab\xca\x94F\xe2yz^\x94\xbc\x04^\xda\x8ePe{,\x9e}\xeaE\xe9\xed\xe6\xe0\xae\x17\xa0\xa6#\xf9\xb2\x9b;\xe9\x1f\xdf}:\xc6A\x80v=\xbau\xba\xd5\xcb\xef_hk7#\xf1\xec\xee_\xf0\x92\x94\x9d.\xde_\xda<\xdd\xde\x19R\xb5\xbfW\xcf\xcb\x03V3\x8b\xb4\x911\xfc\x98\xd9\xd7\xe5\xfb\xcb\x11[f\'\x96\x19\x80\xa7\x8d\xcb\xf3\x0c\xec0O\x13\xbe\xa7b\xf8\x0c\x8b\xdd\xben\xef/\xc0\xf68\xb5E#\xf1\xec\xaaGU\xac\x9d\x08\xba\xba\xdf}\x01<\xf7\xbf\x8cN\xed-\x8a\x00\x00\x00\x00IEND\xaeB`\x82' identity=[ImageReader@0x7f1e0987ecf8 filename=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\xd2\x00\x00\x00\xd2\x01\x00\x00\x00\x00\x17\xe2\xa3\xef\x00\x00\x01$IDATx\x9c\xed\x98An\xc4 \x10\x04k\x16\xdf\xf1\x8f\xe0gyS~\x80\x9f\x92\x1f\xe0;\xab\xde\x03\xc6\xeb\x1c"\xe5d\xd0\xda\x1c\xd0@\xcbRk4\x9e\xee\x01\xb6\xe5$\xa9 \xe5v\xc3\x83\xbf\xd7\xe7cA\x92\x94\xc1"N\x16k\x86\xa4\xd1x\x9e\x8bA\xc8@\xc8NJ\xbe e\'\xc0]</\x07\xccb\xdb\xfas\xe9\x8eM\xefP\xac\x13b\xed\xc6e0\xccKJ\x80\xd9\xecd\x11\x90T\xfap\x19\x06\xdb\x97\x13!;\xd5v\xd3\x87\xcbH\xd8\xa4=\x14\xeb\xd3\xc0\xb7\x9be$\x9e\x9d\xea\xa5V\x89/u\xab\xca\x94F\xe2yz^\x94\xbc\x04^\xda\x8ePe{,\x9e}\xeaE\xe9\xed\xe6\xe0\xae\x17\xa0\xa6#\xf9\xb2\x9b;\xe9\x1f\xdf}:\xc6A\x80v=\xbau\xba\xd5\xcb\xef_hk7#\xf1\xec\xee_\xf0\x92\x94\x9d.\xde_\xda<\xdd\xde\x19R\xb5\xbfW\xcf\xcb\x03V3\x8b\xb4\x911\xfc\x98\xd9\xd7\xe5\xfb\xcb\x11[f\'\x96\x19\x80\xa7\x8d\xcb\xf3\x0c\xec0O\x13\xbe\xa7b\xf8\x0c\x8b\xdd\xben\xef/\xc0\xf68\xb5E#\xf1\xec\xaaGU\xac\x9d\x08\xba\xba\xdf}\x01<\xf7\xbf\x8cN\xed-\x8a\x00\x00\x00\x00IEND\xaeB`\x82']

從錯誤中,它似乎在獲取圖像文件的名稱時出錯。 但是沒有文件。 圖像是從 BytesIO 生成的。

您沒有向我們展示的generate_qr_code function 沒有返回 BytesIO object。 它返回 PNG 圖像的原始字節。 當您print(img, type(img))時,它告訴您它是“字節”類型,對嗎? 那是一串字節,而不是 BytesIO object。 如果您將這些字節包裝到 BytesIO object 中,那么 reportlab Image構造函數將能夠處理它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM