1. 程式人生 > >xhtml2pdf如何支援中文

xhtml2pdf如何支援中文

         這段時間在做一個圖片PDF的專案, 需要把網頁轉換成PDF, 找到了python的xhtml2pdf這個庫, 個方面都滿意,只是對中文的支援不好, html上的中文轉換成PDF後都成了亂碼, 貌似中文網站都沒有找到合適的解決辦法, 只能求助於萬能的google, 果然不負我望, 廢話不多說, 上程式碼:

django程式碼

class GeneratePdf(View):
    def get(self, request, *args, **kwargs):
        # Prepare context
        data = {'today': datetime.date.today()}
        template = get_template('pdf.html')
        html = template.render(Context(data))

        io = StringIO.StringIO()
        pisa.CreatePDF(html, dest=io, link_callback=link_callback)

        io.seek(0)
        pdf = io.read()
        io.close()            # Don't forget to close the file handle
        return HttpResponse(pdf, content_type='application/pdf')

django template程式碼

 {% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>貓</title>
    <link href="{% static "css/pdf.css" %}" rel="stylesheet">
</head>
<style>
    @font-face {
        font-family: STSong;
        src: url('{% static 'fonts/STSong.TTF' %}');
    }

    h3 {
        font-family: STSong;
    }
.image .image-text { float: left; width: 50%; margin: 30px; } .imageFrame{ margin: 20px; } </style> <body> <h3>日期: {{ today }}</h3> <hr/> <div class="imageContent" > <div style="float: left; width: 100%; text-align: center"> <img src="{% static "img/cat_3.jpg" %}" width="300" height="200"> <img src="{% static "img/cat.jpg" %}" width="300" height="200"> </div> <div style="float: left; width: 100%; text-align: center"> <img src="{% static "img/cat.jpg" %}" width="300" height="200"> <img src="{% static "img/cat_3.jpg" %}" width="300" height="200"> </div> <div style="float: left; width: 100%; text-align: center"> <img src="{% static "img/cat_3.jpg" %}" width="300" height="200"> <img src="{% static "img/cat.jpg" %}" width="300" height="200"> </div> </div> </body> </html>

其實很簡單, 下個支援中文的字型檔案, 比如這裡的STSong.ttf, 按模板中標註的地方寫就可以了
 @font-face {
        font-family: STSong;
        src: url('{% static 'fonts/STSong.TTF' %}');
    }

    h3 {
        font-family: STSong;
    }

補充一下:

這段樣式程式碼放到單獨的css檔案中好像不好使, 直接嵌在模板檔案中就可以, 這個一直忙沒時間去研究, 後面有時間看看