在pdf weasyprint中附加img文件 [英] attach img file in pdf weasyprint
本文介绍了在pdf weasyprint中附加img文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要帮助在pdfs中附加img文件。我们使用WeasyPrint库从html生成pdf。
在html中像这样连接img文件
<img src="1.png" alt="">
<img src="2.png" alt="">
<img src="3.png" alt="">
但它不起作用。我没有看到图像。
推荐答案
图片文件路径使用静电
{% load static %}
<img src="{% static 'images/static.jpg' %}" alt="">
并在views.py的HTML类中传递base_url
pdf_file = HTML(string=rendered_html, base_url=request.build_absolute_uri())
HTML文件
<!DOCTYPE html>
<html lang="en">
{% load static %}
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div>
<img src="{% static 'images/static.jpg' %}" alt="">
</div>
</body>
</html>
views.py
from django.template.loader import get_template
from weasyprint import HTML, CSS
from django.conf import settings
from django.http import HttpResponse
def generate_pdf(request):
html_template = get_template('latest/html_pdf.html')
user = request.user
rendered_html = html_template.render().encode(encoding="UTF-8")
pdf_file = HTML(string=rendered_html, base_url=request.build_absolute_uri()).write_pdf(stylesheets=[CSS(settings.STATIC_ROOT + '/css/generate_html.css')])
http_response = HttpResponse(pdf_file, content_type='application/pdf')
http_response['Content-Disposition'] = 'filename="generate_html.pdf"'
return http_response
这篇关于在pdf weasyprint中附加img文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文