// PDF 处理 - 绿色工具箱 // C# 5.0 语法。使用 PdfSharp 1.50(MIT 许可),构建后经 ILMerge 合并为单 exe // 功能:多个 PDF 合并为一个;一个 PDF 拆分为每页一个文件 using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Text; using System.Windows.Forms; using PdfSharp.Pdf; using PdfSharp.Pdf.IO; namespace GreenToolbox { public class PdfToolForm : Form { private static readonly Color COL_GREEN = Color.FromArgb(0, 145, 88); private static readonly Color COL_PANEL = Color.FromArgb(245, 249, 246); private static readonly Color COL_GRAY = Color.FromArgb(120, 130, 124); private ListView lv; private Button btnAdd, btnRemove, btnUp, btnDown, btnMerge, btnSplit, btnPickSplit; private Label lblStatus; private ProgressBar progress; public PdfToolForm() { InitUi(); } private void InitUi() { this.Text = "PDF 处理 - 绿色工具箱"; this.Font = new Font("Microsoft YaHei UI", 9.5f); this.BackColor = Color.White; this.ForeColor = Color.FromArgb(34, 40, 36); this.ClientSize = new Size(720, 540); this.MinimumSize = new Size(640, 500); this.AllowDrop = true; this.DragEnter += new DragEventHandler(OnDragEnter); this.DragDrop += new DragEventHandler(OnDragDrop); int x = 20, y = 16; Label l0 = new Label(); l0.Text = "合并:把多个 PDF 按顺序合成一个(可拖入排序)|拆分:把一个 PDF 每页导出为单独文件"; l0.AutoSize = true; l0.ForeColor = COL_GRAY; l0.Location = new Point(x, y); this.Controls.Add(l0); y += 30; lv = new ListView(); lv.Location = new Point(x, y); lv.Size = new Size(500, 330); lv.View = View.Details; lv.FullRowSelect = true; lv.HeaderStyle = ColumnHeaderStyle.Nonclickable; lv.Columns.Add("#", 34); lv.Columns.Add("文件", 320); lv.Columns.Add("页数", 60); lv.Columns.Add("大小", 80); this.Controls.Add(lv); btnAdd = MkBtn("添加 PDF", 530, y, 166, false, AddClick); btnRemove = MkBtn("移除选中", 530, y + 38, 166, false, RemoveClick); btnUp = MkBtn("上移", 530, y + 76, 80, false, UpClick); btnDown = MkBtn("下移", 616, y + 76, 80, false, DownClick); btnPickSplit = MkBtn("选择要拆分的 PDF…", 530, y + 114, 166, false, SplitPickClick); y += 344; btnMerge = new Button(); btnMerge.Text = "① 合并为一个 PDF"; btnMerge.Location = new Point(x, y); btnMerge.Size = new Size(200, 36); btnMerge.BackColor = COL_GREEN; btnMerge.ForeColor = Color.White; btnMerge.FlatStyle = FlatStyle.Flat; btnMerge.FlatAppearance.BorderSize = 0; btnMerge.Click += new EventHandler(MergeClick); this.Controls.Add(btnMerge); btnSplit = new Button(); btnSplit.Text = "② 拆分上方选中的 PDF"; btnSplit.Location = new Point(x + 216, y); btnSplit.Size = new Size(200, 36); btnSplit.FlatStyle = FlatStyle.Flat; btnSplit.FlatAppearance.BorderColor = COL_GREEN; btnSplit.ForeColor = Color.FromArgb(0, 110, 66); btnSplit.Click += new EventHandler(SplitClick); this.Controls.Add(btnSplit); y += 52; progress = new ProgressBar(); progress.Location = new Point(x, y); progress.Size = new Size(676, 8); this.Controls.Add(progress); y += 20; lblStatus = new Label(); lblStatus.Text = "纯本地处理,文件不上传。加密 PDF 需先解密(本工具不处理密码)。"; lblStatus.Location = new Point(x, y); lblStatus.AutoSize = true; lblStatus.ForeColor = COL_GRAY; this.Controls.Add(lblStatus); } private Button MkBtn(string text, int px, int py, int w, bool primary, EventHandler onClick) { Button b = new Button(); b.Text = text; b.Location = new Point(px, py); b.Size = new Size(w, 30); b.FlatStyle = FlatStyle.Flat; if (primary) { b.BackColor = COL_GREEN; b.ForeColor = Color.White; b.FlatAppearance.BorderSize = 0; } else { b.FlatAppearance.BorderColor = COL_GREEN; b.ForeColor = Color.FromArgb(0, 110, 66); } b.Click += onClick; this.Controls.Add(b); return b; } private void OnDragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; } private void OnDragDrop(object sender, DragEventArgs e) { string[] f = (string[])e.Data.GetData(DataFormats.FileDrop); if (f != null) AddFiles(f); } private void AddClick(object sender, EventArgs e) { using (OpenFileDialog d = new OpenFileDialog()) { d.Filter = "PDF 文件 (*.pdf)|*.pdf"; d.Multiselect = true; d.Title = "选择要合并的 PDF(顺序=列表顺序)"; if (d.ShowDialog() == DialogResult.OK) AddFiles(d.FileNames); } } private void AddFiles(string[] paths) { foreach (string p in paths) { if (!File.Exists(p) || !p.ToLower().EndsWith(".pdf")) continue; try { PdfDocument doc = PdfReader.Open(p, PdfDocumentOpenMode.InformationOnly); ListViewItem it = new ListViewItem((lv.Items.Count + 1).ToString()); it.SubItems.Add(Path.GetFileName(p)); it.SubItems.Add(doc.PageCount.ToString()); it.SubItems.Add(Kb(new FileInfo(p).Length)); it.Tag = p; it.ToolTipText = p; lv.Items.Add(it); } catch (Exception ex) { lblStatus.Text = Path.GetFileName(p) + " 无法读取(可能已加密):" + ex.Message; } } } private void RemoveClick(object sender, EventArgs e) { foreach (ListViewItem it in lv.SelectedItems) lv.Items.Remove(it); Renumber(); } private void UpClick(object sender, EventArgs e) { if (lv.SelectedItems.Count == 0) return; ListViewItem it = lv.SelectedItems[0]; int i = it.Index; if (i > 0) { lv.Items.RemoveAt(i); lv.Items.Insert(i - 1, it); Renumber(); } } private void DownClick(object sender, EventArgs e) { if (lv.SelectedItems.Count == 0) return; ListViewItem it = lv.SelectedItems[0]; int i = it.Index; if (i < lv.Items.Count - 1) { lv.Items.RemoveAt(i); lv.Items.Insert(i + 1, it); Renumber(); } } private void Renumber() { for (int i = 0; i < lv.Items.Count; i++) lv.Items[i].Text = (i + 1).ToString(); } private void MergeClick(object sender, EventArgs e) { if (lv.Items.Count < 2) { lblStatus.Text = "请先添加至少 2 个 PDF。"; return; } using (SaveFileDialog d = new SaveFileDialog()) { d.Filter = "PDF 文件 (*.pdf)|*.pdf"; d.FileName = "合并结果.pdf"; if (d.ShowDialog() != DialogResult.OK) return; try { PdfDocument outDoc = new PdfDocument(); foreach (ListViewItem it in lv.Items) { PdfDocument src = PdfReader.Open((string)it.Tag, PdfDocumentOpenMode.Import); for (int i = 0; i < src.PageCount; i++) outDoc.AddPage(src.Pages[i]); } outDoc.Save(d.FileName); lblStatus.Text = "合并完成:" + d.FileName; } catch (Exception ex) { lblStatus.Text = "合并失败:" + ex.Message; } } } private string splitSource = ""; private void SplitPickClick(object sender, EventArgs e) { using (OpenFileDialog d = new OpenFileDialog()) { d.Filter = "PDF 文件 (*.pdf)|*.pdf"; d.Title = "选择要拆分的 PDF"; if (d.ShowDialog() == DialogResult.OK) { splitSource = d.FileName; lblStatus.Text = "已选择:" + Path.GetFileName(d.FileName) + ",点\"拆分\"执行。"; } } } private void SplitClick(object sender, EventArgs e) { string src = splitSource; if (src.Length == 0 && lv.SelectedItems.Count > 0) src = (string)lv.SelectedItems[0].Tag; if (src.Length == 0) { lblStatus.Text = "先选择要拆分的 PDF。"; return; } using (FolderBrowserDialog d = new FolderBrowserDialog()) { d.Description = "选择输出文件夹(每页生成一个 PDF)"; if (d.ShowDialog() != DialogResult.OK) return; try { PdfDocument doc = PdfReader.Open(src, PdfDocumentOpenMode.Import); string baseName = Path.GetFileNameWithoutExtension(src); int n = doc.PageCount; for (int i = 0; i < n; i++) { PdfDocument one = new PdfDocument(); one.AddPage(doc.Pages[i]); one.Save(Path.Combine(d.SelectedPath, baseName + "_p" + (i + 1).ToString("D3") + ".pdf")); } lblStatus.Text = "拆分完成:" + n + " 个文件在 " + d.SelectedPath; } catch (Exception ex) { lblStatus.Text = "拆分失败:" + ex.Message; } } } private string Kb(long b) { return (b / 1024.0).ToString("0.#") + " KB"; } } // 命令行自测:A(3 页) + B(2 页) → 合并成 5 页 → 逐页拆开 → 断言页数、页面尺寸、产物可再打开 public static class SelfTest { private static int _pass = 0; private static int _fail = 0; private static List _lines = new List(); private static void Check(string name, string got, string want) { if (got == want) { _pass++; _lines.Add(" [ok] " + name); } else { _fail++; _lines.Add(" [!!] " + name + " 期望[" + want + "] 实际[" + got + "]"); } } private static void CheckInt(string name, int got, int want) { Check(name, got.ToString(), want.ToString()); } // 造一个 n 页的 PDF,每页中间写「第 i 页」,页宽留出差异方便验证搬页没搬错 private static string MakePdf(string path, int pages, double widthPt) { PdfDocument doc = new PdfDocument(); for (int i = 1; i <= pages; i++) { PdfPage page = doc.AddPage(); page.Width = PdfSharp.Drawing.XUnit.FromPoint(widthPt); page.Height = PdfSharp.Drawing.XUnit.FromPoint(842); using (PdfSharp.Drawing.XGraphics g = PdfSharp.Drawing.XGraphics.FromPdfPage(page)) { PdfSharp.Drawing.XFont font = new PdfSharp.Drawing.XFont("Arial", 24); g.DrawString("Page " + i + " of " + pages, font, PdfSharp.Drawing.XBrushes.Black, new PdfSharp.Drawing.XPoint(60, 200)); } } doc.Save(path); return path; } public static int Run(string dir) { if (string.IsNullOrEmpty(dir)) dir = Path.Combine(Path.GetTempPath(), "greentool-pdf-selftest"); try { if (Directory.Exists(dir)) { try { Directory.Delete(dir, true); } catch { } } Directory.CreateDirectory(dir); _lines.Add("PDF 处理 自测(" + dir + ")"); string aPath = MakePdf(Path.Combine(dir, "a.pdf"), 3, 595); string bPath = MakePdf(Path.Combine(dir, "b.pdf"), 2, 612); Check("造好 3 页的 a.pdf", File.Exists(aPath) ? "在" : "不在", "在"); Check("造好 2 页的 b.pdf", File.Exists(bPath) ? "在" : "不在", "在"); // ── 合并 ── PdfDocument merged = new PdfDocument(); PdfDocument a = PdfReader.Open(aPath, PdfDocumentOpenMode.Import); PdfDocument b = PdfReader.Open(bPath, PdfDocumentOpenMode.Import); CheckInt("读进来的 a.pdf 是 3 页", a.PageCount, 3); CheckInt("读进来的 b.pdf 是 2 页", b.PageCount, 2); for (int i = 0; i < a.PageCount; i++) merged.AddPage(a.Pages[i]); for (int i = 0; i < b.PageCount; i++) merged.AddPage(b.Pages[i]); CheckInt("内存里合并后 5 页", merged.PageCount, 5); string mergedPath = Path.Combine(dir, "merged.pdf"); merged.Save(mergedPath); merged.Close(); Check("合并结果写了盘", new FileInfo(mergedPath).Length > 1000 ? "合理" : "太小", "合理"); // ── 重新打开校验:这一步最容易暴露「引用没跟着搬」的坏 PDF ── PdfDocument m2 = PdfReader.Open(mergedPath, PdfDocumentOpenMode.Import); CheckInt("重新打开 merged.pdf 仍是 5 页", m2.PageCount, 5); Check("第 1 页保留 a 的页宽 595", Math.Round(m2.Pages[0].Width.Point).ToString(), "595"); Check("第 4 页是 b 的第 1 页(宽 612)", Math.Round(m2.Pages[3].Width.Point).ToString(), "612"); Check("第 5 页是 b 的第 2 页(宽 612)", Math.Round(m2.Pages[4].Width.Point).ToString(), "612"); // ── 逐页拆开 ── string splitDir = Path.Combine(dir, "split"); Directory.CreateDirectory(splitDir); int bugs = 0; for (int i = 0; i < m2.PageCount; i++) { PdfDocument one = new PdfDocument(); one.AddPage(m2.Pages[i]); string p = Path.Combine(splitDir, "p" + (i + 1) + ".pdf"); one.Save(p); one.Close(); PdfDocument chk = PdfReader.Open(p, PdfDocumentOpenMode.InformationOnly); if (chk.PageCount != 1) bugs++; chk.Close(); } CheckInt("拆出 5 个单页文件", Directory.GetFiles(splitDir, "*.pdf").Length, 5); CheckInt("每个拆出来的文件都是 1 页", bugs, 0); m2.Close(); // ── 极端输入不炸:0 页不存在,但空文件必须报错而不是静默成功 ── string empty = Path.Combine(dir, "empty.pdf"); File.WriteAllBytes(empty, new byte[0]); bool threw = false; try { PdfDocument bad = PdfReader.Open(empty, PdfDocumentOpenMode.Import); bad.Close(); } catch { threw = true; } Check("空文件打开会抛异常(不静默当成功)", threw ? "抛了" : "没抛", "抛了"); } catch (Exception ex) { _fail++; _lines.Add(" [!!] 自测中途异常:" + ex.GetType().Name + " " + ex.Message); } _lines.Add(""); if (_fail == 0) _lines.Add("结果:共 " + (_pass + _fail) + " 项,全部通过 ✓"); else _lines.Add("结果:共 " + (_pass + _fail) + " 项,通过 " + _pass + ",失败 " + _fail + " ✗"); string all = string.Join("\r\n", _lines.ToArray()); try { File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "selftest-pdf.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } } static class Program { [STAThread] static void Main(string[] args) { // 自测:PdfTool.exe --selftest [工作目录] (退出码 0 全过 / 1 有失败) if (args != null && args.Length >= 1 && args[0] == "--selftest") { Environment.Exit(SelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new PdfToolForm()); } // 命令行自测:现场造 3 页 + 2 页两个 PDF → 合并 → 拆页 → 断言页数与页面尺寸 public static int RunSelfTest(string dir) { return SelfTest.Run(dir); } } }