Read PDF Files with wxPython

bumsfeld 0 Tallied Votes 2K Views Share

Using the wx.lib.pdfwin.PDFWindow one can read Adobe PDF files (.pdf) with wxPython. The PDF file format is popular document file format allowing mixing of text and graphics. The GUI toolkit wxPython's newer wx.activex module allows one to use the ActiveX control, as if it would be one wx.Window. It actually embeds the Adobe Acrobat Reader into the wx.Window.

# read PDF files (.pdf) with wxPython
# using wx.lib.pdfwin.PDFWindow class ActiveX control
# from wxPython's new wx.activex module, this allows one
# to use an ActiveX control, as if it would be wx.Window
# it embeds the Adobe Acrobat Reader
# as far as HB knows this works only with Windows
# tested with Python24 and wxPython26 by HB

import  wx

if wx.Platform == '__WXMSW__':
    from wx.lib.pdfwin import PDFWindow


class MyPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, id=-1)
        self.pdf = None

        sizer = wx.BoxSizer(wx.VERTICAL)
        btnSizer = wx.BoxSizer(wx.HORIZONTAL)

        self.pdf = PDFWindow(self, style=wx.SUNKEN_BORDER)

        sizer.Add(self.pdf, proportion=1, flag=wx.EXPAND)

        btn = wx.Button(self, wx.NewId(), "Open PDF File")
        self.Bind(wx.EVT_BUTTON, self.OnOpenButton, btn)
        btnSizer.Add(btn, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)

        btn = wx.Button(self, wx.NewId(), "Previous Page")
        self.Bind(wx.EVT_BUTTON, self.OnPrevPageButton, btn)
        btnSizer.Add(btn, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)

        btn = wx.Button(self, wx.NewId(), "Next Page")
        self.Bind(wx.EVT_BUTTON, self.OnNextPageButton, btn)
        btnSizer.Add(btn, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)

        btnSizer.Add((50,-1), proportion=2, flag=wx.EXPAND)
        sizer.Add(btnSizer, proportion=0, flag=wx.EXPAND)

        self.SetSizer(sizer)
        self.SetAutoLayout(True)

    def OnOpenButton(self, event):
        # make sure you have PDF files available on your drive
        dlg = wx.FileDialog(self, wildcard="*.pdf")
        if dlg.ShowModal() == wx.ID_OK:
            wx.BeginBusyCursor()
            self.pdf.LoadFile(dlg.GetPath())
            wx.EndBusyCursor()
        dlg.Destroy()

    def OnPrevPageButton(self, event):
        self.pdf.gotoPreviousPage()

    def OnNextPageButton(self, event):
        self.pdf.gotoNextPage()


app = wx.PySimpleApp()
# create window/frame, no parent, -1 is default ID, title, size
frame = wx.Frame(None, -1, "PDFWindow", size = (640, 480))
# make an instance of the class
MyPanel(frame)
# show the frame
frame.Show(True)
# start the event loop
app.MainLoop()

Dani AI

Generated

If you want the PDF inside your wxPython window (not in a browser), there are three practical paths.

  1. Windows + Acrobat ActiveX (what @bumsfeld described). This embeds Adobe Reader via wx.lib.pdfwin.PDFWindow. It requires Adobe Reader to be installed and comtypes available (what @richardtreier hit), and you should match 32/64-bit between Python and Reader. To avoid the close-time access violation @bucefala saw, call FreeDlls() before destroying the frame.
import wx
from wx.lib.pdfwin import PDFWindow

class Main(wx.Frame):
    def __init__(self, path):
        super().__init__(None, title="PDF (ActiveX)")
        self.viewer = PDFWindow(self)
        self.viewer.LoadFile(path)
        self.Bind(wx.EVT_CLOSE, self.on_close)

    def on_close(self, evt):
        try:
            self.viewer.FreeDlls()
        finally:
            self.Destroy()

app = wx.App(False)
Main(r"C:\path\file.pdf").Show()
app.MainLoop()

See the PDFWindow API (note FreeDlls) for details. (docs.wxpython.org)

  1. Cross-platform via an embedded web view. wx.html2.WebView renders with Edge WebView2 on Windows and WebKit on macOS/Linux. Modern Edge/WebView2 has a built‑in PDF viewer, so simply load a file:// URL. Example:
import wx, wx.html2
from pathlib import Path

wv = wx.html2.WebView.New(parent)
wv.LoadURL(Path("file.pdf").resolve().as_uri())

If you target Windows, ensure the WebView2 Runtime is present on user machines. (docs.wxpython.org)

  1. Pure wxPython viewer (no browser/ActiveX). wx.lib.pdfviewer renders PDFs inside your app using PyMuPDF for best results. This is fully cross‑platform and avoids Reader/WebView dependencies. (docs.wxpython.org)

Notes:

  • webbrowser.open will open your default browser by design; use one of the above to keep the PDF in‑app.
  • is right for opening externally; for in‑app UX, prefer WebView or pdfviewer.
  • For wxActiveX specifics, the wx.lib.pdfwin.PDFWindow docs and the wx demo’s ActiveX sample are the canonical starting points. (docs.wxpython.org)
richardtreier 0 Newbie Poster

i cant do it... i get a errormessage:
Traceback (most recent call last):
File "C:\Users\richardtreier\Desktop\", line 4, in <module>
from wx.lib.pdfwin import PDFWindow
File "C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\lib\", line 28, in <module>
import wx.lib.activex
File "C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\lib\", line 36, in <module>
import comtypes
ImportError: No module named comtypes

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Do you have the Adobe Acrobat Reader installed?

richardtreier 0 Newbie Poster

The problem is gone... i just installed comtypes ^^.

Dilip101 0 Newbie Poster

Could you suggest some tutorials on wxActiveX. I could not find any on the net. Thanks

Using the wx.lib.pdfwin.PDFWindow one can read Adobe PDF files (.pdf) with wxPython. The PDF file format is popular document file format allowing mixing of text and graphics. The GUI toolkit wxPython's newer wx.activex module allows one to use the ActiveX control, as if it would be one wx.Window. It actually embeds the Adobe Acrobat Reader into the wx.Window.

srujana_1 0 Newbie Poster
helpMenu = wx.Menu()
        i = helpMenu.Append(-1, _("Online documentation..."))
        self.Bind(wx.EVT_MENU, lambda e: webbrowser.open_new("C:\Users\hello\Desktop\filename.pdf"), i)

Hello, i use the above code for opening pdf file , but it's not opening, instead it's opening a webbrowser , can anyone suggest

Gribouillis 1,391 Programming Explorer Team Colleague

I don't have windows, but you can try and replace the lambda with

lambda e: os.startfile("C:\Users\hello\Desktop\filename.pdf")

Please start new threads with the tag "python" when you have different questions.

edit: bugfix

bucefala 0 Newbie Poster

I copy and paste this code un py file.
When close the windows I got this error
"
Exception exceptions.WindowsError: 'exception: access violation reading 0x573570B2' in <b
ound method POINTER(IAcroAXDocShim).del of <POINTER(IAcroAXDocShim) ptr=0x780590 at 3
b1b170>> ignored
"
I couldn't find the solution...

Gribouillis 1,391 Programming Explorer Team Colleague

Here is how I currently open pdf files from python in linux

        from webbrowser import BackgroundBrowser
        browser = BackgroundBrowser('/usr/bin/okular')
        browser.args.extend(
            ['--icon', 'okular', '-caption', 'Okular']
        )
        browser.open("/path/to/file.pdf")  # It works !

You could try something similar in windows using the name of your pdf reader executable instead of okular. For example for acrobat reader, the name could be AcroRd32.exe. Find the correct name/path on your computer

bucefala 0 Newbie Poster

Yes, I found this solution

import webbrowser
webbrowser.open_new(r'file://'+_filePath)

but this open the file outside the app.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.