// PDF 加页码水印 - 绿色工具箱 // C# 5.0 语法。使用 PdfSharp 1.50(MIT 许可),构建后经 ILMerge 合并为单 exe // 功能:给 PDF 每页加页码(位置/格式/起始号可调,首页可跳过);可选叠加文字水印(居中倾斜或平铺) using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Text; using System.Windows.Forms; using PdfSharp.Drawing; using PdfSharp.Pdf; using PdfSharp.Pdf.IO; namespace GreenToolbox { public class PdfStampForm : 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 TextBox txtFile; private ComboBox cmbPos, cmbFmt, cmbFont, cmbWmColor; private TextBox txtTpl, txtWm; private NumericUpDown numStart, numSize, numWmSize; private CheckBox chkSkipFirst, chkTile, chkTilt, chkWm; private Button btnPick, btnGo; private ProgressBar progress; private Label lblStatus; private List files = new List(); public PdfStampForm() { 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(760, 520); this.MinimumSize = new Size(700, 500); this.AllowDrop = true; this.DragEnter += new DragEventHandler(OnDragEnter); this.DragDrop += new DragEventHandler(OnDragDrop); int x = 16, y = 14; 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 += 28; txtFile = new TextBox(); txtFile.Location = new Point(x, y); txtFile.Size = new Size(600, 26); txtFile.ReadOnly = true; txtFile.BackColor = COL_PANEL; this.Controls.Add(txtFile); btnPick = MkBtn("选择 PDF…", x + 610, y - 2, 118, false, PickClick); y += 40; // === 页码 === GroupBox g1 = new GroupBox(); g1.Text = "页码"; g1.Location = new Point(x, y); g1.Size = new Size(728, 176); g1.ForeColor = Color.FromArgb(34, 40, 36); this.Controls.Add(g1); int gx = 16, gy = 30; Label la = new Label(); la.Text = "位置"; la.AutoSize = true; la.ForeColor = COL_GRAY; la.Location = new Point(gx, gy + 4); g1.Controls.Add(la); cmbPos = new ComboBox(); cmbPos.DropDownStyle = ComboBoxStyle.DropDownList; cmbPos.Items.Add("页脚 · 居中"); cmbPos.Items.Add("页脚 · 靠右"); cmbPos.Items.Add("页脚 · 靠左"); cmbPos.Items.Add("页眉 · 居中"); cmbPos.Items.Add("页眉 · 靠右"); cmbPos.SelectedIndex = 0; cmbPos.Location = new Point(gx + 44, gy); cmbPos.Size = new Size(140, 26); g1.Controls.Add(cmbPos); Label lb = new Label(); lb.Text = "格式"; lb.AutoSize = true; lb.ForeColor = COL_GRAY; lb.Location = new Point(gx + 204, gy + 4); g1.Controls.Add(lb); cmbFmt = new ComboBox(); cmbFmt.DropDownStyle = ComboBoxStyle.DropDownList; cmbFmt.Items.Add("第 {page} 页 / 共 {total} 页"); cmbFmt.Items.Add("{page} / {total}"); cmbFmt.Items.Add("- {page} -"); cmbFmt.Items.Add("第 {page} 页"); cmbFmt.Items.Add("{page}"); cmbFmt.Items.Add("自定义(在下面填)"); cmbFmt.SelectedIndex = 0; cmbFmt.Location = new Point(gx + 248, gy); cmbFmt.Size = new Size(200, 26); cmbFmt.SelectedIndexChanged += new EventHandler(FmtChange); g1.Controls.Add(cmbFmt); txtTpl = new TextBox(); txtTpl.Location = new Point(gx + 460, gy); txtTpl.Size = new Size(240, 26); txtTpl.Text = "第 {page} 页 / 共 {total} 页"; txtTpl.Enabled = false; g1.Controls.Add(txtTpl); gy += 42; Label lc = new Label(); lc.Text = "字体"; lc.AutoSize = true; lc.ForeColor = COL_GRAY; lc.Location = new Point(gx, gy + 4); g1.Controls.Add(lc); cmbFont = new ComboBox(); cmbFont.DropDownStyle = ComboBoxStyle.DropDownList; cmbFont.Items.Add("黑体(最清楚)"); cmbFont.Items.Add("仿宋"); cmbFont.Items.Add("楷体"); cmbFont.Items.Add("等线"); cmbFont.Items.Add("Arial(纯数字)"); cmbFont.SelectedIndex = 0; cmbFont.Location = new Point(gx + 44, gy); cmbFont.Size = new Size(140, 26); g1.Controls.Add(cmbFont); Label ld = new Label(); ld.Text = "字号"; ld.AutoSize = true; ld.ForeColor = COL_GRAY; ld.Location = new Point(gx + 204, gy + 4); g1.Controls.Add(ld); numSize = new NumericUpDown(); numSize.Minimum = 6; numSize.Maximum = 24; numSize.Value = 9; numSize.Location = new Point(gx + 248, gy); numSize.Size = new Size(56, 26); g1.Controls.Add(numSize); Label le = new Label(); le.Text = "起始页码"; le.AutoSize = true; le.ForeColor = COL_GRAY; le.Location = new Point(gx + 320, gy + 4); g1.Controls.Add(le); numStart = new NumericUpDown(); numStart.Minimum = 0; numStart.Maximum = 9999; numStart.Value = 1; numStart.Location = new Point(gx + 396, gy); numStart.Size = new Size(64, 26); g1.Controls.Add(numStart); chkSkipFirst = new CheckBox(); chkSkipFirst.Text = "首页不加页码(封面、目录)"; chkSkipFirst.AutoSize = true; chkSkipFirst.Location = new Point(gx + 480, gy + 2); g1.Controls.Add(chkSkipFirst); gy += 46; Label lf = new Label(); lf.Text = "提示:页码写在页面边缘的空白处,不改动原有内容;扫描件、图片型 PDF 同样适用。"; lf.AutoSize = true; lf.ForeColor = COL_GRAY; lf.Location = new Point(gx, gy); g1.Controls.Add(lf); y += 190; // === 水印 === GroupBox g2 = new GroupBox(); g2.Text = "文字水印(可选)"; g2.Location = new Point(x, y); g2.Size = new Size(728, 130); g2.ForeColor = Color.FromArgb(34, 40, 36); this.Controls.Add(g2); int wx = 16, wy = 30; chkWm = new CheckBox(); chkWm.Text = "启用水印"; chkWm.AutoSize = true; chkWm.Location = new Point(wx, wy + 2); chkWm.CheckedChanged += new EventHandler(WmToggle); g2.Controls.Add(chkWm); txtWm = new TextBox(); txtWm.Location = new Point(wx + 100, wy); txtWm.Size = new Size(196, 26); txtWm.Text = "内部资料"; txtWm.Enabled = false; g2.Controls.Add(txtWm); Label lw2 = new Label(); lw2.Text = "字号"; lw2.AutoSize = true; lw2.ForeColor = COL_GRAY; lw2.Location = new Point(wx + 310, wy + 4); g2.Controls.Add(lw2); numWmSize = new NumericUpDown(); numWmSize.Minimum = 10; numWmSize.Maximum = 160; numWmSize.Value = 48; numWmSize.Location = new Point(wx + 354, wy); numWmSize.Size = new Size(64, 26); numWmSize.Enabled = false; g2.Controls.Add(numWmSize); Label lw3 = new Label(); lw3.Text = "颜色"; lw3.AutoSize = true; lw3.ForeColor = COL_GRAY; lw3.Location = new Point(wx + 428, wy + 4); g2.Controls.Add(lw3); cmbWmColor = new ComboBox(); cmbWmColor.DropDownStyle = ComboBoxStyle.DropDownList; cmbWmColor.Items.Add("浅灰"); cmbWmColor.Items.Add("淡红"); cmbWmColor.Items.Add("淡蓝"); cmbWmColor.Items.Add("深灰"); cmbWmColor.SelectedIndex = 0; cmbWmColor.Location = new Point(wx + 468, wy); cmbWmColor.Size = new Size(90, 26); cmbWmColor.Enabled = false; g2.Controls.Add(cmbWmColor); wy += 42; chkTilt = new CheckBox(); chkTilt.Text = "倾斜 45°"; chkTilt.AutoSize = true; chkTilt.Location = new Point(wx + 100, wy); chkTilt.Checked = true; chkTilt.Enabled = false; g2.Controls.Add(chkTilt); chkTile = new CheckBox(); chkTile.Text = "整页平铺(防截图盗用)"; chkTile.AutoSize = true; chkTile.Location = new Point(wx + 206, wy); chkTile.Enabled = false; g2.Controls.Add(chkTile); y += 144; btnGo = new Button(); btnGo.Text = "开始处理"; btnGo.Location = new Point(x, y); btnGo.Size = new Size(200, 38); btnGo.BackColor = COL_GREEN; btnGo.ForeColor = Color.White; btnGo.FlatStyle = FlatStyle.Flat; btnGo.FlatAppearance.BorderSize = 0; btnGo.Click += new EventHandler(GoClick); this.Controls.Add(btnGo); progress = new ProgressBar(); progress.Location = new Point(x + 216, y + 8); progress.Size = new Size(512, 22); this.Controls.Add(progress); y += 48; lblStatus = new Label(); lblStatus.Text = "纯本地处理,文件不上传、不联网。"; 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) SetFiles(f); } private void PickClick(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) SetFiles(d.FileNames); } } private void SetFiles(string[] paths) { files.Clear(); foreach (string p in paths) if (File.Exists(p) && p.ToLower().EndsWith(".pdf")) files.Add(p); if (files.Count == 0) { txtFile.Text = ""; return; } if (files.Count == 1) { FileInfo fi = new FileInfo(files[0]); txtFile.Text = files[0] + " (" + Pages(files[0]) + " 页," + (fi.Length / 1024.0).ToString("0.#") + " KB)"; } else { int total = 0; foreach (string f in files) total += Pages(f); txtFile.Text = "已选 " + files.Count + " 个 PDF,共 " + total + " 页"; } } private int Pages(string p) { try { PdfDocument d = PdfReader.Open(p, PdfDocumentOpenMode.InformationOnly); return d.PageCount; } catch { return 0; } } private void FmtChange(object sender, EventArgs e) { txtTpl.Enabled = cmbFmt.SelectedIndex == 5; string[] presets = { "第 {page} 页 / 共 {total} 页", "{page} / {total}", "- {page} -", "第 {page} 页", "{page}" }; if (cmbFmt.SelectedIndex < 5) txtTpl.Text = presets[cmbFmt.SelectedIndex]; } private void WmToggle(object sender, EventArgs e) { bool on = chkWm.Checked; txtWm.Enabled = on; numWmSize.Enabled = on; cmbWmColor.Enabled = on; chkTilt.Enabled = on; chkTile.Enabled = on; } private string FontName() { switch (cmbFont.SelectedIndex) { case 1: return "FangSong"; case 2: return "KaiTi"; case 3: return "DengXian"; case 4: return "Arial"; default: return "SimHei"; } } private XColor WmColor() { switch (cmbWmColor.SelectedIndex) { case 1: return XColor.FromArgb(255, 235, 200, 200); case 2: return XColor.FromArgb(255, 200, 218, 240); case 3: return XColor.FromArgb(255, 150, 150, 150); default: return XColor.FromArgb(255, 208, 208, 208); } } private void GoClick(object sender, EventArgs e) { if (files.Count == 0) { lblStatus.Text = "先选择一个 PDF(也可以直接把文件拖进窗口)。"; return; } if (chkWm.Checked && txtWm.Text.Trim().Length == 0) { lblStatus.Text = "启用了水印但没填水印文字。"; return; } btnGo.Enabled = false; progress.Maximum = files.Count; progress.Value = 0; int okCount = 0; StringBuilder errs = new StringBuilder(); foreach (string f in files) { try { string outPath = TargetPath(f); Stamp(f, outPath); okCount++; lblStatus.Text = "完成:" + Path.GetFileName(outPath); } catch (Exception ex) { errs.Append(Path.GetFileName(f) + ":" + ex.Message + " "); lblStatus.Text = "跳过 " + Path.GetFileName(f) + "(" + ex.Message + ")"; } progress.Value = progress.Value + 1; Application.DoEvents(); } btnGo.Enabled = true; if (errs.Length > 0) lblStatus.Text = "完成 " + okCount + "/" + files.Count + "。失败:" + errs.ToString(); else lblStatus.Text = "全部完成:" + okCount + " 个文件,结果在同目录。"; if (okCount > 0 && MessageBox.Show("处理完成,要打开输出文件夹看一眼吗?", "完成", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { try { System.Diagnostics.Process.Start("explorer.exe", "/select,\"" + TargetPath(files[0]) + "\""); } catch { } } } private string TargetPath(string src) { string dir = Path.GetDirectoryName(src); string name = Path.GetFileNameWithoutExtension(src) + "_已标注.pdf"; string p = Path.Combine(dir, name); int n = 2; while (File.Exists(p)) { p = Path.Combine(dir, Path.GetFileNameWithoutExtension(src) + "_已标注(" + n + ").pdf"); n++; } return p; } // 自测用:一次性把界面选项设好,绕开手工点控件 public void SetForTest(int pos, bool skipFirst, int start, string tpl, bool wm, string wmText, bool tiled, bool tilt) { cmbFmt.SelectedIndex = 5; // 自定义模板 txtTpl.Text = tpl; cmbPos.SelectedIndex = pos; numStart.Value = start; chkSkipFirst.Checked = skipFirst; chkWm.Checked = wm; txtWm.Text = wmText; chkTile.Checked = tiled; chkTilt.Checked = tilt; WmToggle(null, null); } public void StampForTest(string srcPath, string outPath) { Stamp(srcPath, outPath); } private void Stamp(string srcPath, string outPath) { PdfDocument doc = PdfReader.Open(srcPath, PdfDocumentOpenMode.Modify); int total = doc.PageCount; if (total == 0) throw new Exception("这个 PDF 没有页面"); int start = (int)numStart.Value; int lastNumber = start + total - 1; double fontSize = (double)numSize.Value; string tpl = txtTpl.Text.Length > 0 ? txtTpl.Text : "第 {page} 页 / 共 {total} 页"; if (tpl.IndexOf("{page}") < 0) tpl = tpl + " {page}"; XFont numFont = MakeFont(FontName(), fontSize); XFont wmFont = MakeFont(FontName(), (double)numWmSize.Value); for (int i = 0; i < total; i++) { PdfPage page = doc.Pages[i]; bool isFirst = (i == 0); using (XGraphics g = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append)) { double pw = page.Width.Point; double ph = page.Height.Point; if (chkWm.Checked && txtWm.Text.Trim().Length > 0) DrawWatermark(g, wmFont, txtWm.Text.Trim(), pw, ph); if (!(isFirst && chkSkipFirst.Checked)) { int num = start + i; string t = tpl.Replace("{page}", num.ToString()) .Replace("{total}", lastNumber.ToString()); XSize sz = g.MeasureString(t, numFont); double margin = 26 + fontSize; double px, py; switch (cmbPos.SelectedIndex) { case 1: px = pw - 36 - sz.Width; py = ph - margin; break; // 页脚靠右 case 2: px = 36; py = ph - margin; break; // 页脚靠左 case 3: px = (pw - sz.Width) / 2; py = margin; break; // 页眉居中 case 4: px = pw - 36 - sz.Width; py = margin; break; // 页眉靠右 default: px = (pw - sz.Width) / 2; py = ph - margin; break; // 页脚居中 } g.DrawString(t, numFont, XBrushes.Black, px, py); } } } doc.Save(outPath); doc.Close(); } private XFont MakeFont(string family, double size) { string[] cands = new string[] { family, "SimHei", "Arial" }; Exception last = null; foreach (string c in cands) { try { return new XFont(c, size, XFontStyle.Regular, new XPdfFontOptions(PdfFontEncoding.Unicode)); } catch (Exception ex) { last = ex; } } throw new Exception("找不到可用字体(已试 " + string.Join(", ", cands) + "):" + (last != null ? last.Message : "")); } private void DrawWatermark(XGraphics g, XFont f, string text, double pw, double ph) { XBrush br; try { br = new XSolidBrush(WmColor()); } catch { br = new XSolidBrush(XColor.FromArgb(255, 208, 208, 208)); } XSize sz = g.MeasureString(text, f); double angle = chkTilt.Checked ? 45.0 : 0.0; if (chkTile.Checked) { double stepX = sz.Width + 60; double stepY = sz.Height + 90; int cols = (int)Math.Ceiling(pw / stepX) + 2; int rows = (int)Math.Ceiling(ph / stepY) + 2; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { double cx = c * stepX + (r % 2 == 0 ? 0 : stepX / 2) - stepX; double cy = r * stepY - stepY / 2; DrawRotated(g, f, br, text, sz, cx, cy, angle); } } } else { DrawRotated(g, f, br, text, sz, (pw - sz.Width) / 2, (ph - sz.Height) / 2, angle); } } private void DrawRotated(XGraphics g, XFont f, XBrush br, string text, XSize sz, double px, double py, double angle) { XGraphicsState st = g.Save(); try { // 绕文字中心旋转 g.TranslateTransform(px + sz.Width / 2, py + sz.Height / 2); g.RotateTransform(-angle); g.DrawString(text, f, br, -sz.Width / 2, -sz.Height / 2, XStringFormats.Default); } finally { g.Restore(st); } } } // 命令行自测:造 3 页 PDF → 分别跑「只加页码 / 跳过首页 / 平铺水印 / 起始号 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()); } private static void CheckTrue(string name, bool ok) { Check(name, ok ? "是" : "否", "是"); } private static void MakePdf(string path, int pages) { PdfDocument doc = new PdfDocument(); for (int i = 1; i <= pages; i++) { PdfPage p = doc.AddPage(); p.Width = XUnit.FromPoint(595); p.Height = XUnit.FromPoint(842); using (XGraphics g = XGraphics.FromPdfPage(p)) { XFont f = new XFont("Arial", 12); g.DrawString("original page " + i, f, XBrushes.Black, 60, 100); } } doc.Save(path); doc.Close(); } // 把一页的内容流拼成字符串(已解 Flate)。读不到就返回空串 private static string ContentOf(PdfPage page) { StringBuilder sb = new StringBuilder(); try { var contents = page.Contents; int n = contents.Elements.Count; for (int i = 0; i < n; i++) { PdfDictionary d = contents.Elements.GetDictionary(i); if (d == null || d.Stream == null) continue; byte[] body; try { body = d.Stream.UnfilteredValue; } catch { body = d.Stream.Value; } if (body == null) continue; sb.Append(Encoding.GetEncoding(28591).GetString(body)); } } catch { } return sb.ToString(); } // 内容流里显示文字的算子个数(Tj / TJ)。数字变了字数不变,所以用它判「有没有多画东西」 private static int TextOps(string content) { int n = 0, i = 0; while ((i = content.IndexOf("Tj", i, StringComparison.Ordinal)) >= 0) { n++; i += 2; } i = 0; while ((i = content.IndexOf("TJ", i, StringComparison.Ordinal)) >= 0) { n++; i += 2; } return n; } private class Snap { public int Pages; public string[] Size; public string[] Content; public int[] Ops; } private static Snap Read(string path) { Snap s = new Snap(); PdfDocument doc = PdfReader.Open(path, PdfDocumentOpenMode.Modify); s.Pages = doc.PageCount; s.Size = new string[doc.PageCount]; s.Content = new string[doc.PageCount]; s.Ops = new int[doc.PageCount]; for (int i = 0; i < doc.PageCount; i++) { PdfPage p = doc.Pages[i]; s.Size[i] = Math.Round(p.Width.Point) + "x" + Math.Round(p.Height.Point); s.Content[i] = ContentOf(p); s.Ops[i] = TextOps(s.Content[i]); } doc.Close(); return s; } public static int Run(string dir) { if (string.IsNullOrEmpty(dir)) dir = Path.Combine(Path.GetTempPath(), "greentool-pdfstamp-selftest"); try { if (Directory.Exists(dir)) { try { Directory.Delete(dir, true); } catch { } } Directory.CreateDirectory(dir); _lines.Add("PDF 加页码水印 自测(" + dir + ")"); string src = Path.Combine(dir, "src.pdf"); MakePdf(src, 3); Snap orig = Read(src); CheckInt("造好 3 页的样本", orig.Pages, 3); CheckTrue("样本每页本来就有文字(基准不为 0)", orig.Ops[0] > 0 && orig.Ops[1] > 0); PdfStampForm f = new PdfStampForm(); // ① 只加页码:页脚居中,起始 1 string p1 = Path.Combine(dir, "num_only.pdf"); f.SetForTest(0, false, 1, "第 {page} 页 / 共 {total} 页", false, "", false, false); f.StampForTest(src, p1); CheckTrue("只加页码:产出文件", File.Exists(p1)); Snap r1 = Read(p1); CheckInt("只加页码:页数不变", r1.Pages, 3); Check("只加页码:第 1 页尺寸不变(595x842)", r1.Size[0], "595x842"); Check("只加页码:第 3 页尺寸不变(595x842)", r1.Size[2], "595x842"); CheckTrue("只加页码:第 1 页多画了文字", r1.Ops[0] > orig.Ops[0]); CheckTrue("只加页码:第 2 页多画了文字", r1.Ops[1] > orig.Ops[1]); CheckTrue("只加页码:第 3 页多画了文字", r1.Ops[2] > orig.Ops[2]); CheckTrue("只加页码:各页内容不相同(页号确实变了)", r1.Content[0] != r1.Content[1] && r1.Content[1] != r1.Content[2]); // ② 跳过首页 string p2 = Path.Combine(dir, "skip_first.pdf"); f.SetForTest(0, true, 1, "第 {page} 页 / 共 {total} 页", false, "", false, false); f.StampForTest(src, p2); Snap r2 = Read(p2); int grow1 = r2.Content[0].Length - orig.Content[0].Length; int grow2 = r2.Content[1].Length - orig.Content[1].Length; CheckTrue("跳过首页:第 1 页内容几乎没变(增量 ≤ 32 字节,实测 " + grow1 + ")", grow1 <= 32); CheckTrue("跳过首页:第 2 页照样加页码(增量 " + grow2 + " 字节)", grow2 > 40); CheckTrue("跳过首页:两页内容确实不同", r2.Content[0] != r2.Content[1]); // ③ 平铺水印:同一个词要重复画很多次 string p3 = Path.Combine(dir, "tiled.pdf"); f.SetForTest(0, false, 1, "{page}", true, "内部资料", true, false); f.StampForTest(src, p3); Snap r3 = Read(p3); CheckTrue("平铺水印:第 1 页文字次数明显多于只加页码(" + r3.Ops[0] + " > " + r1.Ops[0] + ")", r3.Ops[0] > r1.Ops[0] + 4); CheckTrue("平铺水印:比第 2 页也多(两页瓦数一致)", r3.Ops[1] > r1.Ops[1] + 4); // ④ 居中单条水印:只多一个词,不该像平铺那样铺满 string p4 = Path.Combine(dir, "center_wm.pdf"); f.SetForTest(0, false, 1, "{page}", true, "内部资料", false, true); f.StampForTest(src, p4); Snap r4 = Read(p4); CheckTrue("居中水印:文字次数远少于平铺(" + r4.Ops[0] + " < " + r3.Ops[0] + ")", r4.Ops[0] < r3.Ops[0]); // ⑤ 起始页码 5:画出来的字不一样,内容流必须与起始 1 不同 string p5 = Path.Combine(dir, "start5.pdf"); f.SetForTest(0, false, 5, "第 {page} 页 / 共 {total} 页", false, "", false, false); f.StampForTest(src, p5); Snap r5 = Read(p5); CheckTrue("起始页码 5:第 1 页内容与起始 1 不同", r5.Content[0] != r1.Content[0]); CheckTrue("起始页码 5:页数仍是 3", r5.Pages == 3); // ⑥ 原文件必须没被就地改 Snap again = Read(src); CheckTrue("源文件没被就地改掉", again.Content[0] == orig.Content[0] && again.Ops[0] == orig.Ops[0]); // ⑦ 不存在的文件要报错,不能静默成功 bool threw = false; try { f.StampForTest(Path.Combine(dir, "nofile.pdf"), Path.Combine(dir, "x.pdf")); } catch { threw = true; } CheckTrue("文件不存在会报错", 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()); Console.WriteLine(all); try { File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "selftest-pdfstamp.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } } static class Program { [STAThread] static void Main(string[] args) { // 自测:PdfStamp.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 PdfStampForm()); } // 自测:现场造 3 页 PDF → 跑加页码/水印 → 重新打开核对页数、页面尺寸、内容流变化与报错 public static int RunSelfTest(string dir) { return SelfTest.Run(dir); } } }