跳過到頁腳內容
PYTHON PDF 工具

如何在 Python 中創建 PDF 文件

PDF(可攜式文件格式)是在線傳送和接收數據的最流行的數字文件格式。它主要用於保護數據格式及使用加密密碼來保護數據。 .pdf 擴展名與軟體應用、硬體或操作系統無關。

在這篇文章中,我們將在 Python 程式語言中創建 PDF 文件。 有很多線上選擇可用,然而我們將使用 Python 庫來創建 PDF 文件。 以下是用 Python 生成單頁或多頁 PDF 文件的兩個著名庫:

  1. Reportlab
  2. 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 時,必須將其添加到路徑環境變量,以便可以在命令提示符或 PowerShell 的任何地方執行上述命令。 建議對 Python 3+ 使用 pip,因為它是更新的版本。

打開一個新的 Python 文件

要使用 Reportlab 庫,我們需要在 Python 文件中編寫代碼並執行以創建 PDF 文件。

  1. 從 Windows 搜索欄中搜索並打開 Python 默認 IDLE shell,按 Ctrl + N 或從文件標籤選擇“新文件”。 這將打開編寫代碼的文本編輯器。
  2. 然後以適當的名稱保存文件。 我將其命名為 "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

我們還可以使用 drawStringdrawText 方法使用 Reportlab 在 Python 中創建一個簡單的 PDF 文件。

使用 PDFKit 庫創建 PDF 文件

PDFKit 庫是用於在 Python 中創建 PDF 文件的最佳方法之一。 它可以使用 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 is a useful tool to 創建 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 機器人,結合科技與創意的樂趣。