16

Using python, I want to convert a pdf file into base64Binary

My logic(not python) is reading the contents of the file into a byte array and then use something like Convert.ToBase64String() method to get the Base64 string:

byte[] pdfBytes = File.ReadAllBytes(pdfPath);
string pdfBase64 = Convert.ToBase64String(pdfBytes);

Please let me know what is the right approach to convert a pdf file into base64Binary in python

me24hour
  • 629
  • 3
  • 8
  • 15

2 Answers2

49

its easy as this

import base64

with open("book.pdf", "rb") as pdf_file:
    encoded_string = base64.b64encode(pdf_file.read())

source: Encoding an image file with base64

Community
  • 1
  • 1
Abdallah Alsamman
  • 1,623
  • 14
  • 22
0

Here is my solution:

import base64
from base64 import b64decode, b64encode

def pdf_to_base64(file):
    file_bytes = base64.b64encode(file.read())
    base_64 = file_bytes.decode("ascii")
    return base_64
S.B
  • 13,077
  • 10
  • 22
  • 49