#document #xlsx #docx #pdf #automation #api-bindings

carbone-sdk-rust

使用Carbone,通过模板和JSON数据集生成文档。创建发票、报告、证书、合同、财务报表、Word文件、Excel表格、CSV、PowerPoint幻灯片等文档。模板可以是DOCX、PPTX、XLSX、CSV、XML、HTML等多种格式。

2个版本 (1个稳定版)

1.0.0 2024年8月9日
0.1.0 2023年10月1日

#68 in 模板引擎

Download history 103/week @ 2024-08-05 10/week @ 2024-08-12

每月113次下载

Apache-2.0

215KB
642

License Rust unstable

Carbone-sdk-rust

使用Carbone Rust SDK与Carbone API通信以生成文档。

安装

[dependencies]
carbone-sdk-rust = "1.0.0"

快速入门

尝试以下代码在10秒内渲染报告。只需插入您的API密钥、您要渲染的模板ID以及JSON数据集作为字符串。在您的Carbone账户上获取API密钥:https://account.carbone.io/

use std::env;
 
use carbone_sdk_rust::config::Config;
use carbone_sdk_rust::carbone::Carbone;
use carbone_sdk_rust::types::{ApiJsonToken, JsonData};
use carbone_sdk_rust::template::TemplateId;
 
use carbone_sdk_rust::errors::CarboneError;

use std::fs::File;
use std::io::Write

#[tokio::main]
async fn main() -> Result<(), CarboneError> {
    
    let token = "Token";

    let config: Config = Default::default();
 
    let api_token = ApiJsonToken::new(token.to_string())?;

    let json_data_value = String::from(r#"
        {
            "data" : {
                "firstname" : "John",
                "lastname" : "Wick"
            },
            "convertTo" : "odt"
        }
    "#);
 
    let json_data = JsonData::new(json_data_value)?;

    let template_id = TemplateId::new("YourTemplateId".to_string())?;

    let carbone = Carbone::new(&config, Some(&api_token))?;
    
    let report_content = match carbone.generate_report_with_template_id(template_id, json_data).await {
        Ok(v) => v,
        Err(e) => panic!("{}", e.to_string())
    };

    let mut output_file = File::create("report.pdf").expect("Failed to create file");

    if let Err(e) = output_file.write_all(&report_content) {
        eprintln!("Failed to write to file: {:?}", e);
    }

    Ok(())
}

Rust SDK API

目录

Carbone SDK构造函数

定义

let config: Config;

示例

创建一个新的Carbone Cloud SDK实例的示例:在您的Carbone账户上获取API密钥:https://account.carbone.io/

// For Carbone Cloud, provide your API Access Token as first argument:
let token = "Token";
let config: Config = Default::default();
let api_token = ApiJsonToken::new(token.to_string())?;
let carbone = Carbone::new(&config, Some(&api_token))?;

创建一个新的Carbone On-premise或Carbone On-AWS实例的示例

// Define the URL of your Carbone On-premise Server or AWS EC2 URL:
let config: Config = Config::new("ON_PREMISE_URL".to_string(), "api_time_out_in_sec_in_u64", ApiVersion::new("4".to_string()).expect("REASON")).expect("REASON");
let carbone = Carbone::new(&config, None)?;

构造函数用于创建一个新的CarboneSDK实例。访问令牌可以作为参数传递,也可以通过环境变量"CARBONE_TOKEN"传递。在您的Carbone账户上获取API密钥:https://account.carbone.io/。要设置新的环境变量,使用以下命令:

$ export CARBONE_TOKEN=your-secret-token

运行以下命令检查是否已设置:

$ printenv | grep "CARBONE_TOKEN"

生成并下载文档

从本地模板文件生成文档

pub async fn generate_report( &self, template_name: String, template_data: Vec<u8>, json_data: JsonData, payload: Option<&str>, salt: Option<&str>);

参数详情

  • template_name: 模板文件名。
  • template_data: 文件内容的Vec<u8>
  • json_data: 包含填充模板所需数据的JSON字符串。

示例

let file_name = "name_file.extention";
let file_path = format!("your/path/{}", file_name);
let file_content = fs::read(file_path)?;

let json_data_value = String::from(r#"
        {
            "data" : {
                "firstname" : "John",
                "lastname" : "Wick"
            },
            "convertTo" : "odt"
        }
    "#);

let json_data = JsonData::new(json_data_value)?;

let content = match carbone.generate_report(file_name.to_string(), file_content, json_data, None, None).await {
        Ok(v) => v,
        Err(e) => panic!("{}", e.to_string())
    };

,从模板ID生成文档

pub async fn pub async fn generate_report_with_template_id( &self, template_id: TemplateId, json_data: JsonData);

参数详情

  • 模板ID:模板ID(在 Carbone Studio 上管理您的模板)
  • json_data: 包含填充模板所需数据的JSON字符串。
let template_id = TemplateId::new("template_id".to_string())?;
let json_data = String::from(r#"
        {
            "data" : {
                "firstname" : "John",
                "lastname" : "Wick"
            },
            "convertTo" : "odt"
        }
    "#);

let json_data = JsonData::new(json_data_value)?;

let content = match carbone.generate_report_with_template_id( template_id, filte_content, json_data).await {
        Ok(v) => v,
        Err(e) => panic!("{}", e.to_string())
    };

添加模板

pub async fn upload_template(&self,file_name: &str,file_content: Vec<u8>,salt: Option<&str>);

将模板作为文件内容 Vec<u8> 添加,函数返回模板ID作为 String

示例


let template_name = "template.odt".to_string();
let template_path = format!("src/{}", template_name);
let template_data = fs::read(template_path.to_owned())?;

let template_id = match carbone.upload_template(template_name, template_data, None).await {
        Ok(v) => v,
        Err(e) => panic!("{}", e.to_string())
    };

删除模板

pub async fn delete_template(&self, template_id: TemplateId);

通过提供模板ID template_id 来删除模板,并返回请求是否成功作为一个 Boolean

示例

let template_id = TemplateId::new("template_id".to_string())?;

let boolean = match carbone.delete_template(template_id).await {
        Ok(v) => v,
        Err(e) => panic!("{}", e.to_string())
    };

仅生成文档

generate_report 函数接受一个模板ID作为 String,以及 JSON 数据集作为 JsonData。它返回一个 renderId,您可以将此 renderId 传递到 get_report 以下载文档。

pub async fn render_data( &self, template_id: TemplateId, json_data: JsonData);

示例


let template_id = TemplateId::new("template_id".to_string())?;

let json_data = String::from(r#"
        {
            "data" : {
                "firstname" : "John",
                "lastname" : "Wick"
            },
            "convertTo" : "odt"
        }
    "#);

let json_data = JsonData::new(json_data_value)?;

let render_id = match carbone.render_data(template_id, json_data).await {
        Ok(v) => v,
        Err(e) => panic!("{}", e.to_string())
    };


仅下载文档

定义

pub async fn get_report(&self, render_id: &RenderId);

示例


let render_id = RenderId::new("render_id".to_string())?;

let content = match carbone.get_report(&render_id).await {
        Ok(v) => v,
        Err(e) => panic!("{}", e.to_string())
    };

获取模板

定义

pub async fn download_template(&self, template_id: &TemplateId);

提供一个模板ID作为 String,它返回文件作为 Bytes

示例

let template_id = TemplateId::new("template_id".to_string())?;

let content = match carbone.download_template(&template_id).await {
        Ok(v) => v,
        Err(e) => panic!("{}", e.to_string())
    };

获取API状态

定义


pub async fn get_status(&self);

该函数请求 Carbone API 获取当前状态和版本作为 String

示例

let status = match carbone.get_status().await {
        Ok(v) => v,
        Err(e) => panic!("{}", e.to_string())
    };

设置API配置

定义

pub fn new(api_url: String, api_timeout: u64, api_version: ApiVersion)

为 Carbone On-premise 或 Carbone On-AWS 设置 API URL。

将构造函数的第二个参数指定为要请求的 Carbone Cloud API 版本。默认情况下,所有请求都是对 Carbone API 版本 4 进行。

示例

let config: Config = Config::new("ON_PREMISE_URL".to_string(), "api_time_out_in_sec_in_u64", ApiVersion::new("Version".to_string()).expect("REASON")).expect("REASON");

let carbone = Carbone::new(&config, None)?;

构建命令

在 SDK 仓库的根目录运行

cargo build

在另一个 Rust 项目中,您可以在 Cargo.toml 中加载 SDK 的本地构建版本


carbone-sdk-rust = {path = "your/local/path"}

最后,使用 SDK 编译您的 Rust 项目

cargo run 

测试命令

执行单元测试

cargo test

带有覆盖率的执行单元测试

cargo tarpaulin

👤 历史

该包最初由 Pascal Chenevas 制作,开源了代码。Carbone.io 团队现在维护 SDK 并将带来所有未来的进化。

🤝 贡献

欢迎贡献、问题和功能请求!请随意检查 问题页面

显示您的支持

如果这个项目对您有帮助,请给它一个 ⭐️!

依赖项

~13–29MB
~519K SLoC