【发布时间】:2021-10-14 07:05:29
【问题描述】:
我正在使用 Python 3、Django 和 xhtml2pdf 包。
我想从 HTML 字符串创建 PDF,但我不想将 PDF 写入磁盘,而只是从内存中获取其字节,如使用 BytesIO 或 StringIO。
我读过xhtml2pdfdocumentation。这是我发现的与我需要的最接近的:
可以使用 StringIO 或 cStringIO 生成内存文件,而不是打开文件。高级选项将在本文档后面讨论。
这是我尝试过的最新方法之一:
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()
但这不起作用。
知道如何将生成的 PDF 作为内存对象输出并返回其字节吗?
【问题讨论】:
-
我认为这篇文章会有所帮助:stackoverflow.com/questions/59695870/…。它对我有用
标签: python django stringio xhtml2pdf bytesio