Xar
Xar

Reputation: 7940

xhtml2pdf: Output generated PDF as in-memory object (its bytes)

I'm working with Python 3, Django and the 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've read the xhtml2pdf documentation. 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. 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?

Upvotes: 2

Views: 2374

Answers (2)

Sinisa
Sinisa

Reputation: 71

What you can also do is output.getvalue(). This will get the entire contents of the BytesIO object.

Upvotes: 1

saubao
saubao

Reputation: 11

I think your return statement is using new_output instead of output.

However, the real issue should be something else, have you tried calling output.seek(0) before reading its bytes with output.read()?

Upvotes: 0

Related Questions