I use PyQt5.QtWebEngineWidgets
to display a pdf. In this pdf I added links over certain words with PyMuPDF
. The links are created with this code:
def create_pdf_with_links():
doc = fitz.open("test.pdf")
for count, page in enumerate(doc):
text_instances = page.search_for("Kontrollstelle")
for instance in text_instances:
d = {'kind': 2, 'xref': 0, 'from': instance, 'uri': 'data:Hallo Welt', 'id': ''}
page.insert_link(d)
doc.save("test.pdf")
Now I want to get the data saved inside the links, when I click on them. Therefore I modified QWebEnginePage
and the link scheme based on another question of mine. Unfortunately, I don't get any response, when clicking on the link. When I add a typical url as link content, the corresponding page is loaded. The code for displaying the pdf and handling the link looks like this:
class MyWebEnginePage(QWebEnginePage):
dataLinkClicked = pyqtSignal(str)
def acceptNavigationRequest(self, url, _type, isMainFrame):
if (_type == QWebEnginePage.NavigationTypeLinkClicked and
url.scheme() == 'data'):
# send only the url path
self.dataLinkClicked.emit(url.path())
return False
return super().acceptNavigationRequest(url, _type, isMainFrame)
class App(QMainWindow):
def __init__(self):
super(App, self).__init__()
self.pdf_path = os.path.abspath("test.pdf")
webView = QWebEngineView()
page = MyWebEnginePage(self)
# connect to the signal
page.dataLinkClicked.connect(self.handleDataLink)
webView.setPage(page)
# use a data-url
webView.settings().setAttribute(QWebEngineSettings.PluginsEnabled, True)
webView.settings().setAttribute(QWebEngineSettings.PdfViewerEnabled, True)
webView.setUrl(QUrl.fromLocalFile(self.pdf_path))
self.setCentralWidget(webView)
def handleDataLink(self, text):
print(text) # should print the link: "Hallo Welt"
if __name__ == '__main__':
app = QApplication(sys.argv)
window = App()
window.setGeometry(800, 100, 1000, 800)
window.show()
sys.exit(app.exec_())
How do I get the data from the link?