Code Sample for txt/2/pdf
API
Rust
This Rust sample demonstrates how to access the PDFTeam txt/2/pdf
API endpoint. The code converts a two-page plain text report to a PDF and adds overlays with some text and a QR code. Also added will be a header that prints the file title on every page. The resulting PDF will be stored in AWS S3, the permalink is returned to the caller.
We are using Rust's reqwest
-module with the tokio
runtime. The POST parameters are loaded from a separate file which are then parsed with serde
.
Dependencies are listed in cargo.toml
as follows:
// Sample Rust code for accessing the PDFTeam API, endpoint: txt/2/pdf
// File: cargo.toml
[package]
name = "txt-2-pdf"
version = "0.1.0"
edition = "2024"
[dependencies]
reqwest = {version = "0.12.15", features = ["blocking","json"]}
tokio = { version = "1.44.2", features = ["full"] }
serde = { version = "1.0.219", features = ["derive"] }
serde_json = "1.0.140"
POST parameters are in a separate file:
// Sample Rust code for accessing the PDFTeam API, endpoint: txt/2/pdf
// File: params.json
{
"job": "ACME ANALYSIS",
"user": "YOUR_USERNAME",
"key": "YOUR_APIKEY",
"test": false,
"inputOptions": {
"source": "https://pdfteam.com/samples/coyote_report.txt"
},
"outputOptions": {
"storage": true,
"file": "acme_analysis_rust.pdf"
},
"pdfOptions": {
"format": "A4",
"margin": {
"left": "2cm",
"top": "3cm",
"right": "2cm",
"bottom": "3cm",
},
},
"overlays": [
{
"position": {
"x": "170mm",
"y": "270mm"
},
"type": "barcode",
"config": {
"type": 19,
"data": "https://pdfteam.com"
}
},
{
"rotate": 45,
"position": {
"x": "center",
"y": "middle"
},
"type": "text",
"config": {
"data": "TOP SECRET",
"font": "Helvetica Bold",
"size": 72,
"color": "#ff0000",
"opacity": 0.5
}
},
],
"hfOptions": {
"footer": " ",
"header":
"<div style=\"color:#0000ff;font-size: 12px;margin-left:auto;margin-right:auto;\">TITLE: <span class=\"title\"></span></div>",
}
}
NOTE: Setting "test" to TRUE will not consume any credits but the generated PDF carries a watermark.
Main program:
// Sample Rust code for accessing the PDFTeam API, endpoint: txt/2/pdf
// File: main.rs
use std::error::Error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
// Read POST params as string
let params = std::fs::read_to_string("params.json").unwrap();
// Parse into JSON object
let params_json: serde_json::Value = serde_json::from_str(¶ms).expect("Malformed JSON");
let client = reqwest::Client::new();
let res = client
.post("https://api.pdfteam.com/api/txt/2/pdf")
.json(¶ms_json) // NOTE: json() will also set the content header properly
.send()
.await?
.text()
.await?;
println!("{}", res);
Ok(())
}
Sample response:
{"endpoint": "txt/2/pdf", "job": "ACME ANALYSIS", "credits": 1, "result": "https://pdfteam.s3.eu-north-1.amazonaws.com/.../acme_analysis_rust.pdf"}
Sample result: