【发布时间】:2021-09-24 07:43:21
【问题描述】:
我得到一个带有图像的 base64 编码的 pdf 文件,它以 json 格式发送。但我不明白如何将所有这些解码回 pdf,例如保存在我的计算机上。
例如这是我收到的(不幸的是我无法添加完整的 json,因为他的长度):
{'img': 'JVBERi0xLjcKJeLjz9MKNCAwIG9iago.......'}
【问题讨论】:
标签: python json python-3.x image pdf
我得到一个带有图像的 base64 编码的 pdf 文件,它以 json 格式发送。但我不明白如何将所有这些解码回 pdf,例如保存在我的计算机上。
例如这是我收到的(不幸的是我无法添加完整的 json,因为他的长度):
{'img': 'JVBERi0xLjcKJeLjz9MKNCAwIG9iago.......'}
【问题讨论】:
标签: python json python-3.x image pdf
以下代码应将 Base64 转换为 PDF。 input 是你的 json 字符串
# Import only b64decode function from the base64 module
from base64 import b64decode
json_str = {'img': 'JVBERi0xLjcKJeLjz9MKNCAwIG9iago.......'}
# Define the Base64 string of the PDF file
b64 = json_str['img']
# Decode the Base64 string, making sure that it contains only valid characters
b64bytes = b64decode(b64, validate=True)
# Perform a basic validation to make sure that the result is a valid PDF file
# Be aware! The magic number (file signature) is not 100% reliable solution to validate PDF files
# Moreover, if you get Base64 from an untrusted source, you must sanitize the PDF contents
if b64bytes[0:4] != b'%PDF':
raise ValueError('Missing the PDF file signature')
# Write the PDF contents to a local file
with open('file.pdf', 'wb') as f:
f.write(b64bytes)
来源:https://base64.guru/developers/python/examples/decode-pdf
【讨论】: