如何将 json 转换为 pdf 图像

how to convert json to pdf image

我收到一个带图像的 base64 编码 pdf 文件,它以 json 格式发送。但我不明白如何将所有这些解码回 pdf,例如将其保存在我的电脑上。

例如这就是我收到的(不幸的是我不能添加完整的 json,因为他的长度):

{'img': 'JVBERi0xLjcKJeLjz9MKNCAwIG9iago.......'}

下面的代码应该将 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