python - 如何在 Python 中将临时文件中的 pdf 文件合并为一个
问题描述
我有一个 python 代码,它从 tableau 视图创建一个临时的 pdf 文件并将其分别发送到松弛通道。我想将它们组合成一个文件,但我不知道该怎么做。我对 python 相当陌生,非常感谢在下面的代码中如何使用 PdfFileMerger 的一些帮助。我试过用
合并附加(f)
在 f 变量之后但它不起作用给我 ar 错误 ** AttributeError: 'dict' object has no attribute 'seek' ** 我应该把什么放在括号里?
for view_item in all_views :
with tempfile.NamedTemporaryFile(suffix='.pdf', delete=True) as temp_file:
#server.views.populate_image(view_item, req_options=image_req_option)
server.views.populate_pdf(view_item, req_options = pdf_req_option)
print('got the image')
temp_file.write(view_item.pdf)
temp_file.file.seek(0)
print('in the beginnign again')
f = {'file': (temp_file.name,temp_file, 'pdf')}
merger.append(f)
response = requests.post(url='https://slack.com/api/files.upload', data=
{'token': bot_token, 'channels': slack_channels[0], 'media': f,'title': '{} {}'.format(view_item.name, yesterday), 'initial_comment' :''},
headers={'Accept': 'application/json'}, files=f)
print('the image is in the channel')
解决方案
您需要像这样向 PdfFileMerger 提供文件对象,而不是字典。
由于 PdfFileMerger 无论如何都会在内存中执行操作,因此无需写入磁盘上的临时文件,内存中的 BytesIO 就可以了。
import io
merger = PdfFileMerger()
for view_item in all_views:
server.views.populate_pdf(view_item, req_options=pdf_req_option)
# Write retrieved data into memory file
tf = io.BytesIO()
tf.write(view_item.pdf)
tf.seek(0)
# Add it to the merger
merger.append(tf)
# Write merged data into memory file
temp_file = io.BytesIO()
merger.write(temp_file)
temp_file.seek(0)
f = {'file': ('merged.pdf', temp_file, 'pdf')}
# Slack stuff here...
推荐阅读
- java - 为什么 spring 验证器在这个 Api 中不起作用?
- java - 如何使用命令“Jar x”?
- xsd - 用于解析分隔文本消息的 DFDL Schema
- ruby-on-rails - “form_with 找不到 Post 模型”
- python - 为什么我在 python 3.9 上调用函数时出现错误
- html - 如何在 Thymeleaf 中将 th:attr 更改为 th:onclick
- c# - Datagridview 列标题以编程方式分配颜色,但在程序运行时不显示相同的颜色
- javascript - javascript 函数在控制台上不起作用
- python - 试图在python中用散景绘制鼠标悬停交互式图形
- python - 将前导零添加到具有 MM:SS 时间数据的字段