PYTHON PDF 工具 如何在 Python 中創建 PDF 文件 Curtis Chau 更新:6月 22, 2025 下載 IronPDF pip 下載 開始免費試用 法學碩士副本 法學碩士副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在 Grok 中打開 向 Grok 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 PDF(便攜式文件格式)是目前最受歡迎的用於線上傳送和接收資料的數位文件格式。它主要用於保持資料格式的完整性,並透過加密密碼保護資料安全。 .pdf 副檔名與軟體應用程式、硬體或作業系統無關。 本文將介紹如何使用 Python 程式語言建立 PDF 檔案。 網路上有很多方法可以建立 PDF 文件,但在這裡我們將使用 Python 庫。 以下是兩個著名的 Python 程式庫,可用於產生單頁或多頁 PDF 文件: Reportlab PDFKit 我們可以使用上面提到的任何 PDF Python 庫來產生 PDF 文件。 如何在Python中建立PDF檔案? 讓我們逐一了解這兩個函式庫。 使用 Reportlab 庫建立 PDF 文件 Reportlab程式庫是一個免費的開源 PDF 工具包,可用於輕鬆建立 PDF 檔案。 它提供了一系列繪圖工具,用於在多個頁面的特定位置添加圖像和文字。 您也可以使用encryptCanvas方法建立加密的 PDF 檔案。 安裝 要安裝 Reportlab,需要 pip 套件管理器。 它會使用 pip 命令自動下載並安裝所需的軟體包。 只需在 Windows 命令提示字元或 PowerShell 中輸入以下命令: pip install reportlab pip install reportlab SHELL 注意:安裝 Python 時,必須將其新增至路徑環境變數中,才能從 cmd 或 PowerShell 中的任何位置執行上述命令。 建議在 Python 3+ 中使用 Pip,因為它是最新版本。 開啟一個新的 Python 文件 要使用 Reportlab 函式庫,我們需要在 Python 檔案中編寫程式碼並執行它來建立 PDF 檔案。 從 Windows 搜尋列搜尋並開啟 Python 預設 IDLE shell,然後按 Ctrl + N 或從"檔案"標籤中選擇"新建檔案"。 這將打開文字編輯器,用於編寫程式碼。 接下來,將文件儲存為適當的名稱。 我把它命名為"createpdf.py" 。 用於建立 PDF 的 Python 程式碼 以下程式碼將在幾秒鐘內繪製文件元素並產生 PDF 文件: # Importing required modules from ReportLab from reportlab.pdfgen import canvas from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfbase import pdfmetrics from reportlab.lib import colors # File and document attributes fileName = 'sample.pdf' documentTitle = 'sample' title = 'Create PDF' subTitle = 'Using ReportLab !!' # Creating a PDF object pdf = canvas.Canvas(fileName) # Setting the title of the document pdf.setTitle(documentTitle) # Registering a TrueType font pdfmetrics.registerFont(TTFont('abc', 'Arial.ttf')) # Creating the title by setting its font and placing it on the canvas pdf.setFont('abc', 36) pdf.drawCentredString(300, 770, title) # Creating the subtitle by setting its font, color, and placing it on the canvas pdf.setFillColorRGB(0, 0, 255) # Set color to blue pdf.setFont("Courier-Bold", 24) pdf.drawCentredString(290, 720, subTitle) # Saving the PDF pdf.save() # Importing required modules from ReportLab from reportlab.pdfgen import canvas from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfbase import pdfmetrics from reportlab.lib import colors # File and document attributes fileName = 'sample.pdf' documentTitle = 'sample' title = 'Create PDF' subTitle = 'Using ReportLab !!' # Creating a PDF object pdf = canvas.Canvas(fileName) # Setting the title of the document pdf.setTitle(documentTitle) # Registering a TrueType font pdfmetrics.registerFont(TTFont('abc', 'Arial.ttf')) # Creating the title by setting its font and placing it on the canvas pdf.setFont('abc', 36) pdf.drawCentredString(300, 770, title) # Creating the subtitle by setting its font, color, and placing it on the canvas pdf.setFillColorRGB(0, 0, 255) # Set color to blue pdf.setFont("Courier-Bold", 24) pdf.drawCentredString(290, 720, subTitle) # Saving the PDF pdf.save() PYTHON 程式碼解釋 導入所有模組和套件之後,我們首先初始化了所有將要寫入 PDF 文件的內容。 fileName = 'sample.pdf' documentTitle = 'sample' title = 'Create PDF' subTitle = 'Using ReportLab !!' fileName = 'sample.pdf' documentTitle = 'sample' title = 'Create PDF' subTitle = 'Using ReportLab !!' PYTHON 現在,我們建立 PDF 畫布,設定文件標題,然後在畫布上新增居中的標題和副標題,並使用適當的字體和大小。 # Creating a PDF object pdf = canvas.Canvas(fileName) # Setting the title of the document pdf.setTitle(documentTitle) # Registering a TrueType font pdfmetrics.registerFont(TTFont('abc', 'Arial.ttf')) # Creating the title by setting its font and placing it on the canvas pdf.setFont('abc', 36) pdf.drawCentredString(300, 770, title) # Creating the subtitle by setting its font, color, and placing it on the canvas pdf.setFillColorRGB(0, 0, 255) # Set color to blue pdf.setFont("Courier-Bold", 24) pdf.drawCentredString(290, 720, subTitle) # Creating a PDF object pdf = canvas.Canvas(fileName) # Setting the title of the document pdf.setTitle(documentTitle) # Registering a TrueType font pdfmetrics.registerFont(TTFont('abc', 'Arial.ttf')) # Creating the title by setting its font and placing it on the canvas pdf.setFont('abc', 36) pdf.drawCentredString(300, 770, title) # Creating the subtitle by setting its font, color, and placing it on the canvas pdf.setFillColorRGB(0, 0, 255) # Set color to blue pdf.setFont("Courier-Bold", 24) pdf.drawCentredString(290, 720, subTitle) PYTHON 最後,當畫布上的所有內容都繪製完畢後,我們儲存 PDF 檔案。 # Saving the PDF pdf.save() # Saving the PDF pdf.save() PYTHON 我們也可以使用 Python 中的 Reportlab,透過drawString和drawText方法建立一個簡單的 PDF 檔案。 使用 PDFKit 庫建立 PDF 文件 在 Python 中建立 PDF 檔案時, PDFKit庫是最佳方法之一。 它可以使用HTML程式碼建立PDF檔案。 您可以將簡單且複雜的 HTML 檔案或 URL 中的 HTML 渲染成像素級完美的可列印 PDF 頁面。 但是,PDFKit 整合了wkhtmltopdf功能,可以將 HTML 轉換為 PDF。 若要為 Windows、Linux 和 Mac 安裝wkhtmltopdf ,請造訪此連結。 注意:在 Windows 作業系統中, wkhtmltopdf將安裝在程式檔案中。 安裝 使用以下命令安裝 PDFKit: pip install pdfkit pip install pdfkit SHELL 從 URL 建立 PDF 文件 使用 PDFKit 建立 PDF 檔案非常簡單,只需一行程式碼即可完成。 import pdfkit # Convert a webpage from a URL to a PDF file pdfkit.from_url('http://google.com', 'out.pdf') import pdfkit # Convert a webpage from a URL to a PDF file pdfkit.from_url('http://google.com', 'out.pdf') PYTHON 從 HTML 文件建立 PDF 文件 import pdfkit # Convert an HTML file to a PDF file pdfkit.from_file('index.html', 'out.pdf') import pdfkit # Convert an HTML file to a PDF file pdfkit.from_file('index.html', 'out.pdf') PYTHON 從HTML範本建立PDF文件 您可以將 HTML 範本作為字串傳遞,以將其轉換為 PDF 輸出檔案。 import pdfkit # HTML content to convert to PDF html_string = """ <html> <head> <meta name="pdfkit-page-size" content="Legal"/> <meta name="pdfkit-orientation" content="Landscape"/> </head> <body>Hello World!</body> </html> """ # Convert HTML string to a PDF file pdfkit.from_string(html_string, 'out.pdf') import pdfkit # HTML content to convert to PDF html_string = """ <html> <head> <meta name="pdfkit-page-size" content="Legal"/> <meta name="pdfkit-orientation" content="Landscape"/> </head> <body>Hello World!</body> </html> """ # Convert HTML string to a PDF file pdfkit.from_string(html_string, 'out.pdf') PYTHON PDFKit 可讓您使用 HTML 範本輕鬆地在 Python 中建立 PDF。 IronPDF 圖書館。 IronPDF是一個用於在 .NET 專案中建立 PDF 檔案的實用工具。 該庫的一個常見用途是"HTML 到 PDF"渲染,其中 HTML 用作渲染 PDF 文件的設計語言。 IronPDF 使用 .NET Chromium 引擎將 HTML 頁面繪製成 PDF 檔案。 使用 HTML 轉 PDF 時,無需使用複雜的 API 來定位或設計 PDF。 IronPDF 也支援所有標準網頁技術:HTML、ASPX、JS、CSS 和圖像。 它還允許您使用 HTML5、CSS、JavaScript 和圖像建立 .NET PDF 庫。 您可以輕鬆編輯 PDF 文件,新增圖章、頁首和頁尾。 此外,它還可以輕鬆讀取 PDF 文字和提取圖像。 若要開始使用 IronPDF,您需要安裝 NuGet 套件(請確保此步驟已通過驗證或在 .NET 開發環境中執行): pip install ironpdf 以下範例可協助您直接從 URL 建立 PDF: from ironpdf import ChromePdfRenderer # Instantiate Renderer renderer = ChromePdfRenderer() # Create a PDF from a URL pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/") # Export to a file pdf.SaveAs("url.pdf") from ironpdf import ChromePdfRenderer # Instantiate Renderer renderer = ChromePdfRenderer() # Create a PDF from a URL pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/") # Export to a file pdf.SaveAs("url.pdf") PYTHON 以下程式碼可以幫助您根據 HTML 程式碼以及任何 CSS 或 JavaScript 程式碼建立 PDF 檔案: from ironpdf import ChromePdfRenderer # Instantiate Renderer renderer = ChromePdfRenderer() # Create a PDF from an HTML string using Python pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>") # Export to a file pdf.SaveAs("output.pdf") # Advanced Example with HTML Assets # Load external HTML assets: Images, CSS, and JavaScript. # An optional BasePath is set as the file location to load assets from myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", base_path=r"C:\site\assets") myAdvancedPdf.SaveAs("html-with-assets.pdf") from ironpdf import ChromePdfRenderer # Instantiate Renderer renderer = ChromePdfRenderer() # Create a PDF from an HTML string using Python pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>") # Export to a file pdf.SaveAs("output.pdf") # Advanced Example with HTML Assets # Load external HTML assets: Images, CSS, and JavaScript. # An optional BasePath is set as the file location to load assets from myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", base_path=r"C:\site\assets") myAdvancedPdf.SaveAs("html-with-assets.pdf") PYTHON 從上面的程式碼可以看出,它非常簡單明了。 從 HTML 程式碼建立 PDF 檔案只需要很少幾行程式碼。 它是一種快速、可靠、省時的解決方案,且結果準確。 下載 IronPDF 並免費試用。 試用期結束後,授權費用從$799開始。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新6月 22, 2025 在 Python 的列表中查找項目 本文探索各種方法,當使用Python查找列表中的任何元素時,將為您提供對可用選項和其應用的全面理解。 閱讀更多 更新6月 22, 2025 Spyder Python IDE:完整指南 在本文中,我們將探索什麼是 Spyder,如何安裝它,以及如何使用其關鍵功能。 閱讀更多 更新7月 28, 2025 用 Pytest 寫 Python 測試 PyTest 是一個强大、灵活且用户友好的测试框架,在 Python 社区中获得了极大的普及 閱讀更多 如何使用 PyCharm(開發者指南)如何在 Python 中讀取 PDF 文件