0

I have pdf file which is encoded with base64. I created simple script for saving it as pdf file:

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. 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:

Correct pdf file header: %PDF-1.7^M

My pdf file header: %PDF-1.4

So, what am I doing wrong here?

4
  • 1
    Well, the original PDF might've been broken... Commented Aug 18, 2017 at 13:48
  • How did you encode it? Commented Aug 18, 2017 at 13:48
  • I didn't encode this file, got it as base64 string :( Commented Aug 18, 2017 at 14:08
  • Try if base64.b64decode(... makes any difference. Commented Aug 18, 2017 at 16:51

1 Answer 1

3

I had a similar problem. I used the following function to generate and return a PDF file from a base64 encoded string in Django. (Tested only with 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. I use HttpResponse that handles various things for the response.

I can also use this function for any kind of b64 encoded string, so it's reusable across the project.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.