自动将结构化数据转换为精美文档是后端服务的常见需求。 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 代码的情况下执行相同的操作。

  1. 获取访问令牌
   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"
  1. 上传 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"
  1. 上传 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"
  1. 将 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
         }'
  1. 将工作簿转换为 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"
  1. 下载生成的 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‑特定设置,例如页面大小、方向和图像质量。请参阅 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 storage,将 XML 数据映射到工作表中,然后将工作簿保存为 PDF。请参阅 Aspose.Cells Cloud SDK for Node.js 获取详细的 API 参考。

  • 使用导入 XML 数据到 PDF 时,我可以自定义 PDF 输出吗?
    是的,saveWorkbook 方法接受特定格式的选项,例如页面方向、图像质量和压缩级别。按照 API reference 中的描述,在请求负载中调整这些设置。

  • 需要什么身份验证方法来进行 REST 调用?
    所有请求必须包含从 Aspose Cloud 身份验证端点获取的 OAuth 2.0 访问令牌。在调用任何 API 之前,使用您的客户端 ID 和客户端密钥请求令牌。

  • 有没有办法在不影响生产数据的情况下测试该过程?
    您可以使用在临时许可证页面提供的临时许可证,在非生产环境中运行代码。

阅读更多