【发布时间】:2021-10-20 20:34:54
【问题描述】:
我重新创建了此视频中制作的 PDF 阅读器程序:
我用我电脑上的一些随机 pdf 文件对其进行了测试,但程序只提取了其中几个文件的文本。为什么会这样?是程序有缺陷,是我遗漏了什么还是某些特定的pdf文件默认无法读取?
这里是完整的代码:
import tkinter as tk
import PyPDF2
from PIL import ImageTk,Image
from tkinter.filedialog import askopenfile
root = tk.Tk()
root.geometry('+%d+%d'%(975,150))
canvas = tk.Canvas(root, width=600, height=300)
canvas.grid(columnspan=3, rowspan=3)
logo = Image.open("tkinterResources/logo.png")
logo = ImageTk.PhotoImage(logo)
logo_label = tk.Label(image=logo)
logo_label.image = logo
logo_label.grid(row=0, column=1)
instructions = tk.Label(root, text="Select a PDF file on yo ur computer to extract all its text", font="Raleway")
instructions.grid(row=1, column=0, columnspan=3)
def open_file():
browse_text.set("loading...")
file = askopenfile(parent=root, mode="rb", title="Choose a file", filetype=[("Pdf file", "*.pdf")])
if file:
read_pdf = PyPDF2.PdfFileReader(file)
page = read_pdf.getPage(0)
page_content = page.extractText()
text_box = tk.Text(root, height=10, width=50, padx=15, pady=15)
text_box.insert(1.0, page_content)
text_box.tag_configure("center", justify="center")
text_box.tag_add("center", 1.0, "end")
text_box.grid(row=3, column=1)
browse_text.set("Browse")
browse_text = tk.StringVar()
browse_btn = tk.Button(root, textvariable = browse_text,
font="Raleway", bg="#20bebe", fg="white", height=2, width=15,
command=open_file)
browse_text.set("Browse")
browse_btn.grid(row=2, column=1)
canvas = tk.Canvas(root, width=600, height=250)
canvas.grid(columnspan=3)
root.mainloop()
我还使用 OpenOffice 创建了自己的 pdf 文件,其中只有一行文本,但即使这样似乎也不起作用。
【问题讨论】:
-
1) 您能否准确告诉我们如何您的 Python/TKinter 应用程序正在“读取”.pdf 文件?你在用什么图书馆?您在进行哪些 API 调用?请显示一些代码。 2)您是否考虑过您可能无法“从 .pdf 读取文本”......因为有问题的 .pdf 具有位图图像(与文本内容相比)? PS:感谢您编辑您的帖子,并更新:1)您正在使用 PyPDF2,2)显示示例代码 :)
-
@paulsm4 抱歉,我刚开始忘记粘贴代码,但我现在已经完成了。如果我理解正确,有问题的 .pdf 不应包含任何类型的图像,仅包含文本行。如果可能有一些隐藏的位图图像可以定义页面的设置,我想知道,如果是这样,我只是想知道它是如何工作的。
标签: python python-3.x pdf tkinter pypdf2