gotenberg_pdf 0.5.2

A Rust client for the Gotenberg PDF API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use super::*;
use reqwest::multipart;
use reqwest::{Client as ReqwestClient, Response};

#[cfg(feature = "zeroize")]
use zeroize::Zeroize;

/// Gotenberg API client.
///
/// The client can be freely cloned and moved across threads.
/// All clones use the same connection pool for connection re-use.
#[derive(Clone)]
pub struct Client {
    client: ReqwestClient,
    base_url: String,
    username: Option<String>,
    password: Option<String>,
}

impl Drop for Client {
    fn drop(&mut self) {
        // Securely zeroize the username and password
        #[cfg(feature = "zeroize")]
        {
            if let Some(username) = &mut self.username {
                username.zeroize();
            }
            if let Some(password) = &mut self.password {
                password.zeroize();
            }
        }
    }
}

impl Debug for Client {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Client")
            .field("base_url", &self.base_url)
            .field("username", &self.username)
            .finish()
    }
}

impl Client {
    /// Create a new instance of the API client.
    pub fn new(base_url: &str) -> Self {
        // Strip trailing slashes
        let base_url = base_url.trim_end_matches('/');

        let client = Client::create_client();

        Client {
            client,
            base_url: base_url.to_string(),
            username: None,
            password: None,
        }
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn create_client() -> ReqwestClient {
        ReqwestClient::builder()
            .pool_idle_timeout(Some(std::time::Duration::from_secs(25))) // Adjust for server timeout
            .build()
            .unwrap()
    }

    #[cfg(target_arch = "wasm32")]
    fn create_client() -> ReqwestClient {
        ReqwestClient::default()
    }

    /// Create a new instance of the API client with a custom Reqwest client.
    ///
    /// Best practices include:
    ///   - [`reqwest::ClientBuilder::pool_idle_timeout`]. Set the pool timeout on the client to 5 seconds less than the Gotenberg server's idle timeout as set by `--api-timeout`.
    ///   - [`reqwest::ClientBuilder::http2_prior_knowledge`]. Use HTTP/2 without the need for ALPN negotiation. Useful if gotenberg is not behind a proxy. If you want to use HTTP/2 without HTTPS / TLS, this must be set.
    pub fn new_with_client(base_url: &str, client: ReqwestClient) -> Self {
        // Strip trailing slashes
        let base_url = base_url.trim_end_matches('/');

        Client {
            client,
            base_url: base_url.to_string(),
            username: None,
            password: None,
        }
    }

    /// Set the basic auth username and password for the Gotenberg server, consuming the current client and returning a new instance of the client.
    /// You can set the username and password on the Gotenberg server by starting it with `--api-enable-basic-auth` and supplying `GOTENBERG_API_BASIC_AUTH_USERNAME` and `GOTENBERG_API_BASIC_AUTH_PASSWORD` environment variables.
    ///
    /// # Example
    ///
    /// ```
    /// use gotenberg_pdf::Client;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///    let client = Client::new("http://localhost:3000").auth("username", "password");
    ///
    ///   // Now you can use the client to make requests
    /// }
    /// ```
    pub fn auth(self, username: &str, password: &str) -> Self {
        let mut client = self;
        client.username = Some(username.to_string());
        client.password = Some(password.to_string());

        client
    }

    /// Generic POST method that takes a multipart form and sends it.
    async fn post(
        &self,
        endpoint: &str,
        form: multipart::Form,
        trace: Option<String>,
    ) -> Result<Bytes, Error> {
        let url = format!("{}/{}", self.base_url, endpoint);

        let mut req = self.client.post(&url).multipart(form);
        if let Some(trace) = trace {
            req = req.header("Gotenberg-Trace", trace);
        }

        // Add basic auth if username and password are provided
        if let (Some(username), Some(password)) = (&self.username, &self.password) {
            req = req.basic_auth(username, Some(password));
        }

        let response: Response = req.send().await.map_err(Into::into)?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            return Err(Error::RenderingError(format!(
                "Failed to render PDF: {} - {}",
                status, body
            )));
        }

        response.bytes().await.map_err(Into::into)
    }

    /// Convert a URL to a PDF using the Chromium engine.
    pub async fn pdf_from_url(&self, url: &str, options: WebOptions) -> Result<Bytes, Error> {
        let trace = options.trace_id.clone();
        let form = multipart::Form::new().text("url", url.to_string());
        let form = options.fill_form(form);
        self.post("forms/chromium/convert/url", form, trace).await
    }

    /// Convert HTML to a PDF using the Chromium engine.
    pub async fn pdf_from_html(&self, html: &str, options: WebOptions) -> Result<Bytes, Error> {
        let trace = options.trace_id.clone();

        let form = multipart::Form::new();
        let file_bytes = html.to_string().into_bytes();
        let part = multipart::Part::bytes(file_bytes)
            .file_name("index.html")
            .mime_str("text/html")
            .unwrap();
        let form = form.part("index.html", part);
        let form = options.fill_form(form);
        self.post("forms/chromium/convert/html", form, trace).await
    }

    /// Convert Markdown to a PDF using the Chromium engine.
    ///
    /// The HTML template should in the following format:
    ///
    /// ```html
    /// <!doctype html>
    /// <html lang="en">
    ///  <head>
    ///    <meta charset="utf-8">
    ///    <title>My PDF</title>
    ///  </head>
    ///  <body>
    ///    {{ toHTML "file.md" }}
    ///  </body>
    /// </html>
    /// ```
    ///
    /// The markdown files should be in a "filename" => "content" format. The filename key string must end with `.md`.
    pub async fn pdf_from_markdown(
        &self,
        html_template: &str,
        markdown: HashMap<&str, &str>,
        options: WebOptions,
    ) -> Result<Bytes, Error> {
        let trace = options.trace_id.clone();

        let form = multipart::Form::new();

        let file_bytes = html_template.to_string().into_bytes();
        let part = multipart::Part::bytes(file_bytes)
            .file_name("index.html")
            .mime_str("text/html")
            .unwrap();
        let form = form.part("index.html", part);
        let form = options.fill_form(form);

        let form = {
            let mut form = form;
            for (filename, content) in markdown {
                if !filename.ends_with(".md") {
                    return Err(Error::FilenameError(
                        "Markdown filename must end with '.md'".to_string(),
                    ));
                }
                let file_bytes = content.to_string().into_bytes();
                let part = multipart::Part::bytes(file_bytes)
                    .file_name(filename.to_string())
                    .mime_str("text/markdown")
                    .unwrap();
                form = form.part(filename.to_string(), part);
            }
            form
        };

        self.post("forms/chromium/convert/markdown", form, trace)
            .await
    }

    /// Take a screenshot of a webpage using the Chromium engine.
    pub async fn screenshot_url(
        &self,
        url: &str,
        options: ScreenshotOptions,
    ) -> Result<Bytes, Error> {
        let trace = options.trace_id.clone();
        let form = multipart::Form::new().text("url", url.to_string());
        let form = options.fill_form(form);
        self.post("forms/chromium/screenshot/url", form, trace)
            .await
    }

    /// Take a screenshot of an HTML page using the Chromium engine.
    pub async fn screenshot_html(
        &self,
        html: &str,
        options: ScreenshotOptions,
    ) -> Result<Bytes, Error> {
        let trace = options.trace_id.clone();

        let form = multipart::Form::new();
        let file_bytes = html.to_string().into_bytes();
        let part = multipart::Part::bytes(file_bytes)
            .file_name("index.html")
            .mime_str("text/html")
            .unwrap();
        let form = form.part("index.html", part);
        let form = options.fill_form(form);
        self.post("forms/chromium/screenshot/html", form, trace)
            .await
    }

    /// Take a screenshot of a set of markdown files using the Chromium engine.
    pub async fn screenshot_markdown(
        &self,
        html_template: &str,
        markdown: HashMap<&str, &str>,
        options: ScreenshotOptions,
    ) -> Result<Bytes, Error> {
        let trace = options.trace_id.clone();

        let form = multipart::Form::new();

        let file_bytes = html_template.to_string().into_bytes();
        let part = multipart::Part::bytes(file_bytes)
            .file_name("index.html")
            .mime_str("text/html")
            .unwrap();
        let form = form.part("index.html", part);
        let form = options.fill_form(form);

        let form = {
            let mut form = form;
            for (filename, content) in markdown {
                if !filename.ends_with(".md") {
                    return Err(Error::FilenameError(
                        "Markdown filename must end with '.md'".to_string(),
                    ));
                }
                let file_bytes = content.to_string().into_bytes();
                let part = multipart::Part::bytes(file_bytes)
                    .file_name(filename.to_string())
                    .mime_str("text/markdown")
                    .unwrap();
                form = form.part(filename.to_string(), part);
            }
            form
        };

        self.post("forms/chromium/screenshot/markdown", form, trace)
            .await
    }

    /// Convert a document to a PDF using the LibreOffice engine.
    ///
    /// Supports the following file formats:
    /// ```txt
    /// .123 .602 .abw .bib .bmp .cdr .cgm .cmx .csv .cwk .dbf .dif .doc
    /// .docm .docx .dot .dotm .dotx .dxf .emf .eps .epub .fodg .fodp .fods
    /// .fodt .fopd .gif .htm .html .hwp .jpeg .jpg .key .ltx .lwp .mcw .met
    /// .mml .mw .numbers .odd .odg .odm .odp .ods .odt .otg .oth .otp .ots .ott
    /// .pages .pbm .pcd .pct .pcx .pdb .pdf .pgm .png .pot .potm .potx .ppm .pps
    /// .ppt .pptm .pptx .psd .psw .pub .pwp .pxl .ras .rtf .sda .sdc .sdd .sdp .sdw
    /// .sgl .slk .smf .stc .std .sti .stw .svg .svm .swf .sxc .sxd .sxg .sxi .sxm
    /// .sxw .tga .tif .tiff .txt .uof .uop .uos .uot .vdx .vor .vsd .vsdm .vsdx
    /// .wb2 .wk1 .wks .wmf .wpd .wpg .wps .xbm .xhtml .xls .xlsb .xlsm .xlsx .xlt
    /// .xltm .xltx .xlw .xml .xpm .zabw
    /// ```
    pub async fn pdf_from_doc(
        &self,
        filename: &str,
        bytes: Vec<u8>,
        options: DocumentOptions,
    ) -> Result<Bytes, Error> {
        let trace = options.trace_id.clone();

        let form = multipart::Form::new();
        let part = multipart::Part::bytes(bytes).file_name(filename.to_string());
        let form = form.part("files", part);
        let form = options.fill_form(form);
        self.post("forms/libreoffice/convert", form, trace).await
    }

    /// Transforms a PDF file into the requested PDF/A format and/or PDF/UA.
    pub async fn convert_pdf(
        &self,
        pdf_bytes: Vec<u8>,
        pdfa: Option<PDFFormat>,
        pdfua: bool,
    ) -> Result<Bytes, Error> {
        let form = multipart::Form::new();
        let part = multipart::Part::bytes(pdf_bytes).file_name("file.pdf".to_string());
        let mut form = form.part("file.pdf", part);
        if let Some(pdfa) = pdfa {
            form = form.text("pdfa", pdfa.to_string());
        }
        let form = form.text("pdfua", pdfua.to_string());
        self.post("forms/pdfengines/convert", form, None).await
    }

    /// Read the metadata of a PDF file
    pub async fn read_metadata(
        &self,
        pdf_bytes: Vec<u8>,
    ) -> Result<HashMap<String, serde_json::Value>, Error> {
        let form = multipart::Form::new();
        let part = multipart::Part::bytes(pdf_bytes).file_name("file.pdf".to_string());
        let form = form.part("file.pdf", part);

        #[derive(Debug, Deserialize)]
        pub struct MeatadataContainer {
            #[serde(rename = "file.pdf")]
            pub filepdf: HashMap<String, serde_json::Value>,
        }

        let bytes = self
            .post("forms/pdfengines/metadata/read", form, None)
            .await?;
        let metadata: MeatadataContainer = serde_json::from_slice(&bytes).map_err(|e| {
            Error::ParseError(
                "Metadata".to_string(),
                String::from_utf8_lossy(&bytes).to_string(),
                e.to_string(),
            )
        })?;

        Ok(metadata.filepdf)
    }

    /// Write metadata to a PDF file
    pub async fn write_metadata(
        &self,
        pdf_bytes: Vec<u8>,
        metadata: HashMap<String, serde_json::Value>,
    ) -> Result<Bytes, Error> {
        let form = multipart::Form::new();
        let part = multipart::Part::bytes(pdf_bytes).file_name("file.pdf".to_string());
        let form = form.part("file.pdf", part);
        let metadata = serde_json::to_string(&metadata).map_err(|e| {
            Error::ParseError("Metadata".to_string(), "".to_string(), e.to_string())
        })?;
        let part = multipart::Part::text(metadata);
        let form = form.part("metadata", part);
        self.post("forms/pdfengines/metadata/write", form, None)
            .await
    }

    /// Get the health status of the Gotenberg server.
    pub async fn health_check(&self) -> Result<health::Health, Error> {
        let url = format!("{}/health", self.base_url);
        let response = self.client.get(&url).send().await.map_err(Into::into)?;
        let body = response.text().await.map_err(Into::into)?;
        serde_json::from_str(&body)
            .map_err(|e| Error::ParseError("Health".to_string(), body, e.to_string()))
    }

    /// Get the version of the Gotenberg server.
    pub async fn version(&self) -> Result<String, Error> {
        let url = format!("{}/version", self.base_url);
        let response = self.client.get(&url).send().await.map_err(Into::into)?;
        let body = response.text().await.map_err(Into::into)?;
        Ok(body)
    }

    /// Get the metrics of the Gotenberg server in prometheus format.
    /// The results will not be parsed and are returned as a multi-line string.
    ///
    /// By default the namespace is `gotenberg`, but this can be changed by passing `--prometheus-namespace` to the Gotenberg server on startup.
    ///
    /// - `{namespace}_chromium_requests_queue_size`    Current number of Chromium conversion requests waiting to be treated.
    /// - `{namespace}_chromium_restarts_count`	        Current number of Chromium restarts.
    /// - `{namespace}_libreoffice_requests_queue_size`	Current number of LibreOffice conversion requests waiting to be treated.
    /// - `{namespace}_libreoffice_restarts_count`	    Current number of LibreOffice restarts.
    pub async fn metrics(&self) -> Result<String, Error> {
        let url = format!("{}/prometheus/metrics", self.base_url);
        let response = self.client.get(&url).send().await.map_err(Into::into)?;
        let body = response.text().await.map_err(Into::into)?;
        Ok(body)
    }
}