Coder Social home page Coder Social logo

wkhtmltopdf-rs's Introduction

wkhtmltopdf-rs

High-level Rust bindings for wkhtmltopdf. This is a wrapper around the low-level binding provided by libwkhtmltox-sys.

Resource Link
Crate Crates.io
Documentation Cargo docs
Upstream wkhtmltopdf.org

This crate aims to provide full configuration of wkhtmltopdf with safe, ergonomic Rust. Wkhtmltopdf has several non-obvious limitations (mostly caused by Qt). that make it very easy to cause undefined behavior with the C bindings. Two such limitations that greatly impact the API are:

  1. Wkhtmltopdf initialization can only occur once per process; deinitialization does make it safe to reuse
  2. PDF generation must always occur on the thread that initialized wkhtmltopdf

This crate should make it impossible to break those rules in safe code. If you need parallel PDF generation, you will need to spawn/fork processes to do so. Such an abstraction would be a welcome addition to this crate.

Install

Install wkhtmltopdf 0.12.3.

Note: This library using the libs (shared objects) and includes (headers) for PDF generation instead of the wkhtmltopdf executable.

Usage

Basic usage looks like this:

  let html = r#"<html><body><div>foo</div></body></html>"#;
  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_html(&html)
      .expect("failed to build pdf");

  pdfout.save("foo.pdf").expect("failed to save foo.pdf");
  println!("generated PDF saved as: foo.pdf");

Build

As long as the includes are installed (e.g. pdf.h), then it's all cargo:

cargo build
cargo test

Note: tests have to be combined into a single test case because we can only init PdfApplication once, and it is !Send/!Sync. So the preference going forward will be to test with a variety of good examples.

Contributions welcome in the form of issue reports, feature requests, feedback, and/or pull request.

wkhtmltopdf-rs's People

Contributors

aleury avatar anowell avatar craigmayhew avatar icandivideby0 avatar leandrosilva avatar sciguy16 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

wkhtmltopdf-rs's Issues

Unable build on Windows 11 error: linking with `link.exe` failed: exit code: 1181

I got this error when start Tauri App

error: linking with `link.exe` failed: exit code: 1181
  |
  = note: "C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\VC\\Tools\\MSVC\\14.31.31103\\bin\\HostX64\\x64\\link.exe" "/NOLOGO" "C:\\Users\\Windows\\AppData\\Local\\Temp\\rustcN20GYh\\symbols.o"
.........
........
= note: LINK : fatal error LNK1181: cannot open input file 'wkhtmltox.lib'

I also have installed

  • wkhtmltopdf 0.12.3
  • MS Visual Studio 2022 and Visual Studio Build Tools 2019

Reinit is broken while readme says it works

Readme says "deinitialization does make it safe to reuse":

1. Wkhtmltopdf initialization can only occur once per process; deinitialization does make it safe to reuse

But the following test panics on second initialization, while the first one is dropped.

#[test]
fn double_init() {
	PdfApplication::new().expect("Failed to init PDF application");
	PdfApplication::new().expect("Failed to init PDF application");
}

Inconsistent documentation & code

/// Instantiate a `PdfBuilder`
///
/// This method borrows the `self` mutably to ensure only that one builder is active at a time which is a
/// [basic limitation of wkhtmltopdf](https://github.com/wkhtmltopdf/wkhtmltopdf/issues/1711).
/// Parallel execution is currently only possible by spawning multiple processes.
pub fn builder(&self) -> PdfBuilder {
PdfBuilder {
gs: HashMap::new(),
os: HashMap::new(),
}
}
}

/// Instantiate an `ImageBuilder`
///
/// This method borrows the `self` mutably to ensure only that one builder is active at a time which is a
/// [basic limitation of wkhtmltoimage](https://github.com/wkhtmltoimage/wkhtmltoimage/issues/1711).
/// Parallel execution is currently only possible by spawning multiple processes.
pub fn builder(&self) -> ImageBuilder {
ImageBuilder { gs: HashMap::new() }
}
}

Documentation states that self is mutably borrowed, while it's actually immutably borrowed. I think it's the code that's incorrect, but I'm not completely sure.

Also the links to https://github.com/wkhtmltoimage/wkhtmltoimage need to be updated to https://github.com/wkhtmltopdf/wkhtmltopdf. Currently they are 404ing.

Unable to build in windows

I am trying to use the library in windows console application. I am not able to build successfully. This is the error i am getting

/lowlevel.rs:92: undefined reference to wkhtmltopdf_init'`

i have the build.rs search for the library.

fn main() {
    println!(r"cargo:rustc-link-search=C:\Program Files\wkhtmltopdf\lib");
}

even after doing that i am getting the error.

Any help would be appreciated.

Thank You

Hangs with multiple threads

Despite the lazy static mutex that ensure we only init wkhtmltopdf once (via PdfGlobal::new(), it turns out that we can't let separate threads calling into wkhtmltopdf as it seems to result in hanging/idling inside wkhtmltopdf. Seems to align with this upstream issue

For now, don't spin up threads. I'll be experimenting with a few options:

  1. have each PdfGlobal fork into its own process
  2. return a LockResult<Mutex<T>> to callers, requiring them to unlock it before conversion (probably requires refactoring so all wkhtmltopdf calls happen during the call to convert, also means non-threaded uses will unnecessarily init/deinit for every conversion)
  3. Provide a toplevel wkhtmltopdf::init() -> LockResult<Mutex<PdfBuilder>> to make it clearer that you can have multiple builders in the same process.
  4. Skip to wkhtmltopdf 0.13 (alpha) if it allows threaded usage

Maintenance status

Hi, what is the status of this project? It doesn't seem to have had any activity since 2016 - are you acceping PRs?

Header and Footer

First of all thank you for the library.
How can i specify header and footer. In footer i want to add running page number.
How do i do that?

Thanks in advance

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

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

Local images not displayed in PDF

Hello, I have an HTML file that uses an image in the same folder as the HTML file. I can't get it to be displayed in the PDF, I can get the rest of the page, however. Is there a way to load the image also to the pdf? Due to some constraints, I can't use the load_from_path and load_from_url, so is there any workaround? Thank you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.