首页 > 解决方案 > 如何将json转换为pdf图像

问题描述

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

例如,这就是我收到的(不幸的是,由于他的长度,我无法添加完整的 json):

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

标签: pythonjsonpython-3.ximagepdf

解决方案


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


推荐阅读