从base64字符串渲染pdf文件

时间:2017-08-18 13:44:49

标签: python pdf

我有pdf文件,用base64编码。 我创建了简单的脚本,将其保存为pdf文件:

import base64
with open('pdf.b64', mode='r') as fpdf:
    with open('output.pdf', mode='wb') as output:
        base64.decode(fpdf, output)
        output.close()
    fpdf.close()

脚本运行后,我按预期编写了pdf文件,但它已损坏。 我决定将任何正确的pdf文件与我得到的文件进行比较,并注意到正确的pdf文件中的每一行都以“^ M”结尾,例如:

更正pdf文件标题: %PDF-1.7 ^ M

我的pdf文件标题: %PDF-1.4

那么,我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

我有类似的问题。我使用以下函数从Django中的base64编码字符串生成并返回PDF文件。 (仅使用Python 3.5测试)

def b64_to_pdf(b64content):
    import io as BytesIO
    import base64
    from django.http import HttpResponse

    buffer = BytesIO.BytesIO()
    content = base64.b64decode(b64content)
    buffer.write(content)

    response = HttpResponse(
        buffer.getvalue(),
        content_type="application/pdf",
    )
    response['Content-Disposition'] = 'inline;filename=some_file.pdf'
    return response

如果您不使用Django,那么您只需要弄清楚如何在视图中返回PDF文件或类似的东西。我使用HttpResponse来处理响应的各种事情。

我也可以将此函数用于任何类型的b64编码字符串,因此它可以在整个项目中重复使用。

相关问题