1

I have a django web application which creates an image on the POST call and I want this image to be inserted into a word document that the user can download.

Currently the function that creates the image is something like this:

def create_image():
    results = {}
    plot, axes = plt.subplots(num_plots, 1,figsize=(6, 4))
   # code to create figure here
    fig = plot.get_figure()
    img_in_memory = BytesIO()
    fig.savefig(img_in_memory, format='png')
    image = base64.b64encode(img_in_memory.getvalue())
    image = image.decode(settings.DEFAULT_CHARSET)
    plot.get_figure().clf()
    results['image'] = image
    results['results_intro'] = 'Report introduction'
    return results

And the function that creates the document is something like:

def create_doc(results):
    docx_title = "report.docx"
    document = Document()
    section = document.sections[0]
    header = section.header
    paragraph = header.paragraphs[0]
    document.add_paragraph()
    paragraph = document.add_paragraph("%s" % date.today().strftime('%B %d, %Y'))
    paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    document.add_paragraph()
    
    document.add_paragraph('Start Report,')
    run = document.add_paragraph().add_run('RE: Name DD/MMM/YYYY')
    run.font.bold = True
    run.font.underline = True

    document.add_paragraph(results['results_intro'])
    document.add_paragraph()

    document.add_picture(results['score_image'])

    f = BytesIO()
    document.save(f)
    length = f.tell()
    f.seek(0)
    response = HttpResponse(
        f.getvalue(),
        content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    )
    response['Content-Disposition'] = 'attachment; filename=' + docx_title
    response['Content-Length'] = length
    return response

Currently the image is just displayed as a long string in the word document - how do I get it to be displayed as an image?

RobMcC
  • 392
  • 2
  • 7
  • 20

0 Answers0