简体   繁体   English

Django HTML 和 CSS 呈现为 pdf

[英]Django HTML & CSS render to pdf

I'm trying to convert HTML & CSS into a pdf page using Django- weasyprint but I'm kind of stuck with their tutorial because I want the PDF to render the current page when the user clicks on the download button and the pdf downloads automatically with read-only privileges.我正在尝试使用 Django- weasyprint将 HTML 和 CSS 转换为 pdf 页面,但我有点坚持他们的教程,因为我希望当用户单击下载按钮并自动下载 pdf 时,PDF 呈现当前页面具有只读权限。 This whole process kind of feels painful to do.整个过程做起来有点痛苦。

Currently, weasyprint just converts a URL in Django to pdf, but I don't know how to set the button to look at the weasyprint view.目前,weasyprint 只是将 Django 中的 URL 转换为 pdf,但我不知道如何设置按钮以查看 weasyprint 视图。

Maybe I am looking past it and over complicating it, any assistance would be appreciated.也许我正在查看它并过度复杂化,任何帮助将不胜感激。

Weasyprints example code: Weasyprints 示例代码:

from django.conf import settings
from django.views.generic import DetailView

from django_weasyprint import WeasyTemplateResponseMixin
from django_weasyprint.views import CONTENT_TYPE_PNG


class MyModelView(DetailView):
    # vanilla Django DetailView
    model = MyModel
    template_name = 'mymodel.html'


class MyModelPrintView(WeasyTemplateResponseMixin, MyModelView):
    # output of MyModelView rendered as PDF with hardcoded CSS
    pdf_stylesheets = [
        settings.STATIC_ROOT + 'css/app.css',
    ]
    # show pdf in-line (default: True, show download dialog)
    pdf_attachment = False
    # suggested filename (is required for attachment!)
    pdf_filename = 'foo.pdf'


class MyModelImageView(WeasyTemplateResponseMixin, MyModelView):
    # generate a PNG image instead
    content_type = CONTENT_TYPE_PNG

    # dynamically generate filename
    def get_pdf_filename(self):
        return 'bar-{at}.pdf'.format(
            at=timezone.now().strftime('%Y%m%d-%H%M'),
        )

I made a virtual env on my pc and it's setup exactly like the example.我在我的电脑上制作了一个虚拟环境,它的设置与示例完全一样。 Currently using Boostrap 4.目前使用 Boostrap 4。

*Edit if there is a better way of doing it, you are more than welcome to share it :) *编辑,如果有更好的方法,欢迎分享:)

Also I want to target just the body tags so that it converts only that section to pdf and not the ENTIRE page.另外我想只定位正文标签,以便它只将该部分转换为 pdf 而不是整个页面。

The solution I used before this is: https://codepen.io/AshikNesin/pen/KzgeYX but this doesn't work very well.我之前使用的解决方案是: https : //codepen.io/AshikNesin/pen/KzgeYX但这不太好用。

*EDIT 2.0 *编辑2.0

I've moved on to js and I'm stuck with this script where it doesn't want to create the pdf form on click function also is there a way to set the js function to ONLY download the selected Id in the div and not on certain scale?我已经转移到 js 并且我坚持使用这个脚本,它不想在单击函数上创建 pdf 表单,还有没有办法将 js 函数设置为仅下载 div 中选定的 Id 而不是在一定程度上? (afraid that it's going to use the resolution instead of the actual content that needs to be rendered) (怕它会用分辨率而不是实际需要渲染的内容)

https://jsfiddle.net/u4ko9pzs/18/ https://jsfiddle.net/u4ko9pzs/18/

Any suggestions would be greatly appreciated.任何建议将不胜感激。

You don't need to use that django app.你不需要使用那个 django 应用程序。 You can write a custom view to handle printing as per example in the blog post https://www.bedjango.com/blog/how-generate-pdf-django-weasyprint/您可以按照博客文章https://www.bedjango.com/blog/how-generate-pdf-django-weasyprint/ 中的示例编写自定义视图来处理打印

I found that app limiting and wrote my own views.我发现应用程序限制并写了我自己的观点。 It's not that hard.这并不难。

I was tried django-wkhtmltopdf and weasyprint.我尝试了 django-wkhtmltopdf 和 weasyprint。 For shure weasyprint allow more in subject of css but still it isn't one to one to browser version.对于舒尔 weasyprint 允许更多的 css 主题,但它仍然不是一对一的浏览器版本。 I wasn't happy with results.我对结果不满意。 It is ok for tables, and all word/excel like data.表格和所有 word/excel 之类的数据都可以。 But in my case i have to made px to px 'certificate' like pdf with svg shaped background Then some lack of features starts to be not convenient problem.但是在我的情况下,我必须将 px 转换为 px '证书',例如具有 svg 形状背景的 pdf 然后一些功能的缺乏开始成为不方便的问题。

So if you need use the same css with minimal modification to get effect like in browswer then puppeter solving all compabitlity problems.因此,如果您需要使用相同的 css 并进行最少的修改以获得像在浏览器中那样的效果,那么 puppeter 解决所有兼容性问题。 But this force to use Node to run puppeteer.但是这个强制使用Node来运行puppeteer。 (in my case i already use it to compile assets) (就我而言,我已经用它来编译资产)

Cli for puppetere : puppetere 的 Cli

npm i- puppeteer-pdf

then install wrapper然后安装包装器

pip install django-puppeteer-pdf

add node puppeteer cli start command in settings:在设置中添加 node puppeteer cli start 命令:

PUPPETEER_PDF_CMD = 'npx puppeteer-pdf'

and create view并创建视图

from puppeteer_pdf import render_pdf_from_template
from django.http import HttpResponse, 
import os

# Rendering code 
context = {
    'data': 'test data'
}

output_temp_file = os.path.join(settings.BASE_DIR, 'static', 'temp.pdf')

pdf = render_pdf_from_template(
    input_template='path to template in templates dir'
    header_template='',
    footer_template='',
    context=context,
    cmd_options={
        'format': 'A4',
        'scale': '1',
        'marginTop': '0',
        'marginLeft': '0',
        'marginRight': '0',
        'marginBottom': '0',
        'printBackground': True,
        'preferCSSPageSize': True,
        'output': output_temp_file,
        'pageRanges': 1
    }
)
#you can remove temp file now or collecte them and run some crone task.(performance)
if os.path.exists(output_temp_file):
    os.remove(output_temp_file)
else:
    # raise error or something

filename = f'filename={'your donwload file name'}.pdf'

response = HttpResponse(pdf, content_type='application/pdf;')
response['Content-Disposition'] = filename

To keep original color you have to add为了保持原来的颜色,你必须添加

html{
  -webkit-print-color-adjust: exact;
}

controlling page size and margin when you choice 'preferCSSPageSize'.当您选择“preferCSSPageSize”时控制页面大小和边距。

@page {
  size: A4;
  margin: 0 0 0 0;
}

Use whkhtmltopdf it's very easy to use in Django.使用whkhtmltopdf在 Django 中非常容易使用。 It's provide pure html generated PDF conversion它提供纯 html 生成的 PDF 转换

pip install django-wkhtmltopdf

https://django-wkhtmltopdf.readthedocs.io/en/latest/ https://django-wkhtmltopdf.readthedocs.io/en/latest/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM