python - 如何将json转换为pdf图像
问题描述
我得到一个带有图像的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
推荐阅读
- c# - 如何在运行时从不同的 AppDomain 访问 Fody/Costura 嵌入式库
- powershell - 脚本应该循环通过 powershell 中的子网,并混合使用错误的 ip
- docker - Docker:创建拆卸程序
- java - 我需要帮助以这种特殊方式根据频率对 java 中的数组进行排序
- c# - InputPane 涵盖 Context Flyout UWP
- r - 将数据帧数组列拆分为多个二进制列 [R]
- c++11 - 将 std::vector 展开为参数包
- python - 在 Python 中模拟相关的对数正态
- javascript - 为什么导入 react pdf 会从我的 npm 库中破坏我的应用程序
- php - PHP DateTime::createFromFormat 返回错误的日期