Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to base64 encode a PDF file in Python

How should I base64 encode a PDF file for transport over XML-RPC in Python?

like image 736
Pat Notz Avatar asked Oct 16 '08 14:10

Pat Notz


People also ask

Can you base64 encode a PDF?

Sometimes you have to send or output a PDF file within a text document (for example, HTML, JSON, XML), but you cannot do this because binary characters will damage the syntax of the text document. To prevent this, for example, you can encode PDF file to Base64 and embed it using the data URI.


2 Answers

If you don't want to use the xmlrpclib's Binary class, you can just use the .encode() method of strings:

a = open("pdf_reference.pdf", "rb").read().encode("base64")
like image 161
Tony Meyer Avatar answered Oct 06 '22 07:10

Tony Meyer


Actually, after some more digging, it looks like the xmlrpclib module may have the piece I need with it's Binary helper class:

binary_obj = xmlrpclib.Binary( open('foo.pdf').read() )

Here's an example from the Trac XML-RPC documentation


import xmlrpclib 
server = xmlrpclib.ServerProxy("http://athomas:password@localhost:8080/trunk/login/xmlrpc") 
server.wiki.putAttachment('WikiStart/t.py', xmlrpclib.Binary(open('t.py').read())) 
like image 42
Pat Notz Avatar answered Oct 06 '22 08:10

Pat Notz