如何使用python突出显示pdf上的文本?

bf1o4zei  于 2021-08-25  发布在  Java
关注(0)|答案(0)|浏览(248)

我正在尝试制作一个python脚本,允许用户输入pdf,然后用户将输入要搜索的单词,如果找到这些单词,则突出显示并导出为唯一的文件名。如果找不到单词,我会运行代码,但由于某种原因,当找到单词时,此代码会中断。欢迎提供任何帮助或建议!


### IMPORT PACKAGES NEEDED

import sys
from inspect import cleandoc

# !pip install PyMuPDF==1.16.14

import fitz
import time
import PySimpleGUI as sg
import sys
searchingWords = []

### READ IN PDF

sg.theme('BlueMono')
inputfname = sg.popup_get_file('PDF Browser', 'PDF file to open', file_types=(("PDF Files", "*.pdf"),))
if inputfname is None:
    sg.popup_cancel('Cancelled.')
    exit(0)
print(inputfname)
doc = fitz.open(inputfname)

### USER INPUTTING WORDS

# Window definition

layout = [[sg.Text("What word or phrase do you want to search for?")],
          [sg.Input(key='-INPUT-', do_not_clear=False)],
          [sg.Text(size=(40,1), key='-OUTPUT-')],
          [sg.Button('Next word', ), sg.Button('Confirm'), sg.Button('Next word enter', visible=False, bind_return_key=True)]]

# Create the window

window = sg.Window('Word Search', layout)

# Display window

while True:
    event, values = window.read()
    # See if user wants to quit or window was closed
    if event == sg.WINDOW_CLOSED or event == 'Confirm':
        break
    # Output a message to the window
    searchingWords.append(values['-INPUT-'])
    window['-OUTPUT-'].update(str(searchingWords))

# Remove window

window.close()

### END USER INPUT FOR SEARCH WORDS

for page in doc:
    ### SEARCHING FOR THE WORDS
    for word in searchingWords:
        # ??? How to change this to ensure there is a non-alphabetic letter next to it?
        text = str(word)
        text_instances = page.searchFor(text)
        ### HIGHLIGHTING THE WORDS
        for inst in text_instances:
            highlight = page.addHighlightAnnot(inst)
            highlight.update()

### SET FILE OUTPUT NAME

datetimefilename = time.strftime("%m-%d-%Y-%H.%M.%S") + "Highlighted.pdf"

### OUTPUT

doc.save(str(datetimefilename), garbage=4, deflate=True, clean=True)

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题