將豐富的 HTML 頁面轉換為可編輯的 DOCX 檔案是報告和文件自動化工作流程中常見的需求。 GroupDocs.Conversion Cloud SDK for Node.js 使開發人員能夠完全透過基於 REST‑based 的庫執行此轉換。在本教程中,您將了解如何設定 SDK、編寫在 Node.JS 中執行 HTML 到 DOCX 轉換的程式碼、使用 cURL 呼叫 API,並套用配置選項以獲得最佳結果。
先決條件與設定
在開始之前,請確保您具備以下項目:
- 在開發機器上安裝了 Node.js 14 或更高版本。
- 一個有效的 GroupDocs.Conversion Cloud 帳戶(您可以在產品頁面上註冊免費試用)。
- 從 GroupDocs Cloud 儀表板獲取的 Client ID 和 Client Secret。
- 用於調用雲端 REST API 的 Internet 連接。
使用 npm 安裝 SDK:
npm install groupdocs-conversion-cloud
如果您需要探索程式碼,請下載最新套件並在 GitHub 上檢視原始碼:
下載 GroupDocs.Conversion Cloud SDK for Node.js
安裝好 SDK 並準備好憑證後,您可以繼續實作。
HTML 轉換為 DOCX(Node.JS):逐步說明
以下是一個簡潔的操作說明,展示了每個邏輯步驟。完整的原始程式碼稍後提供。
步驟 1:初始化 Conversion API 客戶端
建立 ConversionApi 實例並配置驗證。
const { ConversionApi, Configuration } = require('groupdocs-conversion-cloud');
const config = new Configuration({
clientId: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET'
});
const conversionApi = new ConversionApi(config);
第 2 步:上傳 HTML 原始檔案
上傳您想要轉換的 HTML 檔案。API 會返回一個檔案識別碼,您將使用它進行轉換。
const fs = require('fs');
const path = require('path');
const htmlPath = path.resolve(__dirname, 'sample.html');
const fileBytes = fs.readFileSync(htmlPath);
const uploadResponse = await conversionApi.uploadFile({
file: fileBytes,
fileName: 'sample.html'
});
const sourceFileId = uploadResponse.id;
步驟 3:設定轉換選項
配置任何 DOCX‑特定的選項,例如嵌入字體或設定頁面邊距。此步驟演示 從 HTML 生成 DOCX 的自訂。
const convertSettings = {
outputFormat: 'DOCX',
options: {
embedFonts: true,
pageSize: 'A4',
marginTop: 20,
marginBottom: 20,
marginLeft: 15,
marginRight: 15
}
};
第 4 步:執行轉換
使用上述定義的來源檔案 ID 和設定呼叫 convert 方法。
const convertResponse = await conversionApi.convert({
fileId: sourceFileId,
convertSettings: convertSettings
});
const docxFileId = convertResponse.id;
步驟 5:下載生成的 DOCX
檢索生成的 DOCX 檔案並將其儲存到本機。
const docxData = await conversionApi.downloadFile({ fileId: docxFileId });
fs.writeFileSync(path.resolve(__dirname, 'output.docx'), docxData);
console.log('DOCX file saved as output.docx');
上述步驟說明了使用 GroupDocs.Conversion Cloud SDK 完成 HTML 轉 DOCX 於 Node.JS 的完整工作流程。
完整程式碼範例:從 HTML 內容生成 DOCX
以下程式將所有部分組合成一個可執行的腳本。
// Full working example for HTML to DOCX conversion using GroupDocs.Conversion Cloud SDK for Node.js
const { ConversionApi, Configuration } = require('groupdocs-conversion-cloud');
const fs = require('fs');
const path = require('path');
async function convertHtmlToDocx() {
// 1. Configure the API client
const config = new Configuration({
clientId: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET'
});
const conversionApi = new ConversionApi(config);
// 2. Read the HTML file
const htmlPath = path.resolve(__dirname, 'sample.html');
const htmlBytes = fs.readFileSync(htmlPath);
// 3. Upload the HTML file
const uploadResult = await conversionApi.uploadFile({
file: htmlBytes,
fileName: 'sample.html'
});
const sourceFileId = uploadResult.id;
// 4. Define conversion settings
const convertSettings = {
outputFormat: 'DOCX',
options: {
embedFonts: true,
pageSize: 'A4',
marginTop: 20,
marginBottom: 20,
marginLeft: 15,
marginRight: 15
}
};
// 5. Perform the conversion
const convertResult = await conversionApi.convert({
fileId: sourceFileId,
convertSettings: convertSettings
});
const docxFileId = convertResult.id;
// 6. Download the DOCX file
const docxBytes = await conversionApi.downloadFile({ fileId: docxFileId });
const outputPath = path.resolve(__dirname, 'output.docx');
fs.writeFileSync(outputPath, docxBytes);
console.log(`Conversion successful. DOCX saved to ${outputPath}`);
}
// Execute the conversion
convertHtmlToDocx().catch(err => {
console.error('Conversion failed:', err);
});
注意: 此程式碼範例展示了核心功能。在您的專案中使用之前,請確保更新檔案路徑(
sample.html、output.docx),驗證所有必要的相依項目已正確安裝,並在開發環境中徹底測試。如遇任何問題,請參閱官方文件或聯繫支援團隊尋求協助。
通過 cURL 和 REST API 執行轉換
如果您更喜歡直接使用 HTTP,以下 cURL 命令可執行相同的轉換。
- 取得存取令牌
將 YOUR_CLIENT_ID 和 YOUR_CLIENT_SECRET 替換為您的憑證。
curl -X POST "https://api.groupdocs.cloud/v2.0/oauth2/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET"
回應包含 access_token。
- 上傳 HTML 檔案
curl -X POST "https://api.groupdocs.cloud/v2.0/storage/files/sample.html" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-F "file=@sample.html"
- 開始轉換
curl -X POST "https://api.groupdocs.cloud/v2.0/conversion/convert" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"sourceFilePath": "sample.html",
"outputFilePath": "output.docx",
"outputFormat": "DOCX",
"options": {
"embedFonts": true,
"pageSize": "A4"
}
}'
- 下載已轉換的 DOCX
curl -X GET "https://api.groupdocs.cloud/v2.0/storage/files/output.docx" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-o output.docx
如需完整的參數列表,請參閱官方 API 文檔。
配置 HTML 內容轉換為 DOCX 的選項
SDK 提供了多個屬性,讓您可以微調輸出:
- embedFonts - 將所有引用的字體嵌入 DOCX,確保視覺保真度。
- pageSize - 設定頁面大小(
A4、Letter等)。 - marginTop / marginBottom / marginLeft / marginRight - 調整頁面邊距(以點為單位)。
套用這些選項的範例:
const convertSettings = {
outputFormat: 'DOCX',
options: {
embedFonts: true,
pageSize: 'Letter',
marginTop: 30,
marginBottom: 30,
marginLeft: 20,
marginRight: 20
}
};
請參閱 ConversionOptions class 以獲取完整列表。
HTML 內容轉換為 DOCX 的效能考量
在轉換大型或複雜的 HTML 文件時,請記住以下提示:
- 重用 API 客戶端 - 為每個文件創建新的
ConversionApi實例會增加開銷。 - 流式處理大型 HTML 文件 - 不要將整個文件載入記憶體,使用流 (
fs.createReadStream) 並使用 SDK 的uploadFileStream方法。 - 限制嵌入資源 - 在上傳前從 HTML 中移除不必要的圖片或腳本,以減少處理時間。
- 批量轉換 - 在迴圈中順序處理文件,但要遵守 API 速率限制,以避免被限流。
遵循這些做法有助於保持低延遲和適度的記憶體消耗。
結論
HTML 到 DOCX 的轉換在 Node.JS 中變得簡單,只需使用 GroupDocs.Conversion Cloud SDK for Node.js。按照上述步驟,您可以將可靠的 HTML 轉 DOCX 生成功能整合到任何伺服器端應用程式中,客製化輸出,並針對大型工作負載優化效能。請記得為生產環境取得適當的授權;您可以購買訂閱或從臨時授權頁面取得臨時授權。祝開發愉快!
常見問題
如何在 Node.JS 中開始 HTML 到 DOCX 的轉換?
使用 SDK 建立 ConversionApi 用戶端,上傳您的 HTML 檔案,設定所需的轉換選項,並呼叫 convert 方法。此過程是完全非同步的,並返回用於下載的 DOCX 檔案識別碼。
從 HTML 生成 DOCX 時可以調整哪些選項?
ConversionOptions 物件允許您嵌入字型、選擇頁面大小、設定邊距,並控制圖像處理。請參閱 API 參考 以了解所有可用設定。
我可以轉換包含外部 CSS 或圖像的 HTML 嗎?
是的。在開始轉換之前,請將所有引用的資源(CSS、圖像)上傳到同一個存儲文件夾,SDK 將在處理過程中解析這些鏈接。
我在生產部署時需要許可證嗎?
生產環境需要有效的授權。您可以從臨時授權頁面獲取測試用的臨時授權,並在準備上線時購買完整訂閱。
