使用reportlab生成的pdf提供标签标题

时间:2015-02-02 13:02:41

标签: python django pdf-generation httpresponse reportlab

这个问题很简单,但我找不到任何数据。 当我使用reportlab生成pdf时,将httpresponse作为文件传递,配置为显示文件的浏览器会正确显示pdf。但是,标签的标题仍为“(匿名)127.0.0.1 / whatnot”,这对用户来说有点难看。

由于大多数网站能够以某种方式显示合适的标题,我认为这是可行的...是否有某种标题参数,我可以传递给PDF?或者响应的一些标题?这是我的代码:

def render_pdf_report(self, context, file_name):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'filename="{}"'.format(file_name)

    document = BaseDocTemplate(response, **self.get_create_document_kwargs())
    #  pdf generation code
    document.build(story)
    return response

5 个答案:

答案 0 :(得分:9)

似乎Google Chrome根本不显示PDF标题。 我测试了评论中的链接(biblioteca.org.ar),它在Firefox中显示为" - 211756.pdf",似乎有一个空标题,然后Firefox只显示文件名而不是完整的URL路径。

我使用这段代码重现了相同的行为:

from reportlab.pdfgen import canvas

c = canvas.Canvas("hello.pdf")
c.setTitle("hello stackoverflow")
c.drawString(100, 750, "Welcome to Reportlab!")
c.save()

在Firefox中打开它会产生所需的结果:

我在ReportLab's User Guide中发现了setTitle。它已在第16页列出。:)

答案 1 :(得分:0)

如果您使用的是trml2pdf,则需要添加"标题"模板标签中的属性,即,< template title =" Invoices" ...

答案 2 :(得分:0)

我也在寻找它,并且在源代码中找到了它。

reportlab / src / reportlab / platypus / doctemplate.py @行-467

我们可以通过以下方式设置文档标题

document.title = 'Sample Title'

答案 3 :(得分:0)

除了其他人所说的,您还可以使用

Canvas.setTitle("yourtitle")

在chrome中显示正常。

答案 4 :(得分:0)

我意识到这是一个老问题,但对于使用 SimpleDocTemplate 的任何人来说,这是一个答案。 title 属性可以在 SimpleDocTemplate 的构造函数中设置为 kwarg。例如

doc = SimpleDocTemplate(pdf_bytes, title="my_pdf_title")