Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display a pdf that has been downloaded in python

I have grabbed a pdf from the web using for example

import requests
pdf = requests.get("http://www.scala-lang.org/docu/files/ScalaByExample.pdf")

I would like to modify this code to display it

from gi.repository import Poppler, Gtk

def draw(widget, surface):
    page.render(surface)

document = Poppler.Document.new_from_file("file:///home/me/some.pdf", None)
page = document.get_page(0)

window = Gtk.Window(title="Hello World")
window.connect("delete-event", Gtk.main_quit)
window.connect("draw", draw)
window.set_app_paintable(True)

window.show_all()
Gtk.main()

How do I modify the document = line to use the variable pdf that contains the pdf?

(I don't mind using popplerqt4 or anything else if that makes it easier.)

like image 220
marshall Avatar asked Feb 10 '14 17:02

marshall


People also ask

How do I open a PDF file in Python?

Popen() — Without CMD. If you want to open a PDF file in the standard PDF viewer such as Adobe Acrobat Reader, you can use the subprocess. Popen([path], shell=True) command. This doesn't open an intermediary command line prompt but opens the PDF directly in the viewer.


2 Answers

It all depends on the OS your using. These might usually help:

import os
os.system('my_pdf.pdf')

or

os.startfile('path_to_pdf.pdf')

or

import webbrowser
webbrowser.open(r'file:///my_pdf.pdf')
like image 119
Beatriz Kanzki Avatar answered Sep 22 '22 14:09

Beatriz Kanzki


How about using a temporary file?

import tempfile
import urllib
import urlparse

import requests

from gi.repository import Poppler, Gtk

pdf = requests.get("http://www.scala-lang.org/docu/files/ScalaByExample.pdf")

with tempfile.NamedTemporaryFile() as pdf_contents:
    pdf_contents.file.write(pdf)
    file_url = urlparse.urljoin(
        'file:', urllib.pathname2url(pdf_contents.name))
    document = Poppler.Document.new_from_file(file_url, None)
like image 24
logc Avatar answered Sep 20 '22 14:09

logc