// 图片转 PDF - 绿色工具箱 // C# 5.0 语法。使用 PdfSharp 1.50(MIT 许可),构建后经 ILMerge 合并为单 exe // 功能:把多张图片按顺序合成一个 PDF。A4 自动横竖 / 与图片同大小两种页面, // 可调页边距,超大图可选先缩小以减小 PDF 体积。 using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Text; using System.Windows.Forms; using PdfSharp; using PdfSharp.Drawing; using PdfSharp.Pdf; using PdfSharp.Pdf.Advanced; using PdfSharp.Pdf.IO; namespace GreenToolbox { public class ImgToPdfForm : 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 ComboBox cmbPage, cmbMargin; private CheckBox chkShrink; private TextBox txtOut; private Button btnGo; private Label lblStatus; public ImgToPdfForm() { 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, 620); this.MinimumSize = new Size(660, 560); this.AllowDrop = true; this.DragEnter += new DragEventHandler(OnDragEnter); this.DragDrop += new DragEventHandler(OnDragDrop); int x = 20, y = 14; Label l0 = new Label(); l0.Text = "把多张图片按下面的顺序合成一个 PDF(扫描件、截图、照片都能用)"; l0.AutoSize = true; l0.ForeColor = COL_GRAY; l0.Location = new Point(x, y); this.Controls.Add(l0); y += 28; Button btnAdd = Flat("添加图片…", new Point(x, y), new Size(96, 28), true); btnAdd.Click += new EventHandler(AddClick); this.Controls.Add(btnAdd); Button btnAddDir = Flat("整个文件夹", new Point(122, y), new Size(96, 28), false); btnAddDir.Click += new EventHandler(AddDirClick); this.Controls.Add(btnAddDir); Button btnSort = Flat("按名称排序", new Point(224, y), new Size(96, 28), false); btnSort.Click += new EventHandler(SortClick); this.Controls.Add(btnSort); Button btnUp = Flat("上移", new Point(326, y), new Size(60, 28), false); btnUp.Click += new EventHandler(UpClick); this.Controls.Add(btnUp); Button btnDown = Flat("下移", new Point(392, y), new Size(60, 28), false); btnDown.Click += new EventHandler(DownClick); this.Controls.Add(btnDown); Button btnDel = Flat("移除", new Point(458, y), new Size(60, 28), false); btnDel.Click += new EventHandler(DelClick); this.Controls.Add(btnDel); Button btnClear = Flat("清空", new Point(524, y), new Size(60, 28), false); btnClear.Click += new EventHandler(ClearClick); this.Controls.Add(btnClear); y += 42; lv = new ListView(); lv.View = View.Details; lv.FullRowSelect = true; lv.MultiSelect = true; lv.HideSelection = false; lv.Location = new Point(x, y); lv.Size = new Size(680, 280); lv.Columns.Add("#", 34); lv.Columns.Add("文件名", 330); lv.Columns.Add("尺寸(像素)", 150); lv.Columns.Add("大小", 130); lv.AllowDrop = true; lv.DragEnter += new DragEventHandler(OnDragEnter); lv.DragDrop += new DragEventHandler(OnDragDrop); this.Controls.Add(lv); y += 292; Label lp = new Label(); lp.Text = "页面:"; lp.AutoSize = true; lp.Location = new Point(x, y + 5); this.Controls.Add(lp); cmbPage = new ComboBox(); cmbPage.DropDownStyle = ComboBoxStyle.DropDownList; cmbPage.Location = new Point(x + 48, y + 1); cmbPage.Size = new Size(230, 26); cmbPage.Items.AddRange(new object[] { "A4(横图自动横向),图片完整放进页面", "与图片一样大(不缩放不加边)" }); cmbPage.SelectedIndex = 0; this.Controls.Add(cmbPage); Label lm = new Label(); lm.Text = "页边距:"; lm.AutoSize = true; lm.Location = new Point(x + 300, y + 5); this.Controls.Add(lm); cmbMargin = new ComboBox(); cmbMargin.DropDownStyle = ComboBoxStyle.DropDownList; cmbMargin.Location = new Point(x + 362, y + 1); cmbMargin.Size = new Size(90, 26); cmbMargin.Items.AddRange(new object[] { "10 毫米", "0", "5 毫米", "20 毫米" }); cmbMargin.SelectedIndex = 0; this.Controls.Add(cmbMargin); chkShrink = new CheckBox(); chkShrink.Text = "超大图先缩小(宽或高超 3000 像素缩到 3000,PDF 体积小很多,屏幕上看不出差别)"; chkShrink.Location = new Point(x, y + 36); chkShrink.AutoSize = true; chkShrink.Checked = true; this.Controls.Add(chkShrink); y += 72; Label lo = new Label(); lo.Text = "保存到:"; lo.AutoSize = true; lo.Location = new Point(x, y + 5); this.Controls.Add(lo); txtOut = new TextBox(); txtOut.Location = new Point(x + 62, y + 1); txtOut.Size = new Size(520, 26); this.Controls.Add(txtOut); Button btnOut = Flat("浏览…", new Point(590, y), new Size(70, 27), false); btnOut.Click += new EventHandler(OutClick); this.Controls.Add(btnOut); y += 44; btnGo = new Button(); btnGo.Text = "生成 PDF"; btnGo.Location = new Point(x, y); btnGo.Size = new Size(140, 36); btnGo.BackColor = COL_GREEN; btnGo.ForeColor = Color.White; btnGo.FlatStyle = FlatStyle.Flat; btnGo.FlatAppearance.BorderSize = 0; btnGo.Font = new Font("Microsoft YaHei UI", 10f, FontStyle.Bold); btnGo.Click += new EventHandler(GoClick); this.Controls.Add(btnGo); 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 Flat(string text, Point loc, Size sz, bool primary) { Button b = new Button(); b.Text = text; b.Location = loc; b.Size = sz; b.FlatStyle = FlatStyle.Flat; b.FlatAppearance.BorderColor = primary ? COL_GREEN : Color.FromArgb(200, 210, 204); b.ForeColor = primary ? Color.White : Color.FromArgb(50, 58, 54); if (primary) b.BackColor = COL_GREEN; 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 || f.Length == 0) return; List imgs = new List(); foreach (string p in f) { if (Directory.Exists(p)) imgs.AddRange(ImagesIn(p, false)); else if (IsImg(p)) imgs.Add(p); } AddFiles(imgs); } private void AddClick(object sender, EventArgs e) { using (OpenFileDialog d = new OpenFileDialog()) { d.Filter = "图片|*.jpg;*.jpeg;*.png;*.bmp;*.gif;*.tif;*.tiff|所有文件|*.*"; d.Title = "选择图片(可多选,按住 Ctrl)"; d.Multiselect = true; if (d.ShowDialog() == DialogResult.OK) AddFiles(new List(d.FileNames)); } } private void AddDirClick(object sender, EventArgs e) { using (FolderBrowserDialog d = new FolderBrowserDialog()) { d.Description = "选择图片文件夹(只取这一层,按文件名排序加入)"; if (d.ShowDialog() == DialogResult.OK) AddFiles(ImagesIn(d.SelectedPath, false)); } } private void SortClick(object sender, EventArgs e) { List cur = Paths(); cur.Sort(new NaturalNameComparer()); Reload(cur); } private void UpClick(object sender, EventArgs e) { if (lv.SelectedIndices.Count == 0) return; int first = lv.SelectedIndices[0]; if (first == 0) return; List cur = Paths(); List sel = new List(); foreach (int i in lv.SelectedIndices) sel.Add(i); foreach (int i in sel) { string t = cur[i - 1]; cur[i - 1] = cur[i]; cur[i] = t; } Reload(cur); foreach (int i in sel) if (i - 1 >= 0) lv.Items[i - 1].Selected = true; } private void DownClick(object sender, EventArgs e) { if (lv.SelectedIndices.Count == 0) return; int last = lv.SelectedIndices[lv.SelectedIndices.Count - 1]; if (last == lv.Items.Count - 1) return; List cur = Paths(); List sel = new List(); foreach (int i in lv.SelectedIndices) sel.Add(i); sel.Reverse(); foreach (int i in sel) { string t = cur[i + 1]; cur[i + 1] = cur[i]; cur[i] = t; } Reload(cur); foreach (int i in sel) if (i + 1 < lv.Items.Count) lv.Items[i + 1].Selected = true; } private void DelClick(object sender, EventArgs e) { List cur = Paths(); List sel = new List(); foreach (int i in lv.SelectedIndices) sel.Add(i); sel.Sort(); for (int i = sel.Count - 1; i >= 0; i--) cur.RemoveAt(sel[i]); Reload(cur); } private void ClearClick(object sender, EventArgs e) { lv.Items.Clear(); } // ---------------------------------------------------------------- 数据 private static bool IsImg(string p) { string e = Path.GetExtension(p).ToLower(); return e == ".jpg" || e == ".jpeg" || e == ".png" || e == ".bmp" || e == ".gif" || e == ".tif" || e == ".tiff"; } private static List ImagesIn(string dir, bool sub) { List r = new List(); if (!Directory.Exists(dir)) return r; foreach (string f in Directory.GetFiles(dir)) if (IsImg(f)) r.Add(f); r.Sort(new NaturalNameComparer()); return r; } private List Paths() { List r = new List(); foreach (ListViewItem it in lv.Items) r.Add((string)it.Tag); return r; } private void AddFiles(List files) { List cur = Paths(); foreach (string f in files) if (IsImg(f) && !cur.Contains(f)) cur.Add(f); Reload(cur); } private void Reload(List files) { lv.BeginUpdate(); lv.Items.Clear(); foreach (string f in files) { ListViewItem it = new ListViewItem((lv.Items.Count + 1).ToString()); it.Tag = f; it.SubItems.Add(Path.GetFileName(f)); try { using (Image img = Image.FromFile(f)) { it.SubItems.Add(img.Width + " × " + img.Height); it.SubItems.Add(Kb(new FileInfo(f).Length)); } } catch { it.SubItems.Add("打不开"); it.SubItems.Add("-"); it.ForeColor = Color.Firebrick; } lv.Items.Add(it); } ReNumber(); lv.EndUpdate(); } private void ReNumber() { for (int i = 0; i < lv.Items.Count; i++) lv.Items[i].Text = (i + 1).ToString(); } private static string Kb(long b) { if (b >= 1024 * 1024) return (b / 1024.0 / 1024.0).ToString("0.##") + " MB"; return (b / 1024.0).ToString("0.#") + " KB"; } private void OutClick(object sender, EventArgs e) { using (SaveFileDialog d = new SaveFileDialog()) { d.Filter = "PDF 文件|*.pdf"; d.FileName = "图片合并.pdf"; if (d.ShowDialog() == DialogResult.OK) txtOut.Text = d.FileName; } } // ---------------------------------------------------------------- 生成 private void GoClick(object sender, EventArgs e) { if (lv.Items.Count == 0) { lblStatus.Text = "先添加图片。"; return; } if (txtOut.Text.Trim().Length == 0) { lblStatus.Text = "先选保存位置。"; return; } btnGo.Enabled = false; lblStatus.Text = "正在生成…"; this.Cursor = Cursors.WaitCursor; try { int n = Build(Paths(), txtOut.Text.Trim(), cmbPage.SelectedIndex, MarginMm(cmbMargin.SelectedIndex), chkShrink.Checked); FileInfo fi = new FileInfo(txtOut.Text.Trim()); lblStatus.Text = "完成:共 " + n + " 页,文件 " + Kb(fi.Length) + " → " + fi.FullName; } catch (Exception ex) { lblStatus.Text = "生成失败:" + ex.Message; } this.Cursor = Cursors.Default; btnGo.Enabled = true; } private static double MarginMm(int idx) { // 与界面选项对应:0=10mm 1=0 2=5mm 3=20mm if (idx == 1) return 0; if (idx == 2) return 5; if (idx == 3) return 20; return 10.0; } // 生成核心(自测与界面共用):mode 0=A4 自适应,1=与图片同大小 public static int Build(List files, string outPath, int mode, double marginMm, bool shrink) { PdfDocument doc = new PdfDocument(); doc.Info.Title = Path.GetFileNameWithoutExtension(outPath); doc.Info.Creator = "绿色工具箱"; string tmpDir = Path.Combine(Path.GetTempPath(), "GreenToolBox_img2pdf"); Directory.CreateDirectory(tmpDir); int done = 0; foreach (string f in files) { // PdfSharp 只能从文件/流读图:先把 EXIF 摆正、可选缩小的图存成临时 JPG string tmpFile = Path.Combine(tmpDir, "p" + done + ".jpg"); SavePrepared(f, tmpFile, shrink); using (XImage ximg = XImage.FromFile(tmpFile)) { PdfPage page = doc.AddPage(); if (mode == 1) { // 与图片同大小:1 像素 = 1 点(96dpi 习惯下与屏幕显示接近) page.Width = ximg.PixelWidth * 72.0 / 96.0; page.Height = ximg.PixelHeight * 72.0 / 96.0; using (XGraphics g = XGraphics.FromPdfPage(page)) { g.DrawImage(ximg, 0, 0, page.Width.Point, page.Height.Point); } } else { bool wide = ximg.PixelWidth > ximg.PixelHeight; page.Size = PageSize.A4; page.Orientation = wide ? PageOrientation.Landscape : PageOrientation.Portrait; double pw = page.Width.Point, ph = page.Height.Point; double m = marginMm * 72.0 / 25.4; double bw = pw - m * 2, bh = ph - m * 2; double s = Math.Min(bw / ximg.PixelWidth, bh / ximg.PixelHeight); double dw = ximg.PixelWidth * s, dh = ximg.PixelHeight * s; double dx = (pw - dw) / 2.0, dy = (ph - dh) / 2.0; using (XGraphics g = XGraphics.FromPdfPage(page)) { g.DrawImage(ximg, dx, dy, dw, dh); } } } try { File.Delete(tmpFile); } catch { } done++; } doc.Save(outPath); try { Directory.Delete(tmpDir, true); } catch { } return done; } private static readonly ImageCodecInfo JpegCodec = GetJpegCodec(); private static ImageCodecInfo GetJpegCodec() { ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); foreach (ImageCodecInfo c in codecs) if (c.FormatID == ImageFormat.Jpeg.Guid) return c; return null; } // 读图 + 按 EXIF 摆正 + 可选缩小,存为临时 JPG private static void SavePrepared(string path, string outPath, bool shrink) { using (Image img = Prepare(path, shrink)) { EncoderParameters ep = new EncoderParameters(1); ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L); img.Save(outPath, JpegCodec != null ? JpegCodec : null, ep); } } // 读图 + 可选缩小 + 按 EXIF 摆正 private static Image Prepare(string path, bool shrink) { Image src = Image.FromFile(path); try { if (Array.IndexOf(src.PropertyIdList, 274) > -1) { int o = src.GetPropertyItem(274).Value[0]; RotateFlipType rft = RotateFlipType.RotateNoneFlipNone; if (o == 3) rft = RotateFlipType.Rotate180FlipNone; else if (o == 6) rft = RotateFlipType.Rotate90FlipNone; else if (o == 8) rft = RotateFlipType.Rotate270FlipNone; if (rft != RotateFlipType.RotateNoneFlipNone) { src.RotateFlip(rft); try { src.RemovePropertyItem(274); } catch { } } } } catch { } if (!shrink) return src; int maxSide = Math.Max(src.Width, src.Height); if (maxSide <= 3000) return src; int nw = (int)((long)src.Width * 3000 / maxSide); int nh = (int)((long)src.Height * 3000 / maxSide); Bitmap small = new Bitmap(nw, nh); using (Graphics g = Graphics.FromImage(small)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(src, 0, 0, nw, nh); } src.Dispose(); return small; } } // 按文件名自然排序:IMG_2.jpg 排在 IMG_10.jpg 前面 public class NaturalNameComparer : IComparer { public int Compare(string a, string b) { string na = Path.GetFileName(a), nb = Path.GetFileName(b); int ia = 0, ib = 0; while (ia < na.Length && ib < nb.Length) { char ca = na[ia], cb = nb[ib]; if (char.IsDigit(ca) && char.IsDigit(cb)) { long va = 0, vb = 0; while (ia < na.Length && char.IsDigit(na[ia])) { va = va * 10 + (na[ia] - '0'); ia++; } while (ib < nb.Length && char.IsDigit(nb[ib])) { vb = vb * 10 + (nb[ib] - '0'); ib++; } if (va != vb) return va < vb ? -1 : 1; } else { int c = string.Compare(ca.ToString(), cb.ToString(), StringComparison.OrdinalIgnoreCase); if (c != 0) return c; ia++; ib++; } } return na.Length.CompareTo(nb.Length); } } // 命令行自测:现场造图 → 生成 PDF → 重新打开核对页数、页面尺寸、内嵌图片像素尺寸、排序与报错 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 MakeImage(string path, int w, int h, Color c) { using (Bitmap b = new Bitmap(w, h)) using (Graphics g = Graphics.FromImage(b)) { g.Clear(c); // 留一圈白边:整页纯色在部分渲染器里会被当成空白,加了边框更像真实扫描件 using (Pen pen = new Pen(Color.White, 6)) g.DrawRectangle(pen, 9, 9, w - 18, h - 18); b.Save(path, ImageFormat.Png); } } // 页面里第一个图片 XObject 的像素尺寸;读不到返回「无」 private static string ImageDims(PdfPage page) { PdfDictionary res = page.Elements.GetDictionary("/Resources"); if (res == null) return "无"; PdfDictionary xo = res.Elements.GetDictionary("/XObject"); if (xo == null) return "无"; foreach (string key in xo.Elements.Keys) { PdfItem it = xo.Elements[key]; PdfReference r = it as PdfReference; PdfDictionary d = (r != null ? r.Value : it) as PdfDictionary; if (d == null) continue; if (d.Elements.GetName("/Subtype") != "/Image") continue; return d.Elements.GetInteger("/Width") + "x" + d.Elements.GetInteger("/Height"); } return "无"; } private static string PageSize(PdfPage page) { return Math.Round(page.Width.Point) + "x" + Math.Round(page.Height.Point); } public static int Run(string dir) { if (string.IsNullOrEmpty(dir)) dir = Path.Combine(Path.GetTempPath(), "greentool-img2pdf-selftest"); try { if (Directory.Exists(dir)) { try { Directory.Delete(dir, true); } catch { } } Directory.CreateDirectory(dir); _lines.Add("图片转 PDF 自测(" + dir + ")"); string a = Path.Combine(dir, "a_wide.png"); string b = Path.Combine(dir, "b_tall.png"); string c = Path.Combine(dir, "c_square.png"); MakeImage(a, 800, 600, Color.FromArgb(220, 40, 40)); MakeImage(b, 600, 1200, Color.FromArgb(40, 40, 220)); MakeImage(c, 200, 200, Color.FromArgb(40, 180, 60)); List files = new List(); files.Add(a); files.Add(b); files.Add(c); // ① A4 自适应:横图横页、竖图竖页、方图竖页 string pdf = Path.Combine(dir, "a4.pdf"); int n = ImgToPdfForm.Build(files, pdf, 0, 10.0, false); CheckInt("A4 模式:页数 = 输入张数", n, 3); Check("A4 模式:文件有内容", new FileInfo(pdf).Length > 2000 ? "合理" : "太小", "合理"); PdfDocument doc = PdfReader.Open(pdf, PdfDocumentOpenMode.Import); CheckInt("A4 模式:重新打开仍是 3 页", doc.PageCount, 3); Check("A4 模式:横图给横向 A4(842x595)", PageSize(doc.Pages[0]), "842x595"); Check("A4 模式:竖图给纵向 A4(595x842)", PageSize(doc.Pages[1]), "595x842"); Check("A4 模式:方图给纵向 A4(595x842)", PageSize(doc.Pages[2]), "595x842"); Check("A4 模式:第 1 页内嵌 800x600 原图(没被缩)", ImageDims(doc.Pages[0]), "800x600"); Check("A4 模式:第 2 页内嵌 600x1200 原图", ImageDims(doc.Pages[1]), "600x1200"); Check("A4 模式:第 3 页内嵌 200x200 原图", ImageDims(doc.Pages[2]), "200x200"); doc.Close(); // ② 顺序必须照列表来,不能自己重排 string order = Path.Combine(dir, "order.pdf"); List rev = new List(); rev.Add(b); rev.Add(a); ImgToPdfForm.Build(rev, order, 0, 10.0, false); PdfDocument od = PdfReader.Open(order, PdfDocumentOpenMode.Import); Check("顺序:传 [b,a] 时第 1 页是 b(600x1200)", ImageDims(od.Pages[0]), "600x1200"); Check("顺序:第 2 页是 a(800x600)", ImageDims(od.Pages[1]), "800x600"); od.Close(); // ③ 与图片同大小:1 像素 = 0.75 点(96dpi) string same = Path.Combine(dir, "same.pdf"); ImgToPdfForm.Build(files, same, 1, 0, false); PdfDocument sd = PdfReader.Open(same, PdfDocumentOpenMode.Import); Check("同大小模式:800x600 图 → 页面 600x450", PageSize(sd.Pages[0]), "600x450"); Check("同大小模式:600x1200 图 → 页面 450x900", PageSize(sd.Pages[1]), "450x900"); sd.Close(); // ④ 超大图:勾了缩小才压到长边 3000 string big = Path.Combine(dir, "big.png"); MakeImage(big, 4000, 3000, Color.FromArgb(90, 140, 200)); List one = new List(); one.Add(big); string raw = Path.Combine(dir, "big_raw.pdf"); ImgToPdfForm.Build(one, raw, 1, 0, false); PdfDocument rd = PdfReader.Open(raw, PdfDocumentOpenMode.Import); Check("不勾缩小:4000x3000 原样进 PDF", ImageDims(rd.Pages[0]), "4000x3000"); rd.Close(); string shr = Path.Combine(dir, "big_shrink.pdf"); ImgToPdfForm.Build(one, shr, 1, 0, true); PdfDocument hd = PdfReader.Open(shr, PdfDocumentOpenMode.Import); Check("勾了缩小:长边压到 3000(等比 3000x2250)", ImageDims(hd.Pages[0]), "3000x2250"); CheckTrue("勾了缩小:产物确实更小", new FileInfo(shr).Length < new FileInfo(raw).Length); hd.Close(); // ⑤ 自然排序:IMG_2 要排在 IMG_10 前面(字典序会反) NaturalNameComparer cmp = new NaturalNameComparer(); CheckTrue("自然排序:IMG_2 在 IMG_10 前面", cmp.Compare("IMG_2.jpg", "IMG_10.jpg") < 0); CheckTrue("自然排序:page1 在 page10 前面", cmp.Compare("page1.png", "page10.png") < 0); CheckTrue("自然排序:a.png 在 b.png 前面", cmp.Compare("a.png", "b.png") < 0); // ⑥ 图片不存在必须报错,不能静默产出空 PDF string badPdf = Path.Combine(dir, "bad.pdf"); bool threw = false; try { List bad = new List(); bad.Add(Path.Combine(dir, "nothere.png")); ImgToPdfForm.Build(bad, badPdf, 0, 10.0, false); } catch { threw = true; } CheckTrue("图片不存在会报错", threw); CheckTrue("报错时不留半成品 PDF", !File.Exists(badPdf)); } 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-imgtopdf.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } } static class Program { [STAThread] static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // 自测:ImgToPdf.exe --selftest [工作目录] (退出码 0 全过 / 1 有失败) if (args.Length >= 1 && args[0] == "--selftest") { Environment.Exit(SelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.Run(new ImgToPdfForm()); } } }