Reputation: 1039
How would I open a pdf from url instead of from the disk
Something like
input1 = PdfFileReader(file("http://example.com/a.pdf", "rb"))
I want to open several files from web and download a merge of all the files.
Upvotes: 15
Views: 42917
Reputation: 91
I think it could be simplified with Requests now.
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)
Upvotes: 9
Reputation: 6779
For 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
Upvotes: 2
Reputation: 13699
I think urllib2 will get you what you want.
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()
Upvotes: 21
Reputation: 15453
Well, you can first download the pdf separately and then use pypdf to read it
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"))
Upvotes: 4