Django pdf 导出

发布于 2024-12-10 21:15:22 字数 381 浏览 0 评论 0原文

我想生成一个 PDF,它将以表格格式显示查询集的输出,例如:

query = ModelA.objects.filter(p_id=100)

class ModelA(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=200)
    p_id = models.IntegerField()
    description = models.TextField()

我需要显示 namedescriptionpid 的值 在生成的 PDF 中。

I want to generate a PDF which will show the output of my queryset in table format, for example:

query = ModelA.objects.filter(p_id=100)

class ModelA(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=200)
    p_id = models.IntegerField()
    description = models.TextField()

I need to show the values for name, description and pid in the generated PDF.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

姐不稀罕 2024-12-17 21:15:22

正如其他人提到的,最好的方法是生成一个模板,然后使用周围的众多库之一将结果转换为 PDF。此方法为您提供了对模板的常规控制,例如使用标签。

我使用了前面提到的 ReportLab/Pisa 设置,但发现它相当有限,大多数布局必须使用表格构建,并且 CSS2 规范的许多部分尚未实现。

一个更易于使用的库是 wkhtmltopdf,它是 WebKit 的无头发行版。这样做的好处是可以像任何 webkit 浏览器一样渲染您的模板,从而让您可以使用 webkit 特定的附加功能,例如 WebKit 中存在的 CSS3 规范的一部分。

使用包装库 django-wkhtmltopdf 您可以在视图中render_to_pdf而不是通常的 Django render_to_response

免责声明:我是该库的贡献者。

更新

该库已转换为 CBV,并且为了方便起见,下面的大部分信息(我将留下这些信息以帮助添加一些上下文)现在已在库本身中实现。

请参阅快速入门文档,了解如何实现的示例下面的代码块。如果您需要使用更高级的用法,您可以子类化 PDFTemplateView 并添加各种选项,例如文件名和边距。

示例视图:

from django.shortcuts import render_to_response
from wkhtmltopdf import render_to_pdf

def pdf(request):
    context.update({'objects': ModelA.objects.filter(p_id=100)})

    kwargs = {}
    if request.GET and request.GET.get('as', '') == 'html':
        render_to = render_to_response
    else:
        render_to = render_to_pdf
        kwargs.update(dict(
            filename='model-a.pdf',
            margin_top=0,
            margin_right=0,
            margin_bottom=0,
            margin_left=0))

    return render_to('pdf.html', context, **kwargs)

此处的条件语句允许您将 ?as=html 传递给视图,以便您可以在浏览器中进行开发。目前这样做有点丑陋,但计划很快在版本中修复此问题。

使用此视图,您可以像平常一样在视图中循环objects 的内容,甚至可以扩展您的基本模板。我通常专门为 PDF 使用不同的样式表,以实现样式的可维护性和可读性,因为您需要对 PDF 做一些不同的事情,例如如果您想将页脚块保留在同一位置,则设置最小高度。

请注意,您可以创建将在 PDF 的每个页面上使用的页眉和页脚模板,方法是将它们作为 kwargs 的一部分传递到 render_to_pdf 中。

As mentioned by other people the best way to do this is to generate a template then convert the result, using one of the many libraries around, into a PDF. This method provides you with the usual amount of control over your templates, for example using tags.

I've used the previously mentioned ReportLab/Pisa setup but found it to be quite limiting, most layouts have to be built using tables and many parts of the CSS2 spec aren't implemented yet.

An easier to use library is wkhtmltopdf which is a headless distribution of WebKit. This has the benefit of rendering your templates like any webkit browser would and thus letting you use webkit specific extras, such as parts of the CSS3 spec that exist in WebKit.

Using the wrapper library django-wkhtmltopdf you can render_to_pdf in your view instead of the usual Django render_to_response.

Disclaimer: I am a contributor to this library.

Update

This library has been converted to CBVs and most of the information below (which I'll leave to help add some context) is now implemented in the library itself for convenience.

See the quickstart docs for an example of how to implement the below code block. If you need to use more advanced usage you can subclass PDFTemplateView and add various options like filename and the margins.

An example view:

from django.shortcuts import render_to_response
from wkhtmltopdf import render_to_pdf

def pdf(request):
    context.update({'objects': ModelA.objects.filter(p_id=100)})

    kwargs = {}
    if request.GET and request.GET.get('as', '') == 'html':
        render_to = render_to_response
    else:
        render_to = render_to_pdf
        kwargs.update(dict(
            filename='model-a.pdf',
            margin_top=0,
            margin_right=0,
            margin_bottom=0,
            margin_left=0))

    return render_to('pdf.html', context, **kwargs)

The conditional statement here lets you pass ?as=html to the view so you can develop in the browser. It's a bit of an ugly way to do it currently but there are plans to fix this in a release soon.

Using this view you could loop the contents of objects in your view as you would normally and even extend your base template. I've normally used a different stylesheet specifically for the PDFs for maintainability and readability of the styles as you need to do a few things differently for PDFs, such as setting a min-height if you want to keep your footer block in the same place.

On this note, you can create header and footer templates that will be used on each page of your PDF by passing them into render_to_pdf as part of kwargs.

青瓷清茶倾城歌 2024-12-17 21:15:22

只需按照您想要的方式生成 HTML,然后要求 xhtml2pdf 将其转换为 pdf。

就像其中提到的评论之一一样,有 ReportLab,但这需要您以 PDF 所需的格式给出规范。它为您提供了更多控制权,但如果您更容易生成 HTML(您需要生成的标准方式),您可以使用 pisa 将其制作为 pdf。

Just generate the HTML the way you would want it and ask xhtml2pdf to convert it into pdf.

Like one of the comment mentions, there is ReportLab, but that would need you to give specification in PDF's required format. It provides you more control, but if it is easier for you to generate HTML, the standard way which you need to generate anyway, you can use pisa to make it pdf.

我很OK 2024-12-17 21:15:22

尝试使用 wkhtmltopdfpython-pdfkit

这似乎是最好的解决方案。支持 javascript 和 css

Try wkhtmltopdf with python-pdfkit

This seems to be the best solution.Supports javascript and css

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文