如何在 Python 中查看 PDF 文件
本文將探討如何使用IronPDF庫在 Python 中檢視 PDF 檔案。
IronPDF - Python 函式庫
IronPDF是一個功能強大的 Python 庫,它使開發人員能夠以程式設計方式處理 PDF 檔案。 使用IronPDF,您可以輕鬆產生、操作和提取 PDF 文件中的數據,使其成為處理各種 PDF 相關任務的多功能工具。 無論您是需要從頭開始建立 PDF、修改現有 PDF 還是從 PDF 中提取內容, IronPDF都提供了一套全面的功能來簡化您的工作流程。
IronPDF for Python 函式庫的一些功能包括:
- 使用 HTML 或 URL 從頭開始建立新的 PDF 文件
- 編輯現有 PDF 文件
- 旋轉 PDF 頁面
- 從 PDF 檔案中提取文字、元資料和圖像
- 將 PDF 檔案轉換為其他格式
- 使用密碼和限制保護 PDF 文件 -拆分和合併PDF文件
注意: IronPDF產生的 PDF 資料檔附有浮水印。要去除浮水印,您需要購買IronPDF 的許可。 如果您想使用IronPDF的授權版本,請造訪IronPDF網站取得授權金鑰。
先決條件
在 Python 中使用IronPDF之前,需要滿足一些先決條件:
- Python 安裝:確保您的系統上已安裝 Python。 IronPDF與 Python 3.x 版本相容,因此請確保您已安裝相容的 Python 版本。
IronPDF庫:安裝IronPDF庫以使用其功能。 您可以使用 Python 套件管理器 ( pip ) 安裝它,只需在命令列介面中執行以下命令:
pip install ironpdfpip install ironpdfSHELLTkinter 函式庫: Tkinter 是 Python 的標準 GUI 工具包。 它用於為提供的程式碼片段中的 PDF 檢視器建立圖形使用者介面。 Tkinter 通常會隨 Python 預先安裝,但如果遇到任何問題,您可以使用套件管理器安裝它:
pip install tkinterpip install tkinterSHELLPillow 函式庫: Pillow 函式庫是 Python Imaging Library (PIL) 的一個分支,提供了額外的影像處理功能。 這段程式碼片段用於載入和顯示從 PDF 中提取的圖像。 使用軟體套件管理器安裝 Pillow:
pip install pillowpip install pillowSHELL
5.整合開發環境 (IDE):使用 IDE 處理 Python 專案可以大幅提升您的開發體驗。 它提供了程式碼自動完成、調試和更簡化的工作流程等功能。 PyCharm 是 Python 開發中一款受歡迎的 IDE。 您可以從 JetBrains 網站 ( https://www.jetbrains.com/pycharm/ ) 下載並安裝 PyCharm。 6.文字編輯器:或者,如果您喜歡使用輕量級的文字編輯器,您可以選擇任何文字編輯器,例如 Visual Studio Code、Sublime Text 或 Atom。 這些編輯器為 Python 開發提供了語法高亮和其他實用功能。 您也可以使用 Python 自帶的 IDE 應用程式來建立 Python 腳本。
使用 PyCharm 建立 PDF 檢視器項目
安裝 PyCharm IDE 後,請依照下列步驟建立一個 PyCharm Python 專案:
1.啟動 PyCharm:從系統應用程式啟動器或桌面捷徑開啟 PyCharm。 2.建立新專案:點選"建立新專案"或開啟一個現有的 Python 專案。

**PyCharm IDE**3.配置項目設定:為您的專案提供名稱,並選擇建立專案目錄的位置。 為您的專案選擇 Python 解釋器。 然後點擊"創建"。

**建立一個新的 Python 項目**4.建立原始檔案: PyCharm 將建立專案結構,包括一個主 Python 檔案和一個用於存放其他來源檔案的目錄。 開始編寫程式碼,然後按一下執行按鈕或按 Shift+F10 執行腳本。
使用IronPDF在 Python 中查看 PDF 文件的步驟
導入所需的庫
首先,導入必要的庫。 在這種情況下,需要 tkinter 和 PIL 庫。 os 和 shutil 庫用於文件和資料夾操作,ironpdf 是用於處理 PDF 文件的庫,tkinter 用於創建圖形用戶界面 (GUI),PIL 用於圖像處理。
import os
import shutil
import ironpdf
from tkinter import *
from PIL import Image, ImageTkimport os
import shutil
import ironpdf
from tkinter import *
from PIL import Image, ImageTk將 PDF 文件轉換為圖像
接下來,定義一個名為 convert_pdf_to_images 的函數。 此函數以 PDF 檔案的路徑作為輸入。 函數內部使用IronPDF庫從文件中載入 PDF 文件。然後,指定一個資料夾路徑來儲存提取的影像檔案。 IronPDF 的 pdf.RasterizeToImageFiles 方法用於將 PDF 的每一頁轉換為圖像文件,並將其保存在指定的資料夾中。 使用列表來儲存影像路徑。 完整的程式碼範例如下:
def convert_pdf_to_images(pdf_file):
"""Convert each page of a PDF file to an image."""
pdf = ironpdf.PdfDocument.FromFile(pdf_file)
# Extract all pages to a folder as image files
folder_path = "images"
pdf.RasterizeToImageFiles(os.path.join(folder_path, "*.png"))
# List to store the image paths
image_paths = []
# Get the list of image files in the folder
for filename in os.listdir(folder_path):
if filename.lower().endswith((".png", ".jpg", ".jpeg", ".gif")):
image_paths.append(os.path.join(folder_path, filename))
return image_pathsdef convert_pdf_to_images(pdf_file):
"""Convert each page of a PDF file to an image."""
pdf = ironpdf.PdfDocument.FromFile(pdf_file)
# Extract all pages to a folder as image files
folder_path = "images"
pdf.RasterizeToImageFiles(os.path.join(folder_path, "*.png"))
# List to store the image paths
image_paths = []
# Get the list of image files in the folder
for filename in os.listdir(folder_path):
if filename.lower().endswith((".png", ".jpg", ".jpeg", ".gif")):
image_paths.append(os.path.join(folder_path, filename))
return image_paths若要從 PDF 文件中提取文本,請造訪此程式碼範例頁面。
把手窗戶關閉
為了在應用程式視窗關閉時清理提取的映像文件,定義一個 on_closing 函數。 在這個函數內部,使用 shutil.rmtree() 方法刪除整個 images 資料夾。 接下來,將此函數設定為視窗關閉時要執行的協定。 以下程式碼有助於實現該任務:
def on_closing():
"""Handle the window closing event by cleaning up the images."""
# Delete the images in the 'images' folder
shutil.rmtree("images")
window.destroy()
window.protocol("WM_DELETE_WINDOW", on_closing)def on_closing():
"""Handle the window closing event by cleaning up the images."""
# Delete the images in the 'images' folder
shutil.rmtree("images")
window.destroy()
window.protocol("WM_DELETE_WINDOW", on_closing)建立圖形使用者介面視窗
現在,讓我們使用 Tk() 建構函數來建立主 GUI 窗口,將視窗標題設為"影像檢視器",並將 on_closing() 函數設定為處理視窗關閉的協定。
window = Tk()
window.title("Image Viewer")
window.protocol("WM_DELETE_WINDOW", on_closing)window = Tk()
window.title("Image Viewer")
window.protocol("WM_DELETE_WINDOW", on_closing)建立可捲動畫布
若要顯示影像並啟用捲動,請建立一個 Canvas 小工具。 Canvas 小工具配置為填滿可用空間,並使用 pack(side=LEFT, fill=BOTH, expand=True) 向兩個方向擴展。 此外,建立一個 Scrollbar 小工具,並將其配置為控制所有頁面和畫布的垂直捲動。
canvas = Canvas(window)
canvas.pack(side=LEFT, fill=BOTH, expand=True)
scrollbar = Scrollbar(window, command=canvas.yview)
scrollbar.pack(side=RIGHT, fill=Y)
canvas.configure(yscrollcommand=scrollbar.set)
# Update the scrollregion to encompass the entire canvas
canvas.bind("<Configure>", lambda e: canvas.configure(
scrollregion=canvas.bbox("all")))
# Configure the vertical scrolling using mouse wheel
canvas.bind_all("<MouseWheel>", lambda e: canvas.yview_scroll(
int(-1*(e.delta/120)), "units"))canvas = Canvas(window)
canvas.pack(side=LEFT, fill=BOTH, expand=True)
scrollbar = Scrollbar(window, command=canvas.yview)
scrollbar.pack(side=RIGHT, fill=Y)
canvas.configure(yscrollcommand=scrollbar.set)
# Update the scrollregion to encompass the entire canvas
canvas.bind("<Configure>", lambda e: canvas.configure(
scrollregion=canvas.bbox("all")))
# Configure the vertical scrolling using mouse wheel
canvas.bind_all("<MouseWheel>", lambda e: canvas.yview_scroll(
int(-1*(e.delta/120)), "units"))創建圖像框架
接下來,在畫布內創建一個 Frame 小部件來容納圖像,方法是使用 create_window() 將框架放置在畫布內。 (0, 0) 座標和 anchor='nw' 參數確保幀從畫布的左上角開始。
frame = Frame(canvas)
canvas.create_window((0, 0), window=frame, anchor="nw")frame = Frame(canvas)
canvas.create_window((0, 0), window=frame, anchor="nw")將 PDF 文件轉換為圖像並顯示
下一步是呼叫 convert_pdf_to_images() 函數,並傳入輸入 PDF 檔案的檔案路徑名。函數會將 PDF 頁面提取為圖像,並傳回圖像路徑清單。 透過遍歷圖像路徑並使用 PIL 庫中的 Image.open() 方法載入每個圖像,即可使用 ImageTk.PhotoImage() 建立一個 PhotoImage 物件。 然後建立一個 Label 小工具來顯示影像。
images = convert_pdf_to_images("input.pdf")
# Load and display the images in the Frame
for image_path in images:
image = Image.open(image_path)
photo = ImageTk.PhotoImage(image)
label = Label(frame, image=photo)
label.image = photo # Store a reference to prevent garbage collection
label.pack(pady=10)images = convert_pdf_to_images("input.pdf")
# Load and display the images in the Frame
for image_path in images:
image = Image.open(image_path)
photo = ImageTk.PhotoImage(image)
label = Label(frame, image=photo)
label.image = photo # Store a reference to prevent garbage collection
label.pack(pady=10)
輸入檔
運行 GUI 主循環
最後,讓我們使用 window.mainloop() 來運行主事件循環。 這樣可以確保圖形使用者介面視窗保持開啟和回應狀態,直到使用者將其關閉。
window.mainloop()window.mainloop()
使用者介面輸出
結論
本教學探討如何使用IronPDF庫在 Python 中檢視 PDF 文件。 它涵蓋了打開 PDF 文件並將其轉換為一系列圖像文件所需的步驟,然後在可滾動畫布中顯示這些圖像,以及在應用程式關閉時處理提取圖像的清理工作。
有關IronPDF for Python 庫的更多詳細信息,請參閱文件。
下載並安裝IronPDF for Python庫,還可以獲得免費試用版,以測試其在商業開發中的完整功能。
常見問題解答
我如何在 Python 中查看 PDF 文件?
您可以使用 IronPDF 庫在 Python 中查看 PDF 文件。它允許您将 PDF 頁面轉换為图像,然後可以使用 Tkinter 在 GUI 應用程序中顯示。
创建 Python PDF 查看器的必要步骤是什么?
要在 Python 中创建 PDF 查看器,您需要安装 IronPDF,使用 Tkinter 创建 GUI,使用 Pillow 進行图像處理。使用 IronPDF 将 PDF 頁面轉换為图像,并在使用 Tkinter 创建的可滚動画布中顯示它们。
如何為 Python 項目安装 IronPDF?
您可以通過在终端或命令提示符中運行命令 pip install ironpdf 来安装 IronPDF。
在 Python 中构建 PDF 查看器應用程序需要哪些庫?
您将需要 IronPDF 處理 PDF、Tkinter 進行 GUI、Pillow 進行图像處理。
我可以使用 Python 從 PDF 提取图像嗎?
是的,IronPDF 允許您從 PDF 中提取图像,然後可以使用 Pillow 庫進行處理或顯示。
如何在 Python 中将 PDF 頁面轉换為图像?
您可以使用 IronPDF 功能将 PDF 頁面轉换為图像格式,然後可以在 Python 應用程序中進行操作或顯示。
如何在 Python PDF 查看器應用程序中處理窗口关闭?
在 PDF 查看器應用程序中,您可以通過清理提取的图像并确保所有资源都已正确释放来處理窗口关闭,通常使用 Tkinter 的事件處理功能。
如何在 Python 中保护 PDF 文件?
IronPDF 提供通過向 PDF 文件添加密碼和使用限制来增強 PDF 安全性的選項。
在 PDF 查看應用程序中使用 Tkinter 的优势是什么?
Tkinter 允許您為 PDF 查看器创建用戶友好的图形界面,使用戶可以通過可滚動视图浏览 PDF 頁面。
在 PDF 項目中使用 Pillow 的目的是什么?
Pillow 在 PDF 項目中用于處理图像,例如加载和顯示從 PDF 文件中提取的图像。










