libreoffice_convert_rust 0.1.0

A Rust library for converting documents using LibreOffice
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
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
//! # LibreOffice Convert Rust
//!
//! 一个用于将文档转换为各种格式的 Rust 库,基于 LibreOffice。
//!
//! ## 功能特性
//!
//! - 支持多种文档格式转换(如 docx → pdf)
//! - 自动检测 LibreOffice 安装路径
//! - 支持自定义转换选项
//! - 异步 API 设计
//! - 完善的错误处理
//!
//! ## 快速开始
//!
//! ```no_run
//! use libreoffice_convert_rust::{convert, ConvertOptions};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // 读取文档
//!     let document = std::fs::read("document.docx")?;
//!     
//!     // 转换为 PDF
//!     let pdf_data = convert(&document, "pdf", None).await?;
//!     
//!     // 保存结果
//!     std::fs::write("output.pdf", pdf_data)?;
//!     
//!     Ok(())
//! }
//! ```
//!
//! ## 使用自定义选项
//!
//! ```no_run
//! use libreoffice_convert_rust::{convert_with_options, ConvertOptions};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let document = std::fs::read("document.docx")?;
//!     
//!     let options = ConvertOptions {
//!         async_times: 5,
//!         async_interval: 300,
//!         tmp_prefix: Some("my_convert_".to_string()),
//!         soffice_binary_paths: Some(vec![
//!             "/custom/path/to/soffice".to_string()
//!         ]),
//!     };
//!     
//!     let pdf_data = convert_with_options(
//!         &document,
//!         "pdf",
//!         None,
//!         options
//!     ).await?;
//!     
//!     Ok(())
//! }
//! ```

use std::env;
use std::path::Path;
use std::process::Stdio;
use tempfile::TempDir;
use tokio::fs::{self, File};
use tokio::io::AsyncWriteExt;
use tokio::process::Command;
use url::Url;

mod error;
pub use error::{ConvertError, ConvertResult};

/// 转换选项配置
///
/// 用于自定义 LibreOffice 文档转换行为。
///
/// # 字段说明
///
/// - `async_times`: 读取输出文件时的最大重试次数
/// - `async_interval`: 重试之间的等待时间(毫秒)
/// - `tmp_prefix`: 临时目录的前缀
/// - `soffice_binary_paths`: 自定义的 LibreOffice 可执行文件路径列表
/// - `input_format`: 输入文件的格式/扩展名(如 "docx", "xlsx", "odt" 等)
#[derive(Debug, Clone)]
pub struct ConvertOptions {
    /// 读取输出文件时的最大重试次数
    pub async_times: u32,
    /// 重试之间的等待时间(毫秒)
    pub async_interval: u64,
    /// 临时目录的前缀
    pub tmp_prefix: Option<String>,
    /// 自定义的 LibreOffice 可执行文件路径列表
    pub soffice_binary_paths: Option<Vec<String>>,
    /// 输入文件的格式/扩展名(如 "docx", "xlsx", "odt" 等)
    pub input_format: Option<String>,
}

impl Default for ConvertOptions {
    fn default() -> Self {
        Self {
            async_times: 3,
            async_interval: 200,
            tmp_prefix: Some("libreoffice_convert_".to_string()),
            soffice_binary_paths: None,
            input_format: None,
        }
    }
}

impl ConvertOptions {
    /// 创建默认的转换选项
    pub fn new() -> Self {
        Self::default()
    }

    /// 设置最大重试次数
    pub fn with_async_times(mut self, times: u32) -> Self {
        self.async_times = times;
        self
    }

    /// 设置重试间隔(毫秒)
    pub fn with_async_interval(mut self, interval_ms: u64) -> Self {
        self.async_interval = interval_ms;
        self
    }

    /// 设置临时目录前缀
    pub fn with_tmp_prefix<S: Into<String>>(mut self, prefix: S) -> Self {
        self.tmp_prefix = Some(prefix.into());
        self
    }

    /// 设置自定义 LibreOffice 路径
    pub fn with_soffice_paths(mut self, paths: Vec<String>) -> Self {
        self.soffice_binary_paths = Some(paths);
        self
    }

    /// 添加一个 LibreOffice 路径
    pub fn add_soffice_path<S: Into<String>>(mut self, path: S) -> Self {
        let mut paths = self.soffice_binary_paths.unwrap_or_default();
        paths.push(path.into());
        self.soffice_binary_paths = Some(paths);
        self
    }

    /// 设置输入文件格式
    pub fn with_input_format<S: Into<String>>(mut self, format: S) -> Self {
        self.input_format = Some(format.into());
        self
    }
}

/// 检查文件扩展名是否为图像格式
fn is_image_file(path: &str) -> bool {
    let path_lower = path.to_lowercase();
    let image_extensions = [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff", ".tif", 
        ".svg", ".webp", ".ico", ".raw", ".cr2", ".nef", ".arw"
    ];
    
    image_extensions.iter().any(|ext| path_lower.ends_with(ext))
}

/// 查找 LibreOffice 可执行文件路径
///
/// 此函数会按以下顺序搜索:
/// 1. 用户提供的自定义路径
/// 2. 系统环境变量 `LIBRE_OFFICE_EXE`
/// 3. 操作系统特定的默认安装路径
///
/// # 错误
///
/// 如果找不到 LibreOffice 可执行文件,返回 `ConvertError::SofficeNotFound`
///
/// # 示例
///
/// ```no_run
/// use libreoffice_convert_rust::find_soffice;
///
/// let path = find_soffice(&Default::default()).unwrap();
/// println!("Found LibreOffice at: {}", path);
/// ```
pub fn find_soffice(options: &ConvertOptions) -> ConvertResult<String> {
    let mut paths = options.soffice_binary_paths.clone().unwrap_or_default();
    // 添加环境变量中的路径
    if let Ok(lo_exe) = env::var("LIBRE_OFFICE_EXE") {
        paths.push(lo_exe);
    }


    // 根据操作系统添加默认路径
    #[cfg(target_os = "macos")]
    {
        paths.extend(vec![
            "/Applications/LibreOffice.app/Contents/MacOS/soffice".to_string(),
            "/Applications/LibreOffice.app/Contents/MacOS/soffice.bin".to_string(),
        ]);
    }

    #[cfg(target_os = "linux")]
    {
        paths.extend(vec![
            "/usr/bin/libreoffice".to_string(),
            "/usr/bin/soffice".to_string(),
            "/snap/bin/libreoffice".to_string(),
            "/opt/libreoffice/program/soffice".to_string(),
            "/usr/local/lib/libreoffice/program/soffice".to_string(),
        ]);
    }

    #[cfg(windows)]
    {
        let program_files = env::var("PROGRAMFILES")
            .unwrap_or_else(|_| "C:\\Program Files".to_string());
        let program_files_x86 = env::var("PROGRAMFILES(X86)")
            .or_else(|_| env::var("PROGRAMFILES_X86"))
            .unwrap_or_else(|_| "C:\\Program Files (x86)".to_string());
        let local_app_data = env::var("LOCALAPPDATA")
            .unwrap_or_else(|_| "C:\\Users\\Public\\AppData\\Local".to_string());

        paths.extend(vec![
            format!("{}\\LibreOffice\\program\\soffice.exe", program_files),
            format!("{}\\LibreOffice\\program\\soffice.exe", program_files_x86),
            "C:\\Program Files\\LibreOffice\\program\\soffice.exe".to_string(),
            "C:\\Program Files (x86)\\LibreOffice\\program\\soffice.exe".to_string(),
            format!("{}\\Programs\\soffice.exe", local_app_data),
        ]);
    }

    // 检查每个路径
    for path in paths {
        if Path::new(&path).exists() {
            return Ok(path);
        }
    }

    Err(ConvertError::SofficeNotFound)
}

/// 使用自定义选项进行文档转换
///
/// # 参数
///
/// - `document`: 文档的二进制数据
/// - `format`: 目标格式(如 "pdf", "docx", "txt" 等)
/// - `filter`: 可选的转换过滤器名称
/// - `options`: 转换选项配置
///
/// # 返回
///
/// 返回转换后的文档二进制数据
///
/// # 错误
///
/// 如果转换过程中出现任何错误,返回 `ConvertError`
///
/// # 示例
///
/// ```no_run
/// use libreoffice_convert_rust::{convert_with_options, ConvertOptions};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let doc = std::fs::read("input.docx")?;
///     
///     let options = ConvertOptions::new()
///         .with_async_times(5)
///         .with_async_interval(300);
///     
///     let pdf = convert_with_options(&doc, "pdf", None, options).await?;
///     
///     Ok(())
/// }
/// ```
pub async fn convert_with_options(
    document: &[u8],
    format: &str,
    filter: Option<&str>,
    options: ConvertOptions,
) -> ConvertResult<Vec<u8>> {
    // 验证输入
    if document.is_empty() {
        return Err(ConvertError::InvalidInput("Document data is empty".to_string()));
    }

    if format.is_empty() {
        return Err(ConvertError::InvalidInput("Format is empty".to_string()));
    }

    // 1. 创建临时目录
    let temp_dir = TempDir::with_prefix(
        options.tmp_prefix.as_deref().unwrap_or("libreoffice_convert_")
    ).map_err(|e| ConvertError::TempDirCreationFailed(e.to_string()))?;
    
    let install_dir = TempDir::with_prefix("soffice_user_profile_")
        .map_err(|e| ConvertError::TempDirCreationFailed(e.to_string()))?;

    // 2. 查找 soffice
    let soffice_path = find_soffice(&options)?;

    // 3. 准备文件名和路径
    // 使用输入格式或默认为 .docx
    let input_format = options.input_format.as_deref().unwrap_or("docx");
    let file_name = format!("source.{}", input_format);
    let input_path = temp_dir.path().join(&file_name);
    
    // 保存源文件
    let mut source_file = File::create(&input_path).await
        .map_err(|e| ConvertError::FileWriteFailed(e.to_string()))?;
    
    source_file.write_all(document).await
        .map_err(|e| ConvertError::FileWriteFailed(e.to_string()))?;
    
    source_file.flush().await
        .map_err(|e| ConvertError::FileWriteFailed(e.to_string()))?;

    // 4. 构建命令参数
    let user_install_url = Url::from_directory_path(install_dir.path())
        .map_err(|_| ConvertError::InvalidPath("Invalid path for URL conversion".to_string()))?;
    
    // 处理 format 和 filter 参数
    let filter_param = filter.map(|f| format!(":{}", f)).unwrap_or_default();
    
    let fmt_str = if filter.map(|f| f.contains(' ')).unwrap_or(false) {
        format!("\"{}{}\"", format, filter_param)
    } else {
        format!("{}{}", format, filter_param)
    };

    // 执行转换命令
    // 将路径转换为字符串格式,确保正确处理
    let input_path_str = input_path.to_string_lossy().to_string();
    let output_dir_str = temp_dir.path().to_string_lossy().to_string();
    
    let output = Command::new(&soffice_path)
        .arg(format!("-env:UserInstallation={}", user_install_url))
        .arg("--headless")
        .arg("--convert-to")
        .arg(&fmt_str)
        .arg("--outdir")
        .arg(&output_dir_str)
        .arg(&input_path_str)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .await
        .map_err(|e| ConvertError::ProcessExecutionFailed(e.to_string()))?;

    // 检查执行结果
    let stderr = String::from_utf8_lossy(&output.stderr);
    
    // 只在退出码非零时才视为错误
    if !output.status.success() {
        return Err(ConvertError::ProcessFailed {
            code: output.status.code(),
            stderr: stderr.to_string(),
        });
    }

    // 5. 读取结果文件(带重试逻辑)
    // LibreOffice 会在输出目录创建相同名称但扩展名不同的文件
    // 文件名是 source,输出扩展名由 format 决定
    let output_path = temp_dir.path().join(format!("source.{}", format.split(':').next().unwrap_or(format)));
    
    let mut retry_count = 0;
    let max_times = options.async_times;
    let interval_ms = options.async_interval;

    let buffer = loop {
        match fs::read(&output_path).await {
            Ok(buf) => break buf,
            Err(e) if retry_count < max_times => {
                retry_count += 1;
                tokio::time::sleep(tokio::time::Duration::from_millis(interval_ms)).await;
            }
            Err(e) => {
                return Err(ConvertError::FileReadFailed(
                    format!("Failed to read output file after {} retries: {}", retry_count, e)
                ));
            }
        }
    };

    Ok(buffer)
}

/// 简化的文档转换函数(使用默认选项)
///
/// # 参数
///
/// - `document`: 文档的二进制数据
/// - `format`: 目标格式(如 "pdf", "docx", "txt" 等)
/// - `filter`: 可选的转换过滤器名称
///
/// # 返回
///
/// 返回转换后的文档二进制数据
///
/// # 示例
///
/// ```no_run
/// use libreoffice_convert_rust::convert;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let doc = std::fs::read("input.docx")?;
///     let pdf = convert(&doc, "pdf", None).await?;
///     Ok(())
/// }
/// ```
pub async fn convert(
    document: &[u8],
    format: &str,
    filter: Option<&str>,
) -> ConvertResult<Vec<u8>> {
    convert_with_options(document, format, filter, ConvertOptions::default()).await
}

/// 将文件转换为另一种格式
///
/// # 参数
///
/// - `input_path`: 输入文件路径
/// - `output_path`: 输出文件路径
/// - `format`: 目标格式
/// - `filter`: 可选的转换过滤器名称
///
/// # 返回
///
/// 成功时返回 `Ok(())`
///
/// # 示例
///
/// ```no_run
/// use libreoffice_convert_rust::convert_file;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     convert_file("input.docx", "output.pdf", "pdf", None).await?;
///     Ok(())
/// }
/// ```
pub async fn convert_file(
    input_path: &str,
    output_path: &str,
    format: &str,
    filter: Option<&str>,
) -> ConvertResult<()> {
    // 检查是否为图像文件
    if is_image_file(input_path) {
        return Err(ConvertError::InvalidInput(format!(
            "Image conversion is not supported. Cannot convert '{}' to '{}'.\n\n\
             This tool uses LibreOffice's --convert-to command which is designed for document formats \
             (like .docx, .xlsx, .pptx, .odt, etc.), not for image files.\n\n\
             For converting images to PDF, consider using:\n\
             - ImageMagick: magick input.png output.pdf\n\
             - ImageMagick: convert input.png output.pdf\n\
             - Online tools or dedicated image-to-PDF converters\n\
             - LibreOffice Draw (manually open image and export as PDF)",
            input_path, format
        )));
    }
    
    let document = fs::read(input_path).await
        .map_err(|e| ConvertError::FileReadFailed(e.to_string()))?;
    
    // 提取输入文件扩展名
    let input_ext = Path::new(input_path)
        .extension()
        .and_then(|ext| ext.to_str())
        .unwrap_or("docx");
    
    let options = ConvertOptions::default()
        .with_input_format(input_ext);
    
    let result = convert_with_options(&document, format, filter, options).await?;
    
    fs::write(output_path, result).await
        .map_err(|e| ConvertError::FileWriteFailed(e.to_string()))?;
    
    Ok(())
}

/// 使用自定义选项将文件转换为另一种格式
pub async fn convert_file_with_options(
    input_path: &str,
    output_path: &str,
    format: &str,
    filter: Option<&str>,
    mut options: ConvertOptions,
) -> ConvertResult<()> {
    // 检查是否为图像文件
    if is_image_file(input_path) {
        return Err(ConvertError::InvalidInput(format!(
            "Image conversion is not supported. Cannot convert '{}' to '{}'.\n\n\
             This tool uses LibreOffice's --convert-to command which is designed for document formats \
             (like .docx, .xlsx, .pptx, .odt, etc.), not for image files.\n\n\
             For converting images to PDF, consider using:\n\
             - ImageMagick: magick input.png output.pdf\n\
             - ImageMagick: convert input.png output.pdf\n\
             - Online tools or dedicated image-to-PDF converters\n\
             - LibreOffice Draw (manually open image and export as PDF)",
            input_path, format
        )));
    }
    
    let document = fs::read(input_path).await
        .map_err(|e| ConvertError::FileReadFailed(e.to_string()))?;
    
    // 如果用户没有指定输入格式,则从文件扩展名推断
    if options.input_format.is_none() {
        let input_ext = Path::new(input_path)
            .extension()
            .and_then(|ext| ext.to_str())
            .unwrap_or("docx");
        options.input_format = Some(input_ext.to_string());
    }
    
    let result = convert_with_options(&document, format, filter, options).await?;
    
    fs::write(output_path, result).await
        .map_err(|e| ConvertError::FileWriteFailed(e.to_string()))?;
    
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_convert_options_default() {
        let options = ConvertOptions::default();
        assert_eq!(options.async_times, 3);
        assert_eq!(options.async_interval, 200);
    }

    #[test]
    fn test_convert_options_builder() {
        let options = ConvertOptions::new()
            .with_async_times(5)
            .with_async_interval(300)
            .with_tmp_prefix("test_");
        
        assert_eq!(options.async_times, 5);
        assert_eq!(options.async_interval, 300);
        assert_eq!(options.tmp_prefix, Some("test_".to_string()));
    }

    #[test]
    fn test_find_soffice() {
        let options = ConvertOptions::default();
        // 这个测试可能失败,取决于系统上是否安装了 LibreOffice
        let result = find_soffice(&options);
        println!("find_soffice result: {:?}", result);
    }
}