自動化將結構化資料轉換為精美文件是後端服務的常見需求。 Aspose.Cells Cloud SDK for Node.js 讓開發人員能夠操作 Excel 活頁簿,並透過功能強大的 REST API 將其轉換為各種格式。在本指南中,您將學習如何使用 SDK 將 XML 資料匯入 PDF,涵蓋從驗證、檔案上傳、XML 映射到 PDF 生成的全部過程。
先決條件與設定
開始之前,請確保您具備以下條件:
- 在您的機器上安裝了 Node.js 14 或更高版本。
- 具有客戶端 ID 和客戶端密鑰的 Aspose Cloud 帳戶。
- 能夠執行 Node.js 腳本的終端機或 IDE 存取權。
安裝 Aspose.Cells Cloud SDK for Node.js:
npm install asposecellscloud
接下來,設定您的驗證憑證。以下程式碼片段直接取自參考實作:
const clientId = 'YOUR_CLIENT_ID';
const clientSecret = 'YOUR_CLIENT_SECRET';
const config = new Configuration(clientId, clientSecret);
const apiClient = new ApiClient(config);
const cellsApi = new CellsApi(apiClient);
您還需要從官方發行頁面下載 SDK 套件: Aspose.Cells Cloud SDK for Node.js Download。在滿足先決條件後,我們可以進入實際實作。
在 Node.js 中將 XML 資料匯入 PDF:逐步說明
步驟 1:載入必要的模組並建立 API 用戶端
首先,匯入必要的模組並實例化 API 用戶端。
const fs = require('fs');
const path = require('path');
const { CellsApi, Configuration, ApiClient } = require('asposecellscloud');
const clientId = 'YOUR_CLIENT_ID';
const clientSecret = 'YOUR_CLIENT_SECRET';
const config = new Configuration(clientId, clientSecret);
const apiClient = new ApiClient(config);
const cellsApi = new CellsApi(apiClient);
步驟 2:定義檔案上傳的輔助函式
建立一個可重複使用的函式,用於將本機檔案上傳至 Aspose Cloud 儲存空間。
async function uploadFile(localFilePath, remoteFileName) {
const fileContent = fs.readFileSync(localFilePath);
await cellsApi.uploadFile(`${remoteFolder}/${remoteFileName}`, fileContent);
}
步驟 3:上傳工作簿和 XML 檔案
將 Excel 範本和 XML 資料檔案上傳至雲端儲存中的 Temp 資料夾。
await uploadFile(path.join(localFolder, workbookName), workbookName);
await uploadFile(path.join(localFolder, xmlDataName), xmlDataName);
第 4 步:將 XML 資料匯入工作表
將 XML 檔案對映到目標工作表。這是 匯入 XML 資料至 PDF 工作流程的核心。
const importXmlRequest = {
xmlFile: `${remoteFolder}/${xmlDataName}`,
xmlMapIndex: 0,
importDataOnly: true,
importDataOnlySpecified: true
};
await cellsApi.importXML(workbookName, 'Sheet1', importXmlRequest, remoteFolder);
步驟 5:將更新的工作簿轉換為 PDF 並下載
最後,將工作簿另存為 PDF 並取得該檔案。
const remotePdfPath = `${remoteFolder}/${outputPdfName}`;
await cellsApi.saveWorkbook(workbookName, 'pdf', remotePdfPath, remoteFolder);
const downloadResponse = await cellsApi.downloadFile(remotePdfPath);
fs.writeFileSync(path.join(localFolder, outputPdfName), downloadResponse.body);
完成這些步驟後,XML 資料已成功匯入,產生的 PDF 已可使用。
完整程式碼範例:將 XML 資料匯入 PDF 並附帶詳細註解
以下程式碼示範完整的端對端流程。
const fs = require('fs');
const path = require('path');
const { CellsApi, Configuration, ApiClient } = require('asposecellscloud');
// ---- Configuration ---------------------------------------------------------
const clientId = 'YOUR_CLIENT_ID';
const clientSecret = 'YOUR_CLIENT_SECRET';
const config = new Configuration(clientId, clientSecret);
const apiClient = new ApiClient(config);
const cellsApi = new CellsApi(apiClient);
// ---- File definitions -------------------------------------------------------
const localFolder = __dirname;
const remoteFolder = 'Temp'; // folder in Aspose Cloud storage
const workbookName = 'template.xlsx'; // existing workbook template
const xmlDataName = 'data.xml'; // XML file containing data
const outputPdfName = 'result.pdf'; // final PDF name
// ---- Helper functions -------------------------------------------------------
async function uploadFile(localFilePath, remoteFileName) {
const fileContent = fs.readFileSync(localFilePath);
await cellsApi.uploadFile(`${remoteFolder}/${remoteFileName}`, fileContent);
}
async function importXml() {
const importXmlRequest = {
xmlFile: `${remoteFolder}/${xmlDataName}`,
xmlMapIndex: 0,
importDataOnly: true,
importDataOnlySpecified: true
};
await cellsApi.importXML(workbookName, 'Sheet1', importXmlRequest, remoteFolder);
}
async function convertToPdf() {
const remotePdfPath = `${remoteFolder}/${outputPdfName}`;
await cellsApi.saveWorkbook(workbookName, 'pdf', remotePdfPath, remoteFolder);
const downloadResponse = await cellsApi.downloadFile(remotePdfPath);
fs.writeFileSync(path.join(localFolder, outputPdfName), downloadResponse.body);
}
// ---- Main execution ---------------------------------------------------------
(async () => {
try {
// Upload required files to Aspose Cloud storage
await uploadFile(path.join(localFolder, workbookName), workbookName);
await uploadFile(path.join(localFolder, xmlDataName), xmlDataName);
// Import XML data into the workbook
await importXml();
// Convert the updated workbook to PDF and download locally
await convertToPdf();
console.log('XML data imported and PDF generated successfully.');
} catch (err) {
console.error('Error:', err.response ? err.response.text : err.message);
}
})();
注意: 此程式碼範例示範了核心功能。在將其用於您的專案之前,請確保更新任何檔案路徑和設定值以符合實際環境,驗證所有必要的相依項目已正確安裝,並在開發環境中徹底測試。如果遇到任何問題,請參閱官方文件或聯繫支援團隊尋求協助。
使用 cURL 與 REST API 進行 XML 轉 PDF
以下是一個基於 cURL 的工作流程,可在不編寫任何 Node.js 代碼的情況下執行相同的操作。
- 取得存取權杖
curl -X POST "https://api.aspose.cloud/connect/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET"
- 上傳 Excel 範本
curl -X PUT "https://api.aspose.cloud/v3.0/cells/storage/file/Temp/template.xlsx" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/octet-stream" \
--data-binary "@template.xlsx"
- 上傳 XML 資料檔案
curl -X PUT "https://api.aspose.cloud/v3.0/cells/storage/file/Temp/data.xml" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/octet-stream" \
--data-binary "@data.xml"
- 將 XML 匯入工作表
curl -X POST "https://api.aspose.cloud/v3.0/cells/template.xlsx/worksheets/Sheet1/importxml" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"xmlFile": "Temp/data.xml",
"xmlMapIndex": 0,
"importDataOnly": true,
"importDataOnlySpecified": true
}'
- 將工作簿轉換為 PDF
curl -X POST "https://api.aspose.cloud/v3.0/cells/template.xlsx/save?format=pdf&outPath=Temp/result.pdf" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"
- 下載生成的 PDF
curl -X GET "https://api.aspose.cloud/v3.0/cells/storage/file/Temp/result.pdf" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-o result.pdf
如需完整的參數清單和其他選項,請參閱 API 參考。
微調 XML 轉 PDF 選項
匯入操作提供了多個旗標,讓您可以控制 XML 資料的合併方式:
- importDataOnly - 設為
true時,僅匯入資料列,保持現有格式不變。 - importDataOnlySpecified - 必須與
importDataOnly同時設為true才能啟用此選項。 - xmlMapIndex - 選擇在有多個 XML 映射時應使用哪一個進行匯入。
這些選項已在先前使用的 importXmlRequest 物件中示範過了:
const importXmlRequest = {
xmlFile: `${remoteFolder}/${xmlDataName}`,
xmlMapIndex: 0,
importDataOnly: true,
importDataOnlySpecified: true
};
您也可以透過將 PdfSaveOptions 物件傳遞給 saveWorkbook 方法,調整 PDF‑specific 設定,例如頁面大小、方向和影像品質。請參考 API 參考 以取得完整的可用選項清單。
結論
透過本教學,您現在已擁有使用 Aspose.Cells Cloud SDK for Node.js 進行 將 XML 資料匯入 PDF 的完整解決方案。此方法結合了簡單的 SDK 呼叫與可選的 cURL 指令,讓您無論偏好完整的 Node.js 全端實作或輕量的 REST 整合,都能保持彈性。請務必保護您的客戶端憑證,並考慮在生產環境中使用臨時或付費授權。您可以從臨時授權頁面取得臨時授權,並在產品頁面上查看定價選項。祝開發愉快!
常見問題
-
如何使用 Aspose.Cells Cloud SDK for Node.js 將 XML 資料匯入 PDF?
SDK 會將您的 Excel 範本和 XML 檔案上傳至 Aspose Cloud 儲存空間,將 XML 資料映射到工作表,然後將活頁簿另存為 PDF。請參閱 Aspose.Cells Cloud SDK for Node.js 以獲取詳細的 API 參考。 -
使用匯入 XML 資料至 PDF 時,我可以自訂 PDF 輸出嗎?
是的,saveWorkbook方法接受特定格式的選項,例如頁面方向、影像品質和壓縮等級。請依照 API 參考 中的說明,在請求負載中調整這些設定。 -
需要什麼驗證方法來呼叫 REST?
所有請求必須包含從 Aspose Cloud 驗證端點取得的 OAuth 2.0 存取權杖。請在呼叫任何 API 之前,使用您的 client ID 和 client secret 來請求權杖。 -
是否有辦法在不影響生產資料的情況下測試此流程?
您可以使用在臨時授權頁面提供的臨時授權,在非生產環境中執行程式碼。