How to base64 encode a PDF file in Python

2020-05-24 14:57发布

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

4条回答
一夜七次
2楼-- · 2020-05-24 15:26

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")
查看更多
兄弟一词,经得起流年.
3楼-- · 2020-05-24 15:33

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())) 
查看更多
forever°为你锁心
4楼-- · 2020-05-24 15:43

You can do it with the base64 library, legacy interface.

查看更多
孤傲高冷的网名
5楼-- · 2020-05-24 15:48

Looks like you might be able to use the binascii module

binascii.b2a_base64(data)

Convert binary data to a line of ASCII characters in base64 coding. The return value is the converted line, including a newline char. The length of data should be at most 57 to adhere to the base64 standard.

查看更多
登录 后发表回答