1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Copy selected text from PDF in PyQt5 QWebEngineView

Discussão em 'Python' iniciado por Stack, Setembro 23, 2024.

  1. Stack

    Stack Membro Participativo

    I use PyQt5.QtWebEngineWidgets to display a PDF and I'm trying to get the selected text. Using hasSelection() and selectedText() works on HTML files, but it fails when the web view displays a PDF file. Any idea how to copy the selected text (apart from using CTRL+C)?

    from PyQt5.QtCore import QUrl
    from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QMenu
    from PyQt5.QtWebEngineWidgets import QWebEngineSettings, QWebEngineView

    class Browser(QWebEngineView):
    def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)

    def get_selection(self):
    if self.hasSelection():
    print(self.selectedText())
    else:
    print('No text selected')

    def contextMenuEvent(self, event):
    self.menu = QMenu()
    get_selection = self.menu.addAction('Copy')
    get_selection.triggered.connect(self.get_selection)
    self.menu.popup(event.globalPos())

    class MainWindow(QMainWindow):
    def __init__(self):
    super(QMainWindow, self).__init__()
    self.setWindowTitle("PDF Viewer")
    self.setGeometry(0, 28, 1000, 750)
    self.webView = QWebEngineView()
    self.webView = Browser()
    self.webView.settings().setAttribute(QWebEngineSettings.PluginsEnabled, True)
    self.webView.settings().setAttribute(QWebEngineSettings.PdfViewerEnabled, True)
    self.setCentralWidget(self.webView)

    if __name__ == '__main__':

    import sys
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    win.webView.setUrl(QUrl.fromLocalFile("d:/test.pdf"))
    sys.exit(app.exec_())

    Continue reading...

Compartilhe esta Página