gpt4 book ai didi

python - 在内存python中下载pdf

转载 作者:太空宇宙 更新时间:2023-11-04 08:43:52 25 4
gpt4 key购买 nike

我想在我的 Python 程序中打开一个 pdf。到目前为止,一切正常。

existing_pdf = PdfFileReader(file(path_to_pdf, "rb"))

现在我从我的本地磁盘打开 pdf,但我希望它从 Internet 获取 pdf,而不是从我的本地驱动器打开它。请注意,我不想保存 existing_pdf,一旦我从互联网上获取它,我将对其进行操作然后保存。

我想我需要 BytesIO + urllib2,但我想不出来,有人可以帮我吗?

假设我想创建变量:existing_pdf 内容为 http://tug.ctan.org/tex-archive/macros/latex/contrib/logpap/example.pdf在其中,但我不想先将该文件下载到磁盘然后再打开它。我想将它下载到“内存中”并创建变量 existing_pdf,稍后我可以在我的程序中对其进行修改。

编辑:

  response=urllib2.urlopen("URL")
pdf_file = BytesIO(response.read())

existing_pdf = PdfFileReader(pdf_file)

它只是挂起并且永远不会完成 PdfFileReader(pdf_file)

  ....
existing_pdf = PdfFileReader(pdf_file)
File "C:\Python27\lib\site-packages\pyPdf\pdf.py", line 374, in __init__
self.read(stream)
File "C:\Python27\lib\site-packages\pyPdf\pdf.py", line 705, in read
line = self.readNextEndLine(stream)
File "C:\Python27\lib\site-packages\pyPdf\pdf.py", line 870, in readNextEndLine
line = x + line

最佳答案

你试过requests package了吗? ?

import requests
from StringIO import StringIO
r = requests.get(URL)
pdf_file = StringIO(r.content)
existing_pdf = PdfFileReader(pdf_file)

这对我有用:

import os
import urllib2
from io import BytesIO
URL = "http://tug.ctan.org/tex-archive/macros/latex/contrib/logpap/example.pdf"
response=urllib2.urlopen(URL)
p = BytesIO(response.read())
p.seek(0, os.SEEK_END)
print p.tell()
# 79577

关于python - 在内存python中下载pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42549236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com