python - 如何从二进制字符串创建 PDF?

标签 python python-requests pdf-generation

已使用 Python 的 requests 模块向服务器发出请求:

requests.get('myserver/pdf', headers)

它返回了一个 status-200 响应,其中包含 response.content 中的 PDF 二进制数据

问题

如何从 response.content 创建 PDF 文件?

最佳答案

您可以创建一个空的 pdf,然后将写入内容以二进制形式保存到该 pdf,如下所示:

from reportlab.pdfgen import canvas
import requests

# Example of path. This file has not been created yet but we 
# will use this as the location and name of the pdf in question

path_to_create_pdf_with_name_of_pdf = r'C:/User/Oleg/MyDownloadablePdf.pdf'

# Anything you used before making the request. Since you did not
# provide code I did not know what you used
.....
request = requests.get('myserver/pdf', headers)

#Actually creates the empty pdf that we will use to write the binary data to
pdf_file = canvas.Canvas(path_to_create_pdf_with_name_of_pdf)

#Open the empty pdf that we created above and write the binary data to. 
with open(path_to_create_pdf_with_name_of_pdf, 'wb') as f:
     f.write(request.content)
     f.close()

reportlab.pdfgen允许您通过使用 canvas.Canvas 方法指定要保存 pdf 的路径以及 pdf 的名称来创建新的 pdf。正如我的回答所述,您需要提供执行此操作的路径。

一旦您有了空的 pdf,您可以将 pdf 文件作为 wb(写入二进制)打开,并将请求中的 pdf 内容写入文件并关闭文件。

使用路径时 - 确保该名称不是任何现有文件的名称,以确保不会覆盖任何现有文件。正如注释所示,如果该名称是任何其他文件的名称,那么您将面临覆盖数据的风险。例如,如果您在循环中执行此操作,则需要在每次迭代时指定具有新名称的路径,以确保每次都有新的 pdf。但如果它是一次性的,那么只要它不是另一个文件的名称,您就不会冒这种风险。

关于python - 如何从二进制字符串创建 PDF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55030074/

相关文章:

python - 通过 Python 在 MPI_Init 中启动 Open MPI 时出错

python - 有没有一种方法可以用决策树/随机森林进行迁移学习?

Python请求库头授权问题

post - 服务器不接受查询中的双引号

ios - 防止PDF文件被修改

css - iTextSharp PDF 基本字体大小与 XMLWorker

python - Django 模板标签返回 True 或 False

python - shutil.copyfileobj 错误地复制了数据

python 请求非 ascii 文件名的问题

php - 在 Symfony 中,有没有办法一次创建 pdf 文件页面?