json2pdf_client/
lib.rs

1//! json2pdf Client library
2//!
3//! This library is a client library for the json2pdf server. json2pdf is a Java webserver that generates PDF
4//! documents from a JSON model.
5//!
6//! ## Example
7//! Generate a PDF documentation with some text and an image
8//! ```no_run
9//! use json2pdf_client::*;
10//!
11//! async fn generate_pdf() {
12//!     let spec = DocumentSpecification::new()
13//!         .add_element(Element::paragraph(Paragraph::new("Hello world!"))
14//!             .border(BorderSettings::new()
15//!                 .bottom(BorderSpecification::new(4f32))))
16//!         .add_element(Element::image(Image::new_bytes(&Vec::new(), 400f32, 400f32)));
17//!
18//!     let data = pdf("http://localhost:8080", &spec).await.unwrap();
19//! }
20//! ```
21
22mod protocol;
23
24pub use protocol::*;
25use reqwest::ClientBuilder;
26
27const USER_AGENT: &str = "PDF Rust Client Library";
28
29/// Generate a PDF document accordign to the provided specification
30///
31/// # Errors
32///
33/// If the server returns an error
34pub async fn pdf<S: AsRef<str>>(
35    server: S,
36    spec: &DocumentSpecification,
37) -> Result<Vec<u8>, reqwest::Error> {
38    Ok(ClientBuilder::new()
39        .user_agent(USER_AGENT)
40        .build()
41        .unwrap()
42        .get(format!("{}/generate", server.as_ref()))
43        .json(spec)
44        .send()
45        .await?
46        .error_for_status()?
47        .bytes()
48        .await?
49        .to_vec())
50}
51
52#[cfg(feature = "blocking")]
53pub mod blocking {
54    use crate::{DocumentSpecification, USER_AGENT};
55    use reqwest::blocking::ClientBuilder;
56
57    /// Generate a PDF document accordign to the provided specification
58    ///
59    /// # Errors
60    ///
61    /// If the server returns an error
62    pub fn pdf<S: AsRef<str>>(
63        server: S,
64        spec: &DocumentSpecification,
65    ) -> Result<Vec<u8>, reqwest::Error> {
66        Ok(ClientBuilder::new()
67            .user_agent(USER_AGENT)
68            .build()
69            .unwrap()
70            .get(format!("{}/generate", server.as_ref()))
71            .json(spec)
72            .send()?
73            .error_for_status()?
74            .bytes()?
75            .to_vec())
76    }
77}