Skip to main content
 首页 » 编程设计

python之在内存python中下载pdf

2025年05月04日24Free-Thinker

我想在我的 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