How to Open a PDF File in Python?

Rate this post

In this tutorial, you’ll learn how to open a PDF file in an external PDF reader or the browser, using a simple Python command. There are many variants to this problem, so let’s dive right into the different ones—and their solutions!

Method 1: Open PDF Standard Viewer with os.system(path) — With CMD

You can open a PDF file in your standard PDF program such as Adobe Acrobat Reader using the command os.system(path) using the os module and the path string to the PDF file. This opens a command-line shell as an intermediate operating system program that in turn opens the PDF.

import os
path = 'my_file.pdf'
os.system(path)

Method 2: Open PDF Standard Viewer with subprocess.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.

# Method 2: Open with subprocess
import subprocess
path = 'my_file.pdf'
subprocess.Popen([path], shell=True)

Method 3: Open PDF Standard Program with webbrowser.open_new()

If you want to open a PDF file in the standard PDF viewer such as Adobe Acrobat Reader, you can use the webbrowser.open_new(path) command. This doesn’t open an intermediary command line prompt but opens the PDF directly in the viewer.

# Method 3: Open with webbrowser
import webbrowser
path = 'my_file.pdf'
webbrowser.open_new(path)

Method 4: Open PDF with Python Given an URL

If you want to open a PDF file in the standard web browser, given any URL to the PDF, you can use the webbrowser.open_new(url) command.

# Method 4: Open with Webbrowser
import webbrowser
path = 'https://blog.finxter.com/wp-content/uploads/2019/02/CheatSheet-Python-2_-Data-Structures.docx.pdf'
webbrowser.open_new(path)

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!