简体   繁体   English

从base64字符串渲染pdf文件

[英]Rendering pdf file from base64 string

I have pdf file which is encoded with base64. 我有用base64编码的pdf文件。 I created simple script for saving it as pdf file: 我创建了简单的脚本将其另存为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()

After the script runs, I have pdf file as expected, but it's broken. 脚本运行后,我的PDF文件符合预期,但已损坏。 I decided to compare just any correct pdf file with the file I got and noticed that every line in correct pdf file ends with "^M", for example: 我决定将任何正确的pdf文件与我得到的文件进行比较,并注意到正确的pdf文件中的每一行都以“ ^ M”结尾,例如:

Correct pdf file header: %PDF-1.7^M 正确的pdf文件标题:%PDF-1.7 ^ M

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

So, what am I doing wrong here? 那么,我在这里做错了什么?

I had a similar problem. 我有一个类似的问题。 I used the following function to generate and return a PDF file from a base64 encoded string in Django. 我使用以下函数从Django中的base64编码字符串生成和返回PDF文件。 (Tested only with Python 3.5) (仅在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

If you are not using Django, then you just need to figure out how to return the PDF file in a view or something like that. 如果您不使用Django,则只需要弄清楚如何在视图或类似视图中返回PDF文件。 I use HttpResponse that handles various things for the response. 我使用HttpResponse处理响应的各种事情。

I can also use this function for any kind of b64 encoded string, so it's reusable across the project. 我还可以将此函数用于任何类型的b64编码的字符串,因此可在整个项目中重复使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM