[GO] A story about converting HTML to PDF with WeasyPrint + matplotlib and embedding graphs [Beginners learn python with a reference book]

Introduction

Using Takashi Otaka, "Learning by Moving! Introduction to Python Django Development" I'm a beginner who started learning python and Django.

I've been studying programming for about 4 months using ruby / rails, When I changed jobs as an engineer, I decided to use python, so I started studying with this book in my hand.

Since I am a de-class amateur, I would be very grateful if you could comment on supplements and suggestions.

Overview

I want to convert an HTML page to PDF and display it. I also want to create a graph with'matplotlib'and put it in PDF as an image.

① HTML → PDF journey

HTML↓

from django.shortcuts import render

def html_view(request):
             .
             .
             .
  #Fill variables into context and pass to HTML
    context = {
        "hoge": hoge,
        "fuga": fuga,
    }
    return render(request, 'hogefuga.html', context)

PDF conversion ↓

from django.http import HttpResponse
from django.shortcuts import render
from weasyprint import HTML, CSS
from django.template.loader import get_template

def pdf_view(request):
             .
             .
             .
   #Specify template & pass variables
    html_template = get_template('hogefuga.html')
    html_str = html_template.render({
        "hoge": hoge,
        "fuga": fuga,
    }, request)

    #PDF conversion
    pdf_file = HTML(string=html_str, encoding='utf-8').write_pdf(
        stylesheets=[
       #WeasyPrint will not be applied unless you specify the CSS file here.
            CSS('./static/css/hogefuga.css'),
        ],
    )
    response = HttpResponse(pdf_file, content_type='application/pdf')
    response['Content-Disposition'] = 'filename="hogefuga.pdf"'
    return response

② Create a graph with matplotlib and display it in PDF

The wisdom of our ancestors is amazing. I managed to struggle so far ...

Now, let's create a graph as well.

from django.http import HttpRespons
from django.shortcuts import render
from weasyprint import HTML, CSS
from django.template.loader import get_template
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.use('Agg')

def pdf_graph_view(request):

    x = [1, 2, 3, 4, 5]
    y = [1, 2, 3, 4, 5]

    fig = plt.figure(figsize=(4.0, 3.0))
    ax = fig.add_subplot(111)
    ax.plot(x, y)
    plt.savefig('static/img/graph.png', format='png', dpi=200)
             .
             .
             .
Same as PDF code below

By the way, if the following description is not provided, an error will occur. I've been deprived of time by just this description ... Click here for the wisdom of the borrowed ancestor

mpl.use('Agg')

③ Image (graph) is not displayed in PDF

Well, it's over by writing the location of the image file in HTML.

hogefuga.html


<img src="{% static 'img/graph.png' %}">

However, the wholesaler does not wholesale it. For some reason, the image is not displayed in the PDF. Why.

Countermeasure ①

pdf_file = HTML(string=html_str, base_url=request.build_absolute_uri(), encoding='utf-8')

change to. Then, the graph is displayed, but the characters are garbled. It seems that the PC will finally be destroyed. goodbye Jobs.

Countermeasure ②

If the characters are garbled for the time being, There is no choice but to raise the priority of fonts by force. (Brain dead single cell)

hogefuga.css


font-family: 'msmincho'!important;

!! If you add important, the garbled characters will be solved safely. ~~ However, it is not a fundamental solution. Cover the ugly things. ~~

Finally

The ancestors are amazing. The technician is amazing. Longing for. It seems that it will take time to get out of the beginners. Studying every day, isn't it? Why are the characters garbled (CSS is not working)? I have to solve it.

Great reference article

Matplotlib reverse lookup memo (frame edition)Tips for drawing with matplotlib on the server side -Easy PDF output with Django2.0 + WeasyPrint · PDF output using Weasyprint not showing images (Django)

Recommended Posts

A story about converting HTML to PDF with WeasyPrint + matplotlib and embedding graphs [Beginners learn python with a reference book]
A story about adding a REST API to a daemon made with Python
A story that I did not know how to load a mixin when making a front with the django app [Beginners learn python with a reference book in one hand]
[Small story] How to save matplotlib graphs in a batch with Jupyter
A story about Python pop and append
[Python] How to draw multiple graphs with Matplotlib
A story about modifying Python and adding functions
A story about how Windows 10 users created an environment to use OpenCV3 with Python 3.5
A story that I wanted to display the division result (%) on HTML with an application using django [Beginner learns python with a reference book in one hand]
[Python] How to draw a line graph with Matplotlib
A story about trying a (Golang +) Python monorepo with Bazel
[Python] How to create a 2D histogram with Matplotlib
[Python] How to draw a scatter plot with Matplotlib
[Python] Road to a snake charmer (5) Play with Matplotlib
A story that I wanted to do a function like before_action used in rails with django [Beginner learns python with a reference book]
[Note] A story about trying to override a class method with two underscores in Python 3 series.
I want to make a voice changer using Python and SPTK with reference to a famous site
From a book that programmers can learn ... (Python): About sorting
A story about how to specify a relative path in python.
Probably the easiest way to create a pdf with Python3
Experiment to make a self-catering PDF for Kindle with Python
Let's create a PRML diagram with Python, Numpy and matplotlib.
How to learn TensorFlow for liberal arts and Python beginners
A story about an amateur making a breakout with python (kivy) ②
Try to bring up a subwindow with PyQt5 and Python
A story about how to deal with the CORS problem
A story about an amateur making a breakout with python (kivy) ①
Dynamically generate graphs with matplotlib and embed in PDF with reporlab
A story about trying to implement a private variable in Python.
A story about a python beginner stuck with No module named'http.server'
A story about everything from data collection to AI development and Web application release in Python (3. AI development)
Python # About reference and copy
I tried to solve the ant book beginner's edition with python
How to make a surveillance camera (Security Camera) with Opencv and Python
I tried to make a periodical process with Selenium and Python
A story about developing a soft type with Firestore + Python + OpenAPI + Typescript
A story about trying to run multiple python versions (Mac edition)
[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
Pass a list by reference from Python to C ++ with pybind11
I ran GhostScript with python, split the PDF into pages, and converted it to a JPEG image.
A story about someone who wanted to import django from a python interactive shell and save things to a DB
I used Python with the minimum necessary knowledge, but I bought a reference book and studied again to summarize what I learned new and what I found useful.