html - Django 将 HTML 渲染为 PDF
问题描述
我正在尝试将 html 文件渲染为 pdf,但是当 pdf 功能正常工作时,渲染工作正常,没有 css。它还呈现整个页面,我如何呈现 html 页面的特定部分。我正在使用 xhtml2pdf。
视图.py 文件
from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template
from django.views import View
from xhtml2pdf import pisa
def render_to_pdf(template_src, context_dict={}):
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
data = {
"company": "Name",
}
#Opens up page as PDF
class ViewPDF(View):
def get(self, request, *args, **kwargs):
pdf = render_to_pdf('listings/listing.html', data)
return HttpResponse(pdf, content_type='application/pdf')
urls.py 文件
path('pdf_view/', views.ViewPDF.as_view(), name="pdf_view"),
.html 文件
<section class="p0">
<div class="container">
<div class="row listing_single_row">
<div class="col-sm-6 col-lg-7 col-xl-8">
<div class="single_property_title">
<a href="{{ listing.photo_1.url }}" class="upload_btn popup-img"><span class="flaticon-photo-camera"></span> View Photos</a>
</div>
</div>
<div class="col-sm-6 col-lg-5 col-xl-4">
<div class="single_property_social_share">
<div class="spss style2 mt10 text-right tal-400">
<ul class="mb0">
<li class="list-inline-item"><a href="#"><span class="flaticon-transfer-1"></span></a></li>
<li class="list-inline-item"><a href="#"><span class="flaticon-heart"></span></a></li>
<li class="list-inline-item"><a href="#"><span class="flaticon-share"></span></a></li>
<li class="list-inline-item"><a href="{% url 'pdf_view' %}"><span class="flaticon-printer"></span></a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</section>
谢谢!
解决方案
Ans 1.) 如果你想给你的 html 设置样式而不是直接在标签中使用 style 属性。如果您创建类并使用模板继承,那么它将无法正常工作,因为它是独立的 html。直接在html中使用样式。Ans 2.)如果您想要 pdf 中的特定 html 部分而不是在 html 中编写您需要的内容或使用 style = “display: none ;” 在您不想要的 pdf 部分上。
推荐阅读
- redis - 谷歌云运行 redis 客户端失去与实例的连接
- vue.js - 切换语言时 Nuxt i18n 无法正确翻译
- angular - 在 Angular 编辑器中使用时,HTML 代码在 kolkov/angular-editor 中不起作用
- windows-10 - 无法安装作曲家。任何建议将不胜感激
- python - Unexpected line in the seaborn bar plot
- reactjs - React Jest TypeError:无法读取未定义的属性“baseUrl”
- angularjs - 如何测试用 mixin 重写的 FullCalendar 函数
- c# - 在 API 中加载 PDF 后释放内存
- apache-spark - 在 Pyspark 的新列中添加与特定列值对应的多个列值
- ruby-on-rails - Ruby on rails:如何设置内联字符串翻译(无需更改 config/locales/*.yml)