How to base64 encode a PDF file in Python

五迷三道 提交于 2019-12-03 09:56:56

问题


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


回答1:


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")



回答2:


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())) 



回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/208894/how-to-base64-encode-a-pdf-file-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!