-
Notifications
You must be signed in to change notification settings - Fork 124
Expand file tree
/
Copy pathlib.rs
More file actions
1459 lines (1363 loc) · 47.3 KB
/
lib.rs
File metadata and controls
1459 lines (1363 loc) · 47.3 KB
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! # Plotly Static Image Export
//!
//! A Rust library for exporting Plotly plots to static images using headless
//! browsers via WebDriver.
//!
//! This library provides a interface for converting Plotly plots provided as
//! JSON values into various static image formats (PNG, JPEG, WEBP, SVG,
//! PDF) using WebDriver and headless browsers.
//!
//! ## Features
//!
//! - **Multiple Formats**: Support for PNG, JPEG, WEBP, SVG, and PDF export
//! - **Headless Rendering**: Uses headless browsers for rendering
//! - **WebDriver Support**: Supports both Chrome (chromedriver) and Firefox
//! (geckodriver)
//! - **Configurable**: Customizable dimensions, scale, and browser capabilities
//! - **Offline Mode**: Can work with offline bundled JavaScript libraries
//! - **Automatic Management**: Handles WebDriver process lifecycle and cleanup
//! - **Parallelism**: Designed for use in parallel environments (tests, etc.)
//! - **Logging Support**: Integrated logging with `env_logger` support
//!
//! ## Quick Start
//!
//! ```no_run
//! // This example requires a WebDriver-compatible browser (Chrome/Firefox).
//! // It cannot be run as a doc test.
//! use plotly_static::{StaticExporterBuilder, ImageFormat};
//! use serde_json::json;
//! use std::path::Path;
//!
//! // Create a simple plot
//! let plot = json!({
//! "data": [{
//! "type": "scatter",
//! "x": [1, 2, 3, 4],
//! "y": [10, 11, 12, 13]
//! }],
//! "layout": {
//! "title": "Simple Scatter Plot"
//! }
//! });
//!
//! // Build and use StaticExporter
//! let mut exporter = StaticExporterBuilder::default()
//! .build()
//! .expect("Failed to build StaticExporter");
//!
//! // Export to PNG
//! exporter.write_fig(
//! Path::new("my_plot"),
//! &plot,
//! ImageFormat::PNG,
//! 800,
//! 600,
//! 1.0
//! ).expect("Failed to export plot");
//! ```
//!
//! ## Features and Dependencies
//!
//! ### Required Features
//!
//! You must enable one of the following features:
//!
//! - `chromedriver`: Use Chrome/Chromium for rendering
//! - `geckodriver`: Use Firefox for rendering
//!
//! ### Optional Features
//!
//! - `webdriver_download`: Automatically download WebDriver binaries at build
//! time
//!
//! ### Example Cargo.toml
//!
//! ```toml
//! [dependencies]
//! plotly_static = { version = "0.0.4", features = ["chromedriver", "webdriver_download"] }
//! ```
//!
//! ## Advanced Usage
//!
//! ### Custom Configuration
//!
//! ```no_run
//! use plotly_static::StaticExporterBuilder;
//!
//! let exporter = StaticExporterBuilder::default()
//! .webdriver_port(4444)
//! .webdriver_url("http://localhost")
//! .spawn_webdriver(true)
//! .offline_mode(true)
//! .webdriver_browser_caps(vec![
//! "--headless".to_string(),
//! "--no-sandbox".to_string(),
//! "--disable-gpu".to_string(),
//! ])
//! .build()
//! .expect("Failed to build StaticExporter");
//! ```
//!
//! ### Browser Binary Configuration
//!
//! You can specify custom browser binaries using environment variables:
//!
//! ```bash
//! # For Chrome/Chromium
//! export BROWSER_PATH="/path/to/chrome"
//!
//! # For Firefox
//! export BROWSER_PATH="/path/to/firefox"
//! ```
//!
//! The library will automatically use these binaries when creating WebDriver
//! sessions.
//!
//! ### String Export
//!
//! ```no_run
//! // This example requires a running WebDriver (chromedriver/geckodriver) and a browser.
//! // It cannot be run as a doc test.
//! use plotly_static::{StaticExporterBuilder, ImageFormat};
//! use serde_json::json;
//!
//! let plot = json!({
//! "data": [{"type": "scatter", "x": [1,2,3], "y": [4,5,6]}],
//! "layout": {}
//! });
//!
//! let mut exporter = StaticExporterBuilder::default()
//! .build()
//! .expect("Failed to build StaticExporter");
//!
//! let svg_data = exporter.write_to_string(
//! &plot,
//! ImageFormat::SVG,
//! 800,
//! 600,
//! 1.0
//! ).expect("Failed to export plot");
//!
//! // svg_data contains SVG markup that can be embedded in HTML
//! ```
//!
//! ### Logging Support
//!
//! The library supports logging via the `log` crate. Enable it with
//! `env_logger`:
//!
//! ```no_run
//! use plotly_static::StaticExporterBuilder;
//!
//! // Initialize logging (typically done once at the start of your application)
//! env_logger::init();
//!
//! // Set log level via environment variable
//! // RUST_LOG=debug cargo run
//!
//! let mut exporter = StaticExporterBuilder::default()
//! .build()
//! .expect("Failed to build StaticExporter");
//! ```
//!
//! ### Parallel Usage
//!
//! The library is designed to work safely in parallel environments:
//!
//! ```no_run
//! use plotly_static::{StaticExporterBuilder, ImageFormat};
//! use std::sync::atomic::{AtomicU32, Ordering};
//!
//! // Generate unique ports for parallel usage
//! static PORT_COUNTER: AtomicU32 = AtomicU32::new(4444);
//!
//! fn get_unique_port() -> u32 {
//! PORT_COUNTER.fetch_add(1, Ordering::SeqCst)
//! }
//!
//! // Each thread/process should use a unique port
//! let mut exporter = StaticExporterBuilder::default()
//! .webdriver_port(get_unique_port())
//! .build()
//! .expect("Failed to build StaticExporter");
//! ```
//!
//! ## WebDriver Management
//!
//! The library automatically manages WebDriver processes:
//!
//! - **Automatic Detection**: Detects if WebDriver is already running on the
//! specified port
//! - **Process Spawning**: Automatically spawns WebDriver if not already
//! running
//! - **Connection Reuse**: Reuses existing WebDriver sessions when possible
//! - **Cleanup**: Automatically terminates WebDriver processes when
//! `StaticExporter` is dropped
//! - **External Sessions**: Can connect to externally managed WebDriver
//! sessions
//!
//! ### WebDriver Configuration
//!
//! Set the `WEBDRIVER_PATH` environment variable to specify a custom WebDriver
//! binary location (should point to the full executable path):
//!
//! ```bash
//! export WEBDRIVER_PATH=/path/to/chromedriver
//! cargo run
//! ```
//!
//! Or use the `webdriver_download` feature for automatic download at build
//! time.
//!
//! ## Error Handling
//!
//! The library uses `anyhow::Result` for error handling. Common errors include:
//!
//! - WebDriver not available or not running
//! - Invalid Plotly JSON format
//! - File system errors
//! - Browser rendering errors
//!
//! ## Browser Support
//!
//! - **Chrome/Chromium**: Full support via chromedriver
//! - **Firefox**: Full support via geckodriver
//! - **Safari**: Not currently supported
//! - **Edge**: Not currently supported
//!
//! ## Performance Considerations
//!
//! - **Reuse Exporters**: Reuse `StaticExporter` instances for multiple exports
//! - **Parallel Usage**: Use unique ports for parallel operations
//! - **WebDriver Reuse**: The library automatically reuses WebDriver sessions
//! when possible
//! - **Resource Cleanup**: WebDriver processes are automatically cleaned up on
//! drop
//!
//! ## Comparison with Kaleido
//!
//! - **No custom Chromium/Chrome external dependency**: Uses standard WebDriver
//! instead of proprietary Kaleido
//! - **Better Browser Support**: Works with any WebDriver-compatible browser:
//! Chrome/Chromium,Firefox,Brave
//! - **Extensible**: Easy to control browser capabilities and customize the
//! StaticExporter instance
//!
//! ## Limitations
//!
//! - Requires a WebDriver-compatible browser
//! - PDF export uses browser JavaScript `html2pdf` (not native Plotly PDF)
//! - EPS is no longer supported and will be removed
//! - Slightly slower than Kaleido
//!
//! ## License
//!
//! MIT License - see LICENSE file for details.
// TODO: remove this once version 0.14.0 is out
#![allow(deprecated)]
use std::fs::File;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use std::vec;
#[cfg(any(test, feature = "debug"))]
use std::{println as error, println as warn, println as debug};
use anyhow::{anyhow, Context, Result};
use base64::{engine::general_purpose, Engine as _};
use fantoccini::{wd::Capabilities, Client, ClientBuilder};
#[cfg(not(any(test, feature = "debug")))]
use log::{debug, error, warn};
use serde::Serialize;
use serde_json::map::Map as JsonMap;
use urlencoding::encode;
use webdriver::WebDriver;
use crate::template::{image_export_js_script, pdf_export_js_script};
mod template;
mod webdriver;
/// Supported image formats for static image export.
///
/// This enum defines all the image formats that can be exported from Plotly
/// plots. Note that PDF export is implemented using browser JavaScript
/// functionality from `html2pdf` library, not the native Plotly PDF export.
///
/// # Supported Formats
///
/// - **PNG**: Portable Network Graphics format (recommended for web use)
/// - **JPEG**: Joint Photographic Experts Group format (good for photos)
/// - **WEBP**: Google's modern image format (excellent compression)
/// - **SVG**: Scalable Vector Graphics format (vector-based, scalable)
/// - **PDF**: Portable Document Format (implemented via browser JS)
///
/// # Deprecated Formats
///
/// - **EPS**: Encapsulated PostScript format (deprecated since 0.13.0, will be
/// removed in 0.14.0)
/// - Use SVG or PDF instead for vector graphics
/// - EPS is not supported in the open source version and in versions prior to
/// 0.13.0 has been generating empty images.
///
/// # Examples
///
/// ```rust
/// use plotly_static::ImageFormat;
///
/// let format = ImageFormat::PNG;
/// assert_eq!(format.to_string(), "png");
/// ```
#[derive(Debug, Clone, Serialize)]
#[allow(deprecated)]
pub enum ImageFormat {
/// Portable Network Graphics format
PNG,
/// Joint Photographic Experts Group format
JPEG,
/// WebP format (Google's image format)
WEBP,
/// Scalable Vector Graphics format
SVG,
/// Portable Document Format (implemented via browser JS)
PDF,
/// Encapsulated PostScript format (deprecated)
///
/// This format is deprecated since version 0.13.0 and will be removed in
/// version 0.14.0. Use SVG or PDF instead for vector graphics. EPS is
/// not supported in the open source Plotly ecosystem version.
#[deprecated(
since = "0.13.0",
note = "Use SVG or PDF instead. EPS variant will be removed in version 0.14.0"
)]
EPS,
}
impl std::fmt::Display for ImageFormat {
/// Formats the ImageFormat as a string.
///
/// # Examples
///
/// ```rust
/// use plotly_static::ImageFormat;
/// assert_eq!(ImageFormat::SVG.to_string(), "svg");
/// assert_eq!(ImageFormat::PDF.to_string(), "pdf");
/// ```
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Self::PNG => "png",
Self::JPEG => "jpeg",
Self::WEBP => "webp",
Self::SVG => "svg",
Self::PDF => "pdf",
#[allow(deprecated)]
Self::EPS => "eps",
}
)
}
}
/// TODO: ideally data would be a Plot object which is later serialized to JSON
/// but with the current workspace set up, that would be a cyclic dependency.
#[derive(Serialize)]
struct PlotData<'a> {
format: ImageFormat,
width: usize,
height: usize,
scale: f64,
data: &'a serde_json::Value,
}
/// Builder for configuring and creating a `StaticExporter` instance.
///
/// This builder provides an interface for configuring WebDriver settings,
/// browser capabilities, and other options before creating a `StaticExporter`
/// instance. The builder automatically handles WebDriver process management,
/// including detection of existing sessions and automatic spawning when needed.
///
/// # Examples
///
/// ```no_run
/// // This example requires a running WebDriver (chromedriver/geckodriver) and a browser.
/// // It cannot be run as a doc test.
/// use plotly_static::StaticExporterBuilder;
///
/// let exporter = StaticExporterBuilder::default()
/// .webdriver_port(4444)
/// .spawn_webdriver(true)
/// .offline_mode(false)
/// .pdf_export_timeout(500)
/// .build()
/// .expect("Failed to build StaticExporter");
/// ```
///
/// # Default Configuration
///
/// - WebDriver port: 4444
/// - WebDriver URL: "http://localhost"
/// - Spawn webdriver: true (automatically manages WebDriver lifecycle)
/// - Offline mode: false
/// - PDF export timeout: 250ms
/// - Browser capabilities: Default Chrome/Firefox headless options
/// - Automatic WebDriver detection and connection reuse
pub struct StaticExporterBuilder {
/// WebDriver server port (default: 4444)
webdriver_port: u32,
/// WebDriver server base URL (default: "http://localhost")
webdriver_url: String,
/// Auto-spawn WebDriver if not running (default: true)
spawn_webdriver: bool,
/// Use bundled JS libraries instead of CDN (default: false)
offline_mode: bool,
/// PDF export timeout in milliseconds (default: 150)
pdf_export_timeout: u32,
/// Browser command-line flags (e.g., "--headless", "--no-sandbox")
webdriver_browser_caps: Vec<String>,
}
impl Default for StaticExporterBuilder {
/// Creates a new `StaticExporterBuilder` with default configuration.
///
/// The default configuration includes:
/// - WebDriver port: 4444
/// - WebDriver URL: "http://localhost"
/// - Spawn webdriver: true
/// - Offline mode: false
/// - PDF export timeout: 250ms
/// - Default browser capabilities for headless operation
fn default() -> Self {
Self {
webdriver_port: webdriver::WEBDRIVER_PORT,
webdriver_url: webdriver::WEBDRIVER_URL.to_string(),
spawn_webdriver: true,
offline_mode: false,
pdf_export_timeout: 150,
webdriver_browser_caps: {
#[cfg(feature = "chromedriver")]
{
crate::webdriver::chrome_default_caps()
.into_iter()
.map(|s| s.to_string())
.collect()
}
#[cfg(feature = "geckodriver")]
{
crate::webdriver::firefox_default_caps()
.into_iter()
.map(|s| s.to_string())
.collect()
}
#[cfg(not(any(feature = "chromedriver", feature = "geckodriver")))]
{
Vec::new()
}
},
}
}
}
impl StaticExporterBuilder {
/// Sets the WebDriver port number.
///
/// # Examples
///
/// ```rust
/// use plotly_static::StaticExporterBuilder;
///
/// let builder = StaticExporterBuilder::default()
/// .webdriver_port(4444);
/// ```
pub fn webdriver_port(mut self, port: u32) -> Self {
self.webdriver_port = port;
self
}
/// Sets the WebDriver URL.
///
/// # Examples
///
/// ```rust
/// use plotly_static::StaticExporterBuilder;
///
/// let builder = StaticExporterBuilder::default()
/// .webdriver_url("http://localhost");
/// ```
pub fn webdriver_url(mut self, url: &str) -> Self {
self.webdriver_url = url.to_string();
self
}
/// Controls whether to automatically spawn a WebDriver process.
///
/// If `true`, automatically spawns a WebDriver process. If `false`,
/// expects an existing WebDriver server to be running.
///
/// # Examples
///
/// ```rust
/// use plotly_static::StaticExporterBuilder;
///
/// // Auto-spawn WebDriver
/// let builder = StaticExporterBuilder::default()
/// .spawn_webdriver(true);
///
/// // Use existing WebDriver server
/// let builder = StaticExporterBuilder::default()
/// .spawn_webdriver(false);
/// ```
pub fn spawn_webdriver(mut self, yes: bool) -> Self {
self.spawn_webdriver = yes;
self
}
/// Controls whether to use offline mode with bundled JavaScript libraries.
///
/// If `true`, uses bundled JavaScript libraries instead of CDN. If `false`,
/// downloads libraries from CDN.
///
/// # Examples
///
/// ```rust
/// use plotly_static::StaticExporterBuilder;
///
/// // Use bundled libraries (no internet required)
/// let builder = StaticExporterBuilder::default()
/// .offline_mode(true);
///
/// // Use CDN libraries
/// let builder = StaticExporterBuilder::default()
/// .offline_mode(false);
/// ```
pub fn offline_mode(mut self, yes: bool) -> Self {
self.offline_mode = yes;
self
}
/// Sets the PDF export timeout in milliseconds.
///
/// This timeout controls how long to wait for the SVG image to load before
/// proceeding with PDF generation. A longer timeout may be needed for
/// complex plots or slower systems.
///
/// # Examples
///
/// ```rust
/// use plotly_static::StaticExporterBuilder;
///
/// // Set a longer timeout for complex plots
/// let builder = StaticExporterBuilder::default()
/// .pdf_export_timeout(500);
///
/// // Use default timeout (150ms)
/// let builder = StaticExporterBuilder::default()
/// .pdf_export_timeout(150);
/// ```
pub fn pdf_export_timeout(mut self, timeout_ms: u32) -> Self {
self.pdf_export_timeout = timeout_ms;
self
}
/// Sets custom browser capabilities for the WebDriver.
///
/// # Examples
///
/// ```rust
/// use plotly_static::StaticExporterBuilder;
///
/// let custom_caps = vec![
/// "--headless".to_string(),
/// "--no-sandbox".to_string(),
/// "--disable-gpu".to_string(),
/// ];
///
/// let builder = StaticExporterBuilder::default()
/// .webdriver_browser_caps(custom_caps);
/// ```
pub fn webdriver_browser_caps(mut self, caps: Vec<String>) -> Self {
self.webdriver_browser_caps = caps;
self
}
/// Builds a `StaticExporter` instance with the current configuration.
///
/// This method creates a new `StaticExporter` instance with all the
/// configured settings. The method manages WebDriver:
///
/// - If `spawn_webdriver` is enabled, it first tries to connect to an
/// existing WebDriver session on the specified port, and only spawns a
/// new process if none is found
/// - If `spawn_webdriver` is disabled, it creates a connection to an
/// existing WebDriver without spawning
///
/// Returns a `Result<StaticExporter>` where:
/// - `Ok(exporter)` - Successfully created the StaticExporter instance
/// - `Err(e)` - Failed to create the instance (e.g., WebDriver not
/// available, port conflicts, etc.)
///
/// # Examples
///
/// ```rust
/// use plotly_static::StaticExporterBuilder;
///
/// let exporter = StaticExporterBuilder::default()
/// .webdriver_port(4444)
/// .build()
/// .expect("Failed to build StaticExporter");
/// ```
pub fn build(&self) -> Result<StaticExporter> {
let wd = self.create_webdriver()?;
let runtime = std::sync::Arc::new(
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.expect("Failed to create Tokio runtime"),
);
Ok(StaticExporter {
webdriver_port: self.webdriver_port,
webdriver_url: self.webdriver_url.clone(),
webdriver: wd,
offline_mode: self.offline_mode,
pdf_export_timeout: self.pdf_export_timeout,
webdriver_browser_caps: self.webdriver_browser_caps.clone(),
runtime,
webdriver_client: None,
})
}
/// Create a new WebDriver instance based on the spawn_webdriver flag
fn create_webdriver(&self) -> Result<WebDriver> {
match self.spawn_webdriver {
// Try to connect to existing WebDriver or spawn new if not available
true => WebDriver::connect_or_spawn(self.webdriver_port),
// Create the WebDriver instance without spawning
false => WebDriver::new(self.webdriver_port),
}
}
}
/// Main struct for exporting Plotly plots to static images.
///
/// This struct provides methods to convert Plotly JSON plots into various
/// static image formats using a headless browser via WebDriver.
///
/// # Examples
///
/// ```no_run
/// // This example requires a running WebDriver (chromedriver/geckodriver) and a browser.
/// // It cannot be run as a doc test.
/// use plotly_static::{StaticExporterBuilder, ImageFormat};
/// use serde_json::json;
/// use std::path::Path;
///
/// // Create a simple plot
/// let plot = json!({
/// "data": [{
/// "type": "scatter",
/// "x": [1, 2, 3],
/// "y": [4, 5, 6]
/// }],
/// "layout": {}
/// });
///
/// // Build StaticExporter instance
/// let mut exporter = StaticExporterBuilder::default()
/// .build()
/// .expect("Failed to build StaticExporter");
///
/// // Export to PNG
/// exporter.write_fig(
/// Path::new("output"),
/// &plot,
/// ImageFormat::PNG,
/// 800,
/// 600,
/// 1.0
/// ).expect("Failed to export plot");
/// ```
///
/// # Features
///
/// - Supports multiple image formats (PNG, JPEG, WEBP, SVG, PDF)
/// - Uses headless browser for rendering
/// - Configurable dimensions and scale
/// - Offline mode support
/// - Automatic WebDriver management
pub struct StaticExporter {
/// WebDriver server port (default: 4444)
webdriver_port: u32,
/// WebDriver server base URL (default: "http://localhost")
webdriver_url: String,
/// WebDriver process manager for spawning and cleanup
webdriver: WebDriver,
/// Use bundled JS libraries instead of CDN
offline_mode: bool,
/// PDF export timeout in milliseconds
pdf_export_timeout: u32,
/// Browser command-line flags (e.g., "--headless", "--no-sandbox")
webdriver_browser_caps: Vec<String>,
/// Tokio runtime for async operations
runtime: std::sync::Arc<tokio::runtime::Runtime>,
/// Cached WebDriver client for session reuse
webdriver_client: Option<Client>,
}
impl Drop for StaticExporter {
/// Automatically cleans up WebDriver resources when the `StaticExporter`
/// instance is dropped.
///
/// This ensures that the WebDriver process is properly terminated and
/// resources are released, even if the instance goes out of scope
/// unexpectedly.
///
/// - Only terminates WebDriver processes that were spawned by this instance
/// - Leaves externally managed WebDriver sessions running
/// - Logs errors but doesn't panic if cleanup fails
fn drop(&mut self) {
// Close the WebDriver client if it exists
if let Some(client) = self.webdriver_client.take() {
let runtime = self.runtime.clone();
runtime.block_on(async {
if let Err(e) = client.close().await {
error!("Failed to close WebDriver client: {e}");
}
});
}
// Stop the WebDriver process
if let Err(e) = self.webdriver.stop() {
error!("Failed to stop WebDriver: {e}");
}
}
}
impl StaticExporter {
/// Exports a Plotly plot to a static image file.
///
/// This method renders the provided Plotly JSON plot using a headless
/// browser and saves the result as an image file in the specified
/// format.
///
/// Returns `Ok(())` on success, or an error if the export fails.
///
/// # Examples
///
/// ```no_run
/// // This example requires a running WebDriver (chromedriver/geckodriver) and a browser.
/// // It cannot be run as a doc test.
/// use plotly_static::{StaticExporterBuilder, ImageFormat};
/// use serde_json::json;
/// use std::path::Path;
///
/// let plot = json!({
/// "data": [{"type": "scatter", "x": [1,2,3], "y": [4,5,6]}],
/// "layout": {}
/// });
///
/// let mut exporter = StaticExporterBuilder::default().build().unwrap();
///
/// exporter.write_fig(
/// Path::new("my_plot"),
/// &plot,
/// ImageFormat::PNG,
/// 1200,
/// 800,
/// 2.0
/// ).expect("Failed to export plot");
/// // Creates "my_plot.png" with 1200x800 pixels at 2x scale
/// ```
///
/// # Notes
///
/// - The file extension is automatically added based on the format
/// - SVG format outputs plain text, others output binary data
/// - PDF format uses browser JavaScript for generation
pub fn write_fig(
&mut self,
dst: &Path,
plot: &serde_json::Value,
format: ImageFormat,
width: usize,
height: usize,
scale: f64,
) -> Result<(), Box<dyn std::error::Error>> {
let mut dst = PathBuf::from(dst);
dst.set_extension(format.to_string());
let plot_data = PlotData {
format: format.clone(),
width,
height,
scale,
data: plot,
};
let image_data = self.export(plot_data)?;
let data = match format {
ImageFormat::SVG => image_data.as_bytes(),
_ => &general_purpose::STANDARD.decode(image_data)?,
};
let mut file = File::create(dst.as_path())?;
file.write_all(data)?;
file.flush()?;
Ok(())
}
/// Exports a Plotly plot to a string representation.
///
/// This method renders the provided Plotly JSON plot and returns the result
/// as a string. The format of the string depends on the image format:
/// - SVG: Returns plain SVG text
/// - PNG/JPEG/WEBP/PDF: Returns base64-encoded data
///
/// Returns the image data as a string on success, or an error if the export
/// fails.
///
/// # Examples
///
/// ```no_run
/// // This example requires a running WebDriver (chromedriver/geckodriver) and a browser.
/// // It cannot be run as a doc test.
/// use plotly_static::{StaticExporterBuilder, ImageFormat};
/// use serde_json::json;
///
/// let plot = json!({
/// "data": [{"type": "scatter", "x": [1,2,3], "y": [4,5,6]}],
/// "layout": {}
/// });
///
/// let mut exporter = StaticExporterBuilder::default().build().unwrap();
///
/// let svg_data = exporter.write_to_string(
/// &plot,
/// ImageFormat::SVG,
/// 800,
/// 600,
/// 1.0
/// ).expect("Failed to export plot");
///
/// // svg_data contains the SVG markup as a string
/// assert!(svg_data.starts_with("<svg"));
/// ```
///
/// # Notes
///
/// - SVG format returns plain text that can be embedded in HTML
/// - Other formats return base64-encoded data that can be used in data URLs
/// - This method is useful when you need the image data as a string rather
/// than a file
pub fn write_to_string(
&mut self,
plot: &serde_json::Value,
format: ImageFormat,
width: usize,
height: usize,
scale: f64,
) -> Result<String, Box<dyn std::error::Error>> {
let plot_data = PlotData {
format,
width,
height,
scale,
data: plot,
};
let image_data = self.export(plot_data)?;
Ok(image_data)
}
/// Convert the Plotly graph to a static image using Kaleido and return the
/// result as a String
pub(crate) fn export(&mut self, plot: PlotData) -> Result<String> {
let data = self.static_export(&plot)?;
Ok(data)
}
fn static_export(&mut self, plot: &PlotData<'_>) -> Result<String> {
let html_content = template::get_html_body(self.offline_mode);
let runtime = self.runtime.clone();
runtime
.block_on(self.extract(&html_content, plot))
.with_context(|| "Failed to extract static image from browser session")
}
async fn extract(&mut self, html_content: &str, plot: &PlotData<'_>) -> Result<String> {
let caps = self.build_webdriver_caps()?;
debug!("Use WebDriver and headless browser to export static plot");
let webdriver_url = format!("{}:{}", self.webdriver_url, self.webdriver_port,);
// Reuse existing client or create new one
let client = if let Some(ref client) = self.webdriver_client {
debug!("Reusing existing WebDriver session");
client.clone()
} else {
debug!("Creating new WebDriver session");
let new_client = ClientBuilder::native()
.capabilities(caps)
.connect(&webdriver_url)
.await
.with_context(|| "WebDriver session error")?;
self.webdriver_client = Some(new_client.clone());
new_client
};
// For offline mode, write HTML to file to avoid data URI size limits since JS
// libraries are embedded in the file
let url = if self.offline_mode {
let temp_file = template::to_file(html_content)
.with_context(|| "Failed to create temporary HTML file")?;
format!("file://{}", temp_file.to_string_lossy())
} else {
// For online mode, use data URI (smaller size since JS is loaded from CDN)
format!("data:text/html,{}", encode(html_content))
};
// Open the HTML
client.goto(&url).await?;
let (js_script, args) = match plot.format {
ImageFormat::PDF => {
// Always use SVG for PDF export
let args = vec![
plot.data.clone(),
ImageFormat::SVG.to_string().into(),
plot.width.into(),
plot.height.into(),
plot.scale.into(),
];
(pdf_export_js_script(self.pdf_export_timeout), args)
}
_ => {
let args = vec![
plot.data.clone(),
plot.format.to_string().into(),
plot.width.into(),
plot.height.into(),
plot.scale.into(),
];
(image_export_js_script(), args)
}
};
let data = client.execute_async(&js_script, args).await?;
// Don't close the client - keep it for reuse
// client.close().await?;
let result = data.as_str().ok_or(anyhow!(
"Failed to execute Plotly.toImage in browser session"
))?;
if let Some(err) = result.strip_prefix("ERROR:") {
return Err(anyhow!("JavaScript error during export: {err}"));
}
match plot.format {
ImageFormat::SVG => Self::extract_plain(result, &plot.format),
ImageFormat::PNG | ImageFormat::JPEG | ImageFormat::WEBP | ImageFormat::PDF => {
Self::extract_encoded(result, &plot.format)
}
#[allow(deprecated)]
ImageFormat::EPS => {
error!("EPS format is deprecated. Use SVG or PDF instead.");
Self::extract_encoded(result, &plot.format)
}
}
}
fn extract_plain(payload: &str, format: &ImageFormat) -> Result<String> {
match payload.split_once(",") {
Some((type_info, data)) => {
Self::extract_type_info(type_info, format);
let decoded = urlencoding::decode(data)?;
Ok(decoded.to_string())
}
None => Err(anyhow!("'src' attribute has invalid {format} data")),
}
}
fn extract_encoded(payload: &str, format: &ImageFormat) -> Result<String> {
match payload.split_once(";") {
Some((type_info, encoded_data)) => {
Self::extract_type_info(type_info, format);
Self::extract_encoded_data(encoded_data)
.ok_or(anyhow!("No valid image data found in 'src' attribute"))
}
None => Err(anyhow!("'src' attribute has invalid base64 data")),
}