【问题标题】:How to create a PDF from a binary string?如何从二进制字符串创建 PDF?
【发布时间】:2019-07-28 12:43:05
【问题描述】:

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

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

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

问题

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

【问题讨论】:

  • 我建议尝试将数据写入以二进制模式打开的文件中 - 如当前在末尾附近显示的 @Edeki Okoh 的答案。
  • 我不同意。为了制作一个真正的 pdf 文件,您不能只使用 write 方法。您需要先创建一个 pdf,以确保正在创建的文件 actually has the properties of a pdf @martineau

标签: python python-requests pdf-generation


【解决方案1】:

您可以创建一个空的 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 内容写入文件,然后关闭文件。

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

【讨论】:

  • 使用reportlab.pdfgen 有什么意义(因为您的代码完全忽略了pdf_file 变量)?
  • 即使我不调用 pdf_file,该方法仍将创建空 pdf,但在过去,如果未将空 pdf 分配给变量,我在制作空 pdf 时会遇到问题。这是我用来自动化它的解决方案。本质上,这部分只是为了确保我们有一个 pdf 文件可以打开并写入二进制数据。 canvas.Canvas 将在路径中使用 pdf 的名称,因此我们可以在之前指定名称,并在我们想要写入时再次调用它。
  • 您编写 pdf 文件的方式会完全覆盖其中可能已经存在的任何内容。
  • 没有什么可以覆盖的,这就是重点。它是一个空的 pdf,我们稍后会使用它来写入二进制数据。但是,如果不将其分配给变量,您可能会出错。
  • 抱歉,我认为这不是真的——或者至少它没有任何意义。什么样的“错误”?
猜你喜欢
  • 1970-01-01
  • 2016-02-10
  • 2015-08-07
  • 1970-01-01
  • 1970-01-01
  • 2019-08-27
  • 1970-01-01
  • 2017-01-22
  • 1970-01-01
相关资源
最近更新 更多