[英]xhtml2pdf: Output generated PDF as in-memory object (its bytes)
I'm working with Python 3, Django and the xhtml2pdf
package.我正在使用 Python 3、Django 和xhtml2pdf
package。
I want to create a PDF from an HTML string, but I don't want to write the PDF on disk, but rather just to get its bytes from memory, as in using BytesIO
or StringIO
. I want to create a PDF from an HTML string, but I don't want to write the PDF on disk, but rather just to get its bytes from memory, as in using BytesIO
or StringIO
.
I've read the xhtml2pdf
documentation .我已阅读xhtml2pdf
文档。 This is the closest I've found related to what I need:这是我发现的与我需要的最接近的:
In-memory files can be generated by using StringIO or cStringIO instead of the file open.可以使用 StringIO 或 cStringIO 生成内存文件,而不是打开文件。 Advanced options will be discussed later in this document.本文档稍后将讨论高级选项。
And this is one of the latest things I've tried:这是我尝试过的最新方法之一:
def html_to_pdf(html):
"""Writes a PDF file using xhtml2pdf from a given HTML stream
Parameters
----------
html : str
A HTML valid string.
Returns
-------
bytes
A bytes sequence containing the rendered PDF.
"""
output = BytesIO()
pisa_status = pisa.CreatePDF(html, dest=output)
return new_output.read()
But this isn't working.但这行不通。
Any idea how to output the generated PDF as a in-memory object and thus return its bytes?知道如何将 output 生成的 PDF 作为内存中的 object 并因此返回其字节吗?
I think your return statement is using new_output
instead of output
.我认为您的 return 语句使用的是new_output
而不是output
。
However, the real issue should be something else, have you tried calling output.seek(0)
before reading its bytes with output.read()
?但是,真正的问题应该是其他问题,您是否尝试在使用output.read()
读取其字节之前调用output.seek(0)
) ?
What you can also do is output.getvalue()
.您还可以做的是output.getvalue()
。 This will get the entire contents of the BytesIO object.这将获得 BytesIO object 的全部内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.