anowell / wkhtmltopdf-rs

High-level Rust bindings for wkhtmltopdf
MIT License
75 stars 12 forks source link

Multiple calls to PdfApplication::new() fail with "IllegalInit" #11

Closed rjloura closed 3 years ago

rjloura commented 3 years ago

It seems multiple calls to PdfApplication::new() fail with IllegalInit even when the pdf_app value is dropped. See sample code below:

#[macro_use]
extern crate serde_derive;

use wkhtmltopdf::{PdfApplication, Orientation, Size};
use handlebars::Handlebars;
use serde_json::json;
use std::fs::File;

#[derive(Serialize)]
struct Entry {
    name: String,
    pay: f32,
}

fn write_pdf(num: i32) {
    let mut output_file = File::create("./table.html").expect("create file");

    let mut hb = Handlebars::new();
    let mut entries = vec![];
    for i in 0..10 {
        entries.push(
            Entry {name: "Me".to_string(), pay: i as f32}
        );
    }

    let data = json!({
        "entry": entries
    });

    hb
        .register_template_file("template", "./report.html.hbs")
        .unwrap();
    hb.render_to_write("template", &data, &mut output_file);

    let mut pdf_app = PdfApplication::new().expect("Failed to init PDF application");
    let mut pdfout = pdf_app.builder()
        .orientation(Orientation::Landscape)
        .margin(Size::Inches(2))
        .title("Awesome Foo")
        .build_from_path("./table.html")
        .expect("failed to build pdf");

    pdfout.save(format!("{}foo.pdf", num).as_str())
        .expect("failed to save foo.pdf");
    println!("generated PDF saved as: foo.pdf");

}
fn main() {
    for i in 0..2 {
        write_pdf(i)
    }
}
thread 'main' panicked at 'Failed to init PDF application: IllegalInit', src/main.rs:36:45
rjloura commented 3 years ago

I see the docs talk about this here (https://anowell.github.io/wkhtmltopdf-rs/wkhtmltopdf/struct.PdfApplication.html). It would be nice if it were possible to create multiple PDFs per-process across multiple threads.

anowell commented 3 years ago

For context/reference about this limitation, see: Hangs with multiple threads #1