Pdfcrowd Blog
Product updates, tips & tricks

Convert HTML to PDF in Rust

In the previous installments of this series we showed how to use the Pdfcrowd API to convert web pages and HTML files to PDF using C and C++. Rust is considered a safe alternative to C and C++, so in this article we will show how to integrate the Pdfcrowd API into your Rust applications.

The code will use the reqwest Rust HTTP client library to make HTTP requests to the API. You can download complete sample code for quick integration into your project.

 

Step by Step Tutorial

1. Install reqwest library by adding it to the dependencies section of your Cargo.toml file:

[dependencies]
reqwest = { version = "0.11", features = ["blocking", "multipart"] }

2. Create a new Rust file and include the following dependencies:

use std::fs::File;
use std::error::Error;
use reqwest::blocking::Client;
use reqwest::blocking::multipart::{Form, Part};

3. Define the Pdfcrowd API endpoint and your API credentials as constants. For the purposes of this tutorial, we 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";

4. Implement the main conversion function:

fn convert(fields: Vec<(&str, &str)>, files: Vec<(&str, &str)>, output_filename: &str) -> Result<(), Box<dyn Error>> {
    // create multipart form
    let mut form = Form::new();

    // set fields to upload
    for (key, value) in fields {
        let part = Part::text(value.to_string()).mime_str("text/plain")?;
        form = form.part(key.to_string(), part);
    }

    // set files to upload
    for (key, filename) in files {
        form = form.file(key.to_string(), filename)?;
    }

    // create client and make the POST request
    let client = Client::builder().build()?;

    let mut response = client.post(API_ENDPOINT)
        .multipart(form)
        .basic_auth(USERNAME.to_string(), Some(API_KEY))
        .send()?;

    // check the HTTP 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());
    }

    // write the output to a local file
    let mut file = File::create(output_filename)?;
    response.copy_to(&mut file)?;

    Ok(())
}

Now we can use the convert() function in examples.

Convert URL 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 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 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

  • see the list of all conversion options available to customize your PDF output
  • the same approach can be used for all Pdfcrowd REST API conversions so e.g. for converting HTML to PNG just replace:
("output_format", "pdf")

with

("output_format", "png")
  • the reqwest library also provides an asynchronous client, which means that with a few modifications to our tutorial, the code can be adapted for use in an asynchronous environment