HTML 轉 PDF
from ironpdf import *

# Instantiate Renderer
renderer = ChromePdfRenderer()
 
# Create a PDF from a HTML string using Python
pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")
 
# Export to a file or Stream
pdf.SaveAs("output.pdf")

# Advanced Example with HTML Assets
# Load external html assets: Images, CSS and JavaScript.
# An optional BasePath 'C:\site\assets\' is set as the file location to load assets from
myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", r"C:\site\assets")
myAdvancedPdf.SaveAs("html-with-assets.pdf")
pip install ironpdf
HTML 轉 PDF

HTML 轉 PDF

此程式碼範例展示了IronPDF for Python的旗艦功能:將HTML轉換為PDF。

Python開發者可以使用RenderHtmlAsPdf方法將原始HTML標記轉換成PDF文件。 IronPDF可以將所有HTML內容忠實地渲染成等效的PDF格式。 這包括上面簡單的"Hello World"範例,也包括由巢狀元素組成的更複雜的HTML結構。

如上所示,RenderHtmlAsPdf方法接受包含要渲染成PDF的HTML標記的字串。 請注意,該方法還能識別HTML字串中包含的圖片、iframe以及其他外部參考資源。 這些元素在生成的PDF中將按標準合規瀏覽器預期的方式渲染。

使用RenderHtmlAsPdf方法的專屬功能如標頭、頁尾、邊距和其他頁面設定來自訂生成的PDF文件。 有關更多資訊,請查看此程式碼範例。

學習如何在Python中將HTML轉換為PDF - 教程
在GitHub上查看

準備開始了嗎?

版本:2026.11剛剛發布