概述

实时生成发票是计费系统、电子商务平台和 SaaS 应用的常见需求。
使用 GroupDocs.Assembly Cloud,您可以完全在云端创建专业发票,无需在服务器上安装任何办公软件。

关键优势

  • 模板灵活性 – 在 Microsoft Word、LibreOffice Writer 等本地编辑器中设计发票布局。
  • 动态数据绑定 – 使用 JSON 或 XML 数据填充模板,支持简单占位符或高级 LINQ 表达式,以实现计算、循环和条件段落。
  • 多种输出格式 – 将最终发票生成 DOCX(可进一步编辑)或 PDF(只读分发)格式。
  • 安全存储 – 通过身份验证令牌访问存储在 GroupDocs Cloud 中的模板和文档。
  • 轻量化运行环境 – 所有处理均在 GroupDocs Cloud 上完成,省去您在基础设施上部署第三方库或高 CPU、内存的需求。

在接下来的章节中,我们将逐步演示整个流程——从准备模板和数据源到使用 .NET SDK(C#)和纯 cURL 命令生成发票。


准备发票模板

使用您喜欢的桌面编辑器(Microsoft Word、LibreOffice Writer 等)设计发票布局。
插入与以后提供的 JSON 字段匹配的 占位符标签,例如:

模板JSON 路径
<<[Invoice.Number]>>invoice.number
<<[Customer.Name]>>customer.name

表格渲染模板定义如下所示:

描述数量单价金额
<<foreach [in Items]>>
<<[Description]>>

<<[Quantity]>>

$<<[UnitPrice]:"N2">>
$<<[Quantity*UnitPrice]:"N2">>
<</foreach>>

为方便起见,您可以下载下面显示的 模板示例

invoice template example

或者自行构建模板并上传至 GroupDocs Cloud 存储(下一节)。


将模板上传至云存储

C# 代码的主要步骤

  1. 创建包含 App SIDApp KeyConfiguration 对象。
  2. 初始化 AssemblyApi 客户端。
  3. 将本地模板文件上传至云存储的指定路径(例如 templates/invoice-template.docx)。
// 1️⃣ Initialize the Cloud API configuration
var config = new Configuration
{
    AppSid = "YOUR_APP_SID",      // replace with your App SID
    AppKey = "YOUR_APP_KEY"       // replace with your App Key
};
var assemblyApi = new AssemblyApi(config);

// 2️⃣ Define the cloud path where the template will be stored
string cloudTemplatePath = "templates/invoice-template.docx";

// 3️⃣ Open the local template file (prepare this file beforehand)
using (var templateStream = File.OpenRead("resources/invoice-template.docx"))
{
    // 4️⃣ Build the upload request – the API expects a stream + target path
    var uploadRequest = new UploadFileRequest(templateStream, cloudTemplatePath);

    // 5️⃣ Execute the upload; the template is now available in Cloud storage
    assemblyApi.UploadFile(uploadRequest);
}

提示: 如果您更喜欢命令行方式,也可以使用简单的 cURL 命令上传文件(见 使用 cURL 生成发票 部分)。


创建数据源

构建包含发票数据的 JSON

以下示例 JSON 与模板中使用的占位符相匹配。
将其保存为 resources 文件夹中的 invoice-data.json,或直接嵌入代码中。

{
  "invoice": {
    "number": "INV-2024-001",
    "issueDate": "2024-01-15T00:00:00"
  },
  "customer": {
    "name": "John Smith",
    "company": "Acme Corporation",
    "email": "john.smith@example.com",
    "address": "123 Main Street",
    "city": "New York",
    "state": "NY",
    "zipCode": "10001",
    "country": "USA"
  },
  "items": [
    {
      "description": "Web Development Services",
      "quantity": 40,
      "unitPrice": 150.00
    },
    {
      "description": "UI/UX Design",
      "quantity": 20,
      "unitPrice": 120.00
    },
    {
      "description": "Consulting Services",
      "quantity": 10,
      "unitPrice": 200.00
    }
  ],
  "taxRate": 10.0
}

在代码中使用 JSON 文件

// Load the JSON data from a file – this string will be passed to the API
string jsonData = File.ReadAllText("resources/invoice-data.json");

注意: 同样的 JSON 也可以在使用 cURL 时直接放在请求体中;文件方式对较大数据集更为方便。


使用 .NET SDK 生成发票

C# 代码的主要步骤

  1. 上传 模板(已在前述步骤中完成)。
  2. 读取 JSON 数据源。
  3. 配置 AssembleOptions – 指定输出格式(docxpdf)并关联模板。
  4. 调用 AssembleDocument 生成发票。
  5. 保存 生成的文件到本地或其他云位置。
using GroupDocs.Assembly.Cloud.Sdk;
using GroupDocs.Assembly.Cloud.Sdk.Model;
using GroupDocs.Assembly.Cloud.Sdk.Model.Requests;
using System.IO;

// 1️⃣ Initialize the Assembly API (same config as upload step)
var config = new Configuration { AppSid = "YOUR_APP_SID", AppKey = "YOUR_APP_KEY" };
var assemblyApi = new AssemblyApi(config);

// 2️⃣ Load JSON data (see previous section)
string jsonData = File.ReadAllText("resources/invoice-data.json");

// 3️⃣ Prepare assembly options
var assembleOptions = new AssembleOptions
{
    // Choose the format you need – "docx" for editable, "pdf" for final PDF
    SaveFormat = "pdf",

    // Pass the whole JSON string – the API parses it automatically
    ReportData = jsonData,

    // Reference the template that we uploaded earlier
    TemplateFileInfo = new TemplateFileInfo
    {
        FilePath = "templates/invoice-template.docx"   // cloud path
    }
};

// 4️⃣ Build the request object
var assembleRequest = new AssembleDocumentRequest(assembleOptions);

// 5️⃣ Execute the request – the response contains the generated file stream
var assembledDocument = assemblyApi.AssembleDocument(assembleRequest);

// 6️⃣ Persist the result locally
using (var outputStream = File.Create("output/invoice-output.pdf"))
{
    // Copy the API stream to a file on disk
    assembledDocument.CopyTo(outputStream);
}

结果: invoice-output.pdf(如果将 SaveFormat 改为 docx 则为 .docx)包含完整填充的发票,可直接发送给客户。


使用 cURL 生成发票

如果您不想安装任何 SDK,只需使用普通的 HTTP 调用即可完成全部操作。

1️⃣ 获取访问令牌

curl.exe -X POST "https://api.groupdocs.cloud/connect/token" \
  -d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET" \
  -H "Content-Type: application/x-www-form-urlencoded"

响应中会返回 access_token,请将其复制用于后续步骤。

2️⃣ 通过 cURL 上传模板

curl.exe -X PUT "https://api.groupdocs.cloud/v1.0/assembly/storage/file/templates/invoice-template.docx" \
  -H "Authorization: Bearer ACCESS_TOKEN" \
  -F "File=@resources/invoice-template.docx"

如果模板已经在云端(如通过 SDK 上传),可以跳过此调用。

3️⃣ 组装发票

resources 文件夹中创建 invoice-data.json(内容同上),然后调用 AssembleDocument 接口:

REPORT_DATA_ESCAPED=$(python -c "import json,sys; print(json.dumps(open('resources/invoice-data.json','r',encoding='utf-8').read()))")
	  
curl.exe -v "https://api.groupdocs.cloud/v1.0/assembly/assemble" \
  -X POST \
  -H "Authorization: Bearer ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  --data-binary @- <<EOF
{
  "TemplateFileInfo": {
    "FilePath": "/templates/invoice-template.docx"
  },
  "SaveFormat": "pdf",
  "OutputPath": "/output/invoice-generated.pdf",
  "ReportData": $REPORT_DATA_ESCAPED
}
EOF

该命令会生成发票并将其存储在 GroupDocs Cloud 存储的 /output/invoice-generated.pdf 中。

4️⃣ 下载生成的发票

curl.exe \
  "https://api.groupdocs.cloud/v1.0/assembly/storage/file/Output/invoice-generated.pdf" \
  -H "Authorization: Bearer ACCESS_TOKEN" \
  -H "Accept: application/octet-stream" \
  -o invoice-generated.pdf

结果: 您现在拥有一份无需编写任何 C# 代码即可发送的发票。


结论

本文展示了 GroupDocs.Assembly Cloud 如何让发票生成变得轻而易举:

  • 轻量化云端处理 – 服务器上无需部署任何重量级工具。
  • 模板设计自由度 – 在 Word/LibreOffice 中创建模板文档并存储到云存储。
  • 动态数据绑定 – 直接提供 JSON(或 XML),支持 LINQ、计算、循环和条件语句。
  • 多种输出格式 – 可选 DOCX 进行后续编辑,或 PDF 用于不可更改的分发。
  • 简易集成 – 使用 .NET SDK 或多条 cURL 调用,示例代码完整展示。

立即通过上传模板并调用 Assemble 接口,开始自动化您的计费工作流!


另请参阅


常见问题 (FAQs)

  • 我可以使用 LibreOffice Writer 而不是 Microsoft Word 来制作模板吗?
    可以。API 支持任何 DOCX 文件,无论使用何种编辑器创建。

  • 是否可以在模板内部进行计算(例如总计、税金)?
    完全可以。您可以在占位符中使用 LINQ 表达式或简单算术,例如 <<[item.quantity * item.unitPrice]>>

  • 我可以上传的模板或数据文件的最大尺寸是多少?
    服务支持最高 500 MB 的文件;典型的发票模板远低于此限制。

  • 在上传前我需要预先创建云存储中的目标文件夹吗?
    不需要。上传接口会自动创建不存在的文件夹层级。

  • 我可以获得免费试用吗?
    是的,每月提供 150 次免费 API 调用。