Convert HTML and Webpages to PDF in Rust
In our latest series, we've explored how to leverage the Pdfcrowd cloud-based API for converting web pages and HTML files to PDF, previously using languages such as C and C++. As Rust offers a safer alternative to these languages, this article will guide you through integrating the Pdfcrowd HTML to PDF API into your Rust applications to achieve robust document conversion solutions. You can download the complete source code from GitHub.
Getting Started with the Pdfcrowd API in Rust
Prerequisities:
To begin, ensure that the reqwest
Rust HTTP client library is included in your project. This library is essential for making HTTP requests to the Pdfcrowd API. Install reqwest
by adding it to your Cargo.toml
file under dependencies:
[dependencies]
reqwest = { version = "0.11", features = ["blocking", "multipart"] }
Setting Up Your Rust Environment
Step 1: Initialize Your Project
Create a new Rust file and import the necessary modules and dependencies:
use std::fs::File;
use std::error::Error;
use reqwest::blocking::Client;
use reqwest::blocking::multipart::{Form, Part};
Step 2: Configure API Credentials
Define the Pdfcrowd API endpoint and your API credentials. For demonstration purposes, we'll use demo credentials:
static API_ENDPOINT: &'static str = "https://api.pdfcrowd.com/convert/latest/";
static USERNAME: &'static str = "demo";
static API_KEY: &'static str = "ce544b6ea52a5621fb9d55f8b542d14d";
Implementing the Conversion Function
Main Conversion Function:
The convert()
function orchestrates handling of API requests, and saving the response as a PDF file. Here’s how you can implement it:
fn convert(
fields: Vec<(&str, &str)>,
files: Vec<(&str, &str)>,
output_filename: &str
) -> Result<(), Box<dyn Error>> {
// Create a form
let mut form = Form::new();
// Add text fields to the form
for (key, value) in fields {
let part = Part::text(value.to_string()).mime_str("text/plain")?;
form = form.part(key.to_string(), part);
}
// Add files to the form
for (key, filename) in files {
form = form.file(key.to_string(), filename)?;
}
// Send the POST request using the configured client
let client = Client::builder().build()?;
let mut response = client.post(API_ENDPOINT)
.multipart(form)
.basic_auth(USERNAME.to_string(), Some(API_KEY))
.send()?;
// Validate the response
if !response.status().is_success() {
eprintln!("Pdfcrowd Error Code: {}", response.status().as_u16());
eprintln!("Pdfcrowd Error Details: {}", response.text()?);
return Err("Unexpected conversion error".into());
}
// Save the PDF to a local file
let mut file = File::create(output_filename)?;
response.copy_to(&mut file)?;
Ok(())
}
Practical Examples
Utilize the convert()
function in various scenarios:
Convert a Webpage to PDF:
let options = vec![
("input_format", "html"),
("output_format", "pdf"),
("page_size", "letter"),
("url", "https://example.com/")
];
convert(options, vec![], "example_url.pdf")
Convert an HTML String to PDF:
let options = vec![
("input_format", "html"),
("output_format", "pdf"),
("page_size", "letter"),
("text", "<h1>Hello from Pdfcrowd</h1>")
];
convert(options, vec![], "example_text.pdf")
Convert a Local HTML File to PDF:
let options = vec![
("input_format", "html"),
("output_format", "pdf"),
("page_size", "letter")
];
let files = vec![
("file", "your-file.html")
];
convert(options, files, "example_file.pdf")
Final Tips
For a detailed description of all available parameters and to get started, refer to our Getting Started guide and the HTTP Parameter Reference.
In addition to PDF conversion, the Pdfcrowd API offers a variety of other services. For instance, the HTML to Image API allows you to capture screenshots of webpages or HTML content directly into images. Here's a quick example of how to capture a webpage into a PNG image:
let options = vec![
("input_format", "html"),
("output_format", "png"),
("url", "https://example.com/")
];
convert(options, vec![], "screenshot.png")
For more information about our diverse API offerings, please visit the Pdfcrowd API documentation.
Updated: April 19, 2024