將 DOCX 文件轉換為 HTML 是在構建基於 Web 的報告或內容管理解決方案時的常見需求。 GroupDocs.Conversion Cloud SDK for Python 使開發人員能夠僅通過少量 API 調用在 Python 中自動執行 DOCX 到 HTML 的轉換。在本教程中,您將設置 SDK,逐步實現,查看完整的代碼示例,並學習如何為響應式網頁微調輸出。
Python 中 DOCX 轉換為 HTML 的需求
開發人員在構建以文件為驅動的 Web 應用程式時,通常會從使用者那裡收到 DOCX 檔案,並需要在瀏覽器中即時顯示其內容。典型的需求包括:
- 保持原始樣式、表格和圖像,同時渲染為 HTML。
- 產生可適應不同螢幕尺寸的標記,而無需額外的 CSS 工作。
- 在伺服器端環境中執行轉換,無需安裝大型辦公套件。
使用桌面工具或開源庫進行手動轉換可能容易出錯,尤其是對於複雜的佈局,且無法滿足高容量 API 驅動工作負載的規模需求。
方法:自動將 DOCX 轉換為 HTML
GroupDocs.Conversion Cloud SDK for Python 提供一個基於雲端的 API,負責處理格式轉換的繁重工作。符合需求的主要功能包括:
- 保留樣式 - 引擎保持字體、顏色和段落格式完整。
- 響應式 HTML 輸出 - 內建選項產生適合行動裝置的流式佈局。
- 可擴展的 REST 介面 - 您可以從任何 Python 應用程式呼叫服務,而無需管理本地轉換二進位檔。
有關詳細的 API 使用說明,請參閱官方文件和API 參考。
建構解決方案:在 Python 中將 DOCX 轉換為 HTML
安裝 SDK 並匯入所需類別
pip install groupdocs-conversion-cloud
from groupdocs_conversion_cloud import (
ConvertApi, ConvertSettings, HtmlOptions,
StorageApi, FileInfo, Configuration, ApiClient
)
使用憑證配置 API 客戶端
config = Configuration()
config.client_id = "YOUR_CLIENT_ID"
config.client_secret = "YOUR_CLIENT_SECRET"
api_client = ApiClient(configuration=config)
convert_api = ConvertApi(api_client)
storage_api = StorageApi(api_client)
上傳 DOCX 原始檔案
# Assume 'sample.docx' is in the local folder
with open("sample.docx", "rb") as file:
storage_api.upload_file(path="input/sample.docx", file=file)
將 DOCX 轉換為響應式 HTML
file_info = FileInfo()
file_info.file_path = "input/sample.docx"
html_options = HtmlOptions()
html_options.responsive = True # Enable responsive layout
html_options.embed_fonts = True # Embed custom fonts if any
convert_settings = ConvertSettings()
convert_settings.file_info = file_info
convert_settings.format = "html"
convert_settings.options = html_options
result = convert_api.convert_document(convert_settings)
# The result contains the URL of the generated HTML file
print("HTML file URL:", result.path)
下載生成的 HTML 檔案
output_path = "output/sample.html"
with open(output_path, "wb") as out_file:
storage_api.download_file(path=result.path, out_file=out_file)
print("HTML saved to:", output_path)
完整程式碼範例:DOCX 轉換為 HTML 並具備回應式輸出
以下腳本將所有步驟整合成一個可執行的程式。
from groupdocs_conversion_cloud import (
ConvertApi, ConvertSettings, HtmlOptions,
StorageApi, FileInfo, Configuration, ApiClient
)
def main():
# 1. Configure the client
config = Configuration()
config.client_id = "YOUR_CLIENT_ID"
config.client_secret = "YOUR_CLIENT_SECRET"
api_client = ApiClient(configuration=config)
convert_api = ConvertApi(api_client)
storage_api = StorageApi(api_client)
# 2. Upload DOCX file
local_file = "sample.docx"
remote_path = "input/sample.docx"
with open(local_file, "rb") as f:
storage_api.upload_file(path=remote_path, file=f)
# 3. Prepare conversion settings
file_info = FileInfo()
file_info.file_path = remote_path
html_options = HtmlOptions()
html_options.responsive = True
html_options.embed_fonts = True
settings = ConvertSettings()
settings.file_info = file_info
settings.format = "html"
settings.options = html_options
# 4. Execute conversion
result = convert_api.convert_document(settings)
print("Conversion completed. HTML URL:", result.path)
# 5. Download the HTML result
output_file = "sample_converted.html"
with open(output_file, "wb") as out:
storage_api.download_file(path=result.path, out_file=out)
print("HTML saved to:", output_file)
if __name__ == "__main__":
main()
注意: 此代碼示例演示了核心功能。在將其用於您的項目之前,請確保更新文件路徑(
sample.docx、sample_converted.html),驗證所有必需的依賴項已正確安裝,並在開發環境中徹底測試。如果遇到任何問題,請參閱官方文檔或聯繫支援團隊尋求協助。
使用 cURL 與 REST API 自動化 DOCX 到 HTML 的轉換
您可以透過對 REST 端點使用 cURL 命令,而無需編寫 Python 程式碼,即完成相同的轉換。
1. 取得存取令牌
curl -X POST "https://api.groupdocs.cloud/v2.0/oauth2/token" \
-H "Content-Type: application/json" \
-d '{"client_id":"YOUR_CLIENT_ID","client_secret":"YOUR_CLIENT_SECRET"}'
回應中包含 access_token,您將在後續呼叫中使用它。
2. 上傳 DOCX 檔案
curl -X PUT "https://api.groupdocs.cloud/v2.0/storage/file/input/sample.docx" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/octet-stream" \
--data-binary "@sample.docx"
3. 請求 DOCX 轉換為響應式 HTML
curl -X POST "https://api.groupdocs.cloud/v2.0/conversion/convert" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"fileInfo": { "filePath": "input/sample.docx" },
"format": "html",
"options": { "responsive": true, "embedFonts": true }
}'
回應返回一個 JSON 物件,內含產生的 HTML 檔案的 path。
4. 下載 HTML 結果
curl -X GET "https://api.groupdocs.cloud/v2.0/storage/file/output/sample.html" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-o sample_converted.html
欲取得完整的參數清單,請參閱 API 參考。
微調 DOCX 到響應式 HTML 轉換設定
SDK 提供了多種選項,讓您可以控制生成的 HTML 的品質和大小。
- Responsive flag -
html_options.responsive = True新增一個對視口友好的 CSS 包裝器。 - Embed fonts -
html_options.embed_fonts = True確保自訂字型以 base64 資料形式嵌入。 - Preserve images -
html_options.extract_images = False將圖像保留為內嵌,而不是建立獨立檔案。 - Custom CSS - 您可以透過
html_options.css提供 CSS 字串,以套用全站樣式。
設定自訂 CSS 字串的範例:
custom_css = "body {font-family: Arial, sans-serif; line-height: 1.6;}"
html_options.css = custom_css
根據您的 Web 前端需求調整這些設定。
結論
GroupDocs.Conversion Cloud SDK for Python 使在 Python 中將 DOCX 轉換為 HTML 變得簡單、可靠且可擴展。按照上述步驟,您可以將自動化轉換整合到任何後端服務中,生成響應式標記,並對樣式和資產保持完整控制。請記得為生產環境獲取適當的許可證;產品頁面上提供了價格詳細資訊,您也可以獲取臨時許可證頁面以進行評估。擁有此 SDK 後,從 DOCX 源提供豐富的 HTML 預覽將成為您應用工作流程的常規部分。
常見問題
如何在 Python 中使用 GroupDocs 執行 DOCX 轉 HTML 轉換?
使用 GroupDocs.Conversion Cloud SDK for Python 的 Convert API,為響應式輸出配置HtmlOptions,然後調用convert_document。SDK 會返回生成的 HTML 文件的 URL。是否可以使 HTML 輸出具備行動裝置友好性?
是的,將html_options.responsive = True設定為 True。SDK 會注入 CSS,自動根據不同螢幕寬度調整佈局。SDK 需要什麼驗證機制?
SDK 使用 OAuth 客戶端憑證流程。在建立 API 實例之前,請在Configuration物件中提供您的client_id和client_secret。DOCX 檔案有大小限制嗎?
雲端服務接受的檔案上限為 100 MB 以供轉換。較大的文件應在上傳前分割或分批處理。
