html文件嵌入到reportlab,如何使用基于Django的类视图包含ReportLab的?(How to incorporate R...

我想我的HTML转换为PDF。 我看着这个教程, https://www.codingforentrepreneurs.com/blog/html-template-to-pdf-in-django/ ,我能顺利拿到教程用硬编码值工作。 问题是...我无法弄清楚如何动态地纳入我的模型和它的属性到这个例子。

下面是我遵循的步骤...

首先,我安装ReportLab的到我有以下版本环境...

pip install --pre xhtml2pdf

这个工作?

然后,我添加了一个utils.py文件到我的项目的指示。

然后我复制此代码到我的utils.py文件...

from io import BytesIO

from django.http import HttpResponse

from django.template.loader import get_template

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("ISO-8859-1")), result)

if not pdf.err:

return HttpResponse(result.getvalue(), content_type='application/pdf')

return None

然后,我创建了一个HTML文件类似下面:

Title

body {

font-weight: 200;

font-size: 14px;

}

.header {

font-size: 20px;

font-weight: 100;

text-align: center;

color: #007cae;

}

.title {

font-size: 22px;

font-weight: 100;

/* text-align: right;*/

padding: 10px 20px 0px 20px;

}

.title span {

color: #007cae;

}

.details {

padding: 10px 20px 0px 20px;

text-align: left !important;

/*margin-left: 40%;*/

}

.hrItem {

border: none;

height: 1px;

/* Set the hr color */

color: #333; /* old IE */

background-color: #fff; /* Modern Browsers */

}

Invoice #

Bill to: {{ customer_name }}

Amount: {{ amount }}

Date:


我也创造了必要的URL ....

然后,我创建了类似于下面定义的视图:

from django.http import HttpResponse

from django.views.generic import View

from yourproject.utils import render_to_pdf #created in step 4

class GeneratePdf(View):

def get(self, request, *args, **kwargs):

data = {

'today': datetime.date.today(),

'amount': 39.99,

'customer_name': 'Cooper Mann',

'order_id': 1233434,

}

pdf = render_to_pdf('pdf/invoice.html', data)

return HttpResponse(pdf, content_type='application/pdf')

当我点击我的链接这一观点上...输出显示就像教程说...

但是,如果我试图让我的模型,这个格式来显示...我难倒就如何做到这一点。 我试过的DetailView ....然后我得到的数据,但没有PDF ....我也搜索其他许多地方,似乎我无法找到一个例子,让我来动态获取我的模型和拉在属性中按需...预先感谢任何帮助或指针。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值