【问题标题】:xhtml2pdf: Output generated PDF as in-memory object (its bytes)xhtml2pdf:将生成的 PDF 输出为内存对象(其字节)
【发布时间】:2021-10-14 07:05:29
【问题描述】:

我正在使用 Python 3、Django 和 xhtml2pdf 包。

我想从 HTML 字符串创建 PDF,但我不想将 PDF 写入磁盘,而只是从内存中获取其字节,如使用 BytesIOStringIO

我读过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 作为内存对象输出并返回其字节吗?

【问题讨论】:

标签: python django stringio xhtml2pdf bytesio


【解决方案1】:

我认为您的退货声明使用的是new_output 而不是output

但是,真正的问题应该是其他问题,您是否尝试在使用output.read() 读取其字节之前调用output.seek(0)

【讨论】:

    猜你喜欢
    • 2013-05-30
    • 2020-12-15
    • 2020-01-13
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-21
    相关资源
    最近更新 更多