Skip to content

PDF Split — C# source

Split a PDF by page, chunk size, or custom ranges — entirely in your browser. Nothing uploads.

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

// pdf-split — split one PDF into many by page plan with PDFsharp.
//
// Language: C# (.NET 8), PDFsharp 6 (display-only — the PDFsharp API is
// called the way a real build would reference it; this snippet is never
// compiled against the package here)
// CosmoDev polyglot showcase port of the `pdf-split` tool.
// Ported from src/lib/pdf-split.ts — display source, part of CosmoDev's
// polyglot tool pages. Mirrors this dir's java.java structure 1:1.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;

namespace CosmoDev.PdfSplit;

/// <summary>Load failure kind: "encrypted" (password-protected) or "invalid" (unparseable).</summary>
public sealed class PdfToolError : Exception
{
    /// <summary>The TS union code: "encrypted" | "invalid".</summary>
    public string Code { get; }

    public PdfToolError(string code, string message)
        : base(message)
    {
        Code = code;
    }
}

/// <summary>Split output: the planned file name, its bytes, and its page count.</summary>
public sealed record SplitOutput(string Name, byte[] Bytes, int PageCount);

/// <summary>The C# twin of the TS pdf-split lib (all members static, like java.java).</summary>
public static class PdfSplitLib
{
    private static readonly Regex Chunk = new(@"^(\d+)/chunk$", RegexOptions.Compiled);
    private static readonly Regex Single = new(@"^\d+$", RegexOptions.Compiled);
    private static readonly Regex Span = new(@"^(\d+)-(\d+)$", RegexOptions.Compiled);

    /// <summary>Pure classifier — encrypted vs invalid, from the raw error message.</summary>
    internal static string ClassifyLoadError(string? message) =>
        message is not null && Regex.IsMatch(message, "encrypt|password", RegexOptions.IgnoreCase)
            ? "encrypted"
            : "invalid";

    /// <summary>Map a thrown load failure to a user-facing PdfToolError.</summary>
    internal static PdfToolError MapError(Exception e) =>
        ClassifyLoadError(e.Message) == "encrypted"
            ? new PdfToolError("encrypted", "This PDF is password-protected. Unlock it first.")
            : new PdfToolError("invalid", "Not a readable PDF file.");

    /// <summary>The inclusive 1-based range [a..b] (the TS range() helper).</summary>
    private static List<int> SpanRange(int a, int b)
    {
        var pages = new List<int>(b - a + 1);
        for (var p = a; p <= b; p++) pages.Add(p);
        return pages;
    }

    /// <summary>
    /// Pure planner — no PDFsharp on this path. Grammar (mirrors parsePageRanges
    /// in src/lib/pdf-split.ts):
    ///   'all'       -> [[1], [2], .., [pageCount]]
    ///   'N/chunk'   -> groups of N pages in order (last group may be short)
    ///   'a-b,c-d,e' -> [[a..b], [c..d], [e]] (1-based, inclusive)
    /// Throws PdfToolError code "invalid" on empty specs, unparseable tokens,
    /// descending ranges, and any page outside 1..pageCount.
    /// </summary>
    public static List<List<int>> ParsePageRanges(string spec, int pageCount)
    {
        var trimmed = spec.Trim();
        if (trimmed.Length == 0)
        {
            throw new PdfToolError("invalid", "Enter a page range first.");
        }

        if (trimmed == "all")
        {
            var groups = new List<List<int>>(pageCount);
            for (var p = 1; p <= pageCount; p++) groups.Add(new List<int> { p });
            return groups;
        }

        var chunk = Chunk.Match(trimmed);
        if (chunk.Success)
        {
            var size = int.Parse(chunk.Groups[1].Value);
            if (size < 1 || size > pageCount)
            {
                throw new PdfToolError("invalid", $"Chunk size must be between 1 and {pageCount}.");
            }
            var chunkGroups = new List<List<int>>();
            for (var start = 1; start <= pageCount; start += size)
            {
                chunkGroups.Add(SpanRange(start, Math.Min(start + size - 1, pageCount)));
            }
            return chunkGroups;
        }

        var groups = new List<List<int>>();
        foreach (var token in trimmed.Split(','))
        {
            var t = token.Trim();
            if (Single.IsMatch(t))
            {
                var page = int.Parse(t);
                if (page < 1 || page > pageCount)
                {
                    throw new PdfToolError("invalid", $"Page {page} is out of range (1–{pageCount}).");
                }
                groups.Add(new List<int> { page });
                continue;
            }
            var span = Span.Match(t);
            if (span.Success)
            {
                var a = int.Parse(span.Groups[1].Value);
                var b = int.Parse(span.Groups[2].Value);
                if (b < a)
                {
                    throw new PdfToolError("invalid", $"Range {a}-{b} descends — use a-b with a ≤ b.");
                }
                if (a < 1 || b > pageCount)
                {
                    throw new PdfToolError("invalid", $"Range {a}-{b} is out of range (1–{pageCount}).");
                }
                groups.Add(SpanRange(a, b));
                continue;
            }
            throw new PdfToolError("invalid", $"\"{t}\" is not a page, a-b range, \"all\", or \"N/chunk\".");
        }
        return groups;
    }

    /// <summary>
    /// Chunk-shaped = partition of 1..n into equal runs of >=2 pages (last may
    /// be short). Size-1 "chunks" are indistinguishable from 'all' — those stay
    /// page-N.
    /// </summary>
    private static bool ChunkShaped(IReadOnlyList<List<int>> groups)
    {
        if (groups.Count < 2) return false;
        var size = groups[0].Count;
        if (size < 2) return false;
        var next = 1;
        for (var i = 0; i < groups.Count; i++)
        {
            var g = groups[i];
            if (g[0] != next) return false;
            next = g[g.Count - 1] + 1;
            if (i < groups.Count - 1 && g.Count != size) return false;
            if (i == groups.Count - 1 && g.Count > size) return false;
        }
        return true;
    }

    /// <summary>
    /// Pure naming pass: single page -> 'page-N.pdf'; chunk-shaped plan ->
    /// 'chunk-K.pdf'; contiguous group -> 'pages-A-B.pdf'; else 'pages-A,B.pdf'.
    /// </summary>
    public static List<string> PlanNames(IReadOnlyList<List<int>> groups)
    {
        var chunk = ChunkShaped(groups);
        var names = new List<string>(groups.Count);
        for (var i = 0; i < groups.Count; i++)
        {
            var g = groups[i];
            if (chunk)
            {
                names.Add($"chunk-{i + 1}.pdf");
            }
            else if (g.Count == 1)
            {
                names.Add($"page-{g[0]}.pdf");
            }
            else if (g[g.Count - 1] - g[0] + 1 == g.Count)
            {
                names.Add($"pages-{g[0]}-{g[g.Count - 1]}.pdf");
            }
            else
            {
                names.Add("pages-" + string.Join(",", g) + ".pdf");
            }
        }
        return names;
    }

    /// <summary>
    /// One output PDF per group: the source is opened once with PDFsharp's
    /// PdfReader, then each planned page is cloned into a fresh PdfDocument
    /// and saved (the PDFsharp analogue of pdf-lib's copyPages). Mirrors
    /// splitPdf() in src/lib/pdf-split.ts.
    /// </summary>
    public static List<SplitOutput> SplitPdf(byte[] pdf, IReadOnlyList<List<int>> groups)
    {
        if (groups.Count == 0)
        {
            throw new PdfToolError("invalid", "Nothing to split — plan at least one page.");
        }
        try
        {
            using var src = PdfReader.Open(new MemoryStream(pdf), PdfDocumentOpenMode.Import);
            if (src.PageCount == 0)
            {
                throw new PdfToolError("invalid", "Not a readable PDF file.");
            }
            var total = src.PageCount;
            var names = PlanNames(groups);
            var outs = new List<SplitOutput>(groups.Count);
            for (var i = 0; i < groups.Count; i++)
            {
                foreach (var page in groups[i])
                {
                    if (page < 1 || page > total)
                    {
                        throw new PdfToolError("invalid", $"Page {page} is out of range (1–{total}).");
                    }
                }
                var outDoc = new PdfDocument();
                foreach (var page in groups[i])
                {
                    // AddPage deep-copies the imported page (Import mode).
                    outDoc.AddPage(src.Pages[page - 1]);
                }
                using var buffer = new MemoryStream();
                outDoc.Save(buffer);
                outs.Add(new SplitOutput(names[i], buffer.ToArray(), outDoc.PageCount));
            }
            return outs;
        }
        catch (PdfToolError)
        {
            throw;
        }
        catch (Exception e)
        {
            throw MapError(e);
        }
    }

    /// <summary>Page count for UI display — the C# twin of the TS countPages() helper.</summary>
    public static int CountPages(byte[] pdf)
    {
        try
        {
            using var doc = PdfReader.Open(new MemoryStream(pdf), PdfDocumentOpenMode.InformationOnly);
            return doc.PageCount;
        }
        catch (Exception e)
        {
            throw MapError(e);
        }
    }
}

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 →