使用pyPdf打开pdf链接

13

如何从URL打开PDF而不是从磁盘中打开?

类似于:

input1 = PdfFileReader(file("http://example.com/a.pdf", "rb"))

我想从网页上打开多个文件并下载它们的合并文件。


1
这是Python3的解决方案:https://dev59.com/I1YN5IYBdhLWcg3wm5Oi - tommy.carstensen
4个回答

20

我认为urllib2可以帮助你得到你想要的内容。

from urllib2 import Request, urlopen
from pyPdf import PdfFileWriter, PdfFileReader
from StringIO import StringIO

url = "http://www.silicontao.com/ProgrammingGuide/other/beejnet.pdf"
writer = PdfFileWriter()

remoteFile = urlopen(Request(url)).read()
memoryFile = StringIO(remoteFile)
pdfFile = PdfFileReader(memoryFile)

for pageNum in xrange(pdfFile.getNumPages()):
        currentPage = pdfFile.getPage(pageNum)
        #currentPage.mergePage(watermark.getPage(0))
        writer.addPage(currentPage)


outputStream = open("output.pdf","wb")
writer.write(outputStream)
outputStream.close()

我收到了 AttributeError: 'str' 对象没有 'seek' 属性的错误。 - meadhikari
1
@meadhikari,抱歉,现在已经修复了。 - John
当我尝试使用outputStream = file("output.pdf","wb")写文件时,我一直收到“AttributeError: addinfourl实例没有__call__方法”的错误提示。非常感谢您的帮助。 - meadhikari
1
@meadhikari 你的代码很好,是我犯了错。outputStream = file("output.pdf","wb") 需要改成 outputStream = open("output.pdf","wb") - John
3
对于 Python 3.5 及更高版本,请使用 urllib.request 而不是 urllib2。 - Shriganesh Kolhe
4
使用 "StringIO" 时,请从 io 库中导入 StringIO 模块。对于 Python 3,可以使用以下代码:from io import StringIO - Shriganesh Kolhe

6

我认为现在可以使用Requests来简化它。

import io
import requests
from PyPDF2 import PdfReader
headers = {'User-Agent': 'Mozilla/5.0 (X11; Windows; Windows x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36'}

url = 'https://www.url_of_pdf_file.com/sample.pdf'
response = requests.get(url=url, headers=headers, timeout=120)
on_fly_mem_obj = io.BytesIO(response.content)
pdf_file = PdfReader(on_fly_mem_obj)

1
现在这就是正确答案。 - rawkintrevo

4

首先,您可以单独下载PDF文件,然后使用pypdf库进行阅读。

import urllib

url = 'http://example.com/a.pdf'
webFile = urllib.urlopen(url)
pdfFile = open(url.split('/')[-1], 'w')
pdfFile.write(webFile.read())
webFile.close()
pdfFile.close()

base = os.path.splitext(pdfFile)[0]
os.rename(pdfFile, base + ".pdf")

input1 = PdfFileReader(file(pdfFile, "rb"))

嘿,这个从行基础= os.path.splitext(thisFile)[0] 是什么文件? - meadhikari
1
哦,抱歉,那是我的错误,应该是pdfFile(下载文件的绝对路径)。 - Switch

2

针对 Python 3.8 版本

import io
from urllib.request import Request, urlopen

from PyPDF2 import PdfFileReader


class GetPdfFromUrlMixin:
    def get_pdf_from_url(self, url):
        """
        :param url: url to get pdf file
        :return: PdfFileReader object
        """
        remote_file = urlopen(Request(url)).read()
        memory_file = io.BytesIO(remote_file)
        pdf_file = PdfFileReader(memory_file)
        return pdf_file

1
你可能会想要使用PdfReader,而不是已弃用的PdfFileReader。 - Martin Thoma
同时,将此函数放置在类内是完全不必要的。 - Martin Thoma

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接