Skip to content

PDF Merge — Rust source

Combine PDF files in order, entirely in your browser — reorder, merge, download. Nothing uploads.

This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.

//! pdf-merge — merge many PDFs into one with lopdf (crates.io).
//! Authored snippet mirroring src/lib/pdf-merge.ts: empty input rejected,
//! encrypted vs invalid classified from the raw load error, page count
//! returned for UI display. lopdf's Document::merge copies every page of
//! every input, in order, into one fresh document.
use std::fmt;

/// Load failure kind: Encrypted (password-protected) or Invalid (unparseable).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorKind {
    Encrypted,
    Invalid,
}

/// The Rust twin of the TS PdfToolError class.
#[derive(Debug)]
pub struct PdfToolError {
    pub kind: ErrorKind,
    pub message: String,
}

impl fmt::Display for PdfToolError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl std::error::Error for PdfToolError {}

/// Pure classifier — encrypted vs invalid, from the raw error message.
/// Same /encrypt|password/i heuristic the TS lib applies.
pub fn classify_load_error(msg: Option<&str>) -> ErrorKind {
    match msg {
        // std-only check: case-insensitive scan for the same two keywords the
        // TS regex /encrypt|password/i looks for (no regex crate needed).
        Some(m) => {
            let lower = m.to_ascii_lowercase();
            if lower.contains("encrypt") || lower.contains("password") {
                ErrorKind::Encrypted
            } else {
                ErrorKind::Invalid
            }
        }
        None => ErrorKind::Invalid,
    }
}

/// Map a raw lopdf load failure to a user-facing PdfToolError.
fn map_error(e: lopdf::Error) -> PdfToolError {
    let msg = e.to_string();
    match e {
        lopdf::Error::InvalidPassword => PdfToolError {
            kind: ErrorKind::Encrypted,
            message: "This PDF is password-protected. Unlock it first.".into(),
        },
        _ => {
            let kind = classify_load_error(Some(&msg));
            let message = if kind == ErrorKind::Encrypted {
                "This PDF is password-protected. Unlock it first.".into()
            } else {
                "Not a readable PDF file.".into()
            };
            PdfToolError { kind, message }
        }
    }
}

/// Merge result: output bytes plus the merged document's page count.
pub struct MergeResult {
    pub bytes: Vec<u8>,
    pub page_count: usize,
}

/// Copy every page of every input, in order, into one fresh PDF. Mirrors
/// mergePdfs() in src/lib/pdf-merge.ts.
pub fn merge_pdfs(docs: &[Vec<u8>]) -> Result<MergeResult, PdfToolError> {
    if docs.is_empty() {
        return Err(PdfToolError {
            kind: ErrorKind::Invalid,
            message: "Nothing to merge.".into(),
        });
    }
    let documents: Vec<lopdf::Document> = docs
        .iter()
        .map(|d| lopdf::Document::load_mem(d).map_err(map_error))
        .collect::<Result<_, _>>()?;
    let mut out = lopdf::Document::merge(documents).map_err(map_error)?;
    let page_count = out.get_pages().len();
    let mut bytes = Vec::new();
    out.save_to(&mut bytes).map_err(|e| {
        map_error(lopdf::Error::Syntax(format!("save failed: {e}").into()))
    })?;
    Ok(MergeResult { bytes, page_count })
}

/// Page count for UI display — the Rust twin of the TS countPages() helper.
pub fn count_pages(bytes: &[u8]) -> Result<usize, PdfToolError> {
    let doc = lopdf::Document::load_mem(bytes).map_err(map_error)?;
    Ok(doc.get_pages().len())
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →