如何在 Python 中創建 PDF 文件
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 reportlabpip install reportlab注意:安裝 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()程式碼解釋
導入所有模組和套件之後,我們首先初始化了所有將要寫入 PDF 文件的內容。
fileName = 'sample.pdf'
documentTitle = 'sample'
title = 'Create PDF'
subTitle = 'Using ReportLab !!'fileName = 'sample.pdf'
documentTitle = 'sample'
title = 'Create PDF'
subTitle = 'Using ReportLab !!'現在,我們建立 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)最後,當畫布上的所有內容都繪製完畢後,我們儲存 PDF 檔案。
# Saving the PDF
pdf.save()# Saving the PDF
pdf.save()我們也可以使用 drawString 和 drawText 方法,利用 Python 中的 Reportlab 建立一個簡單的 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 pdfkitpip install pdfkit從 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')從 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')從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')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")以下程式碼可以幫助您根據 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")從上面的程式碼可以看出,它非常簡單明了。 從 HTML 程式碼建立 PDF 檔案只需要很少幾行程式碼。 它是一種快速、可靠、省時的解決方案,且結果準確。
下載IronPDF並免費試用。 試用期結束後,許可證從 $799 開始。










