Search code examples
pythonpyqtpyqt5pymupdf

How to read pdf files with pymupdf in PyQt5?


I want to open pdf file through pilihfile pushbutton, then take its name to display on textEdit and display its pdf contents on textEdit_2 by using pymupdf. But i got error said cannot open ('D:/Kuliah/KRIP.pdf', 'PDF Files (*.pdf)'): Invalid argument. I do not know how to fix it.

def pilihfile(self):
    files = QFileDialog.getOpenFileName(None, "Open File", "", "PDF Files (*.pdf)")
    file_name = str(files))

    pdf_document = file_name
    self.textEdit.setText(pdf_document)
    doc = fitz.open(pdf_document)
    hal = doc.pageCount

    for i in range (hal):
        page = doc.loadPage(i)
        page1text = page.get_text().strip()
        self.textEdit_2.setPlainText(page1text)

Solution

  • Based on your error message, pdf_document has actually the value of ('D:/Kuliah/KRIP.pdf', 'PDF Files (*.pdf)'). This is because you use QtWidgets.QFileDialog.getOpenFileName with PyQt5 which returns a tuple instead of just a str (check this). If that is the case, try:

    files, _ = QFileDialog.getOpenFileName(None, "Open File", "", "PDF Files (*.pdf)")