// PDF 转图片(PDF → PNG/JPG 批量导出) // 引擎:Windows 10+ 系统自带 PDF 渲染(Windows.Data.Pdf),离线、免费、不传文件。 // 说明:net48 直接引用 WinRT winmd 时会撞「union Windows.winmd」依赖问题 //(System.Runtime.WindowsRuntime.dll 是按 union 元数据编译的),所以这里 // 不用 GetAwaiter/AsBuffer 等扩展,改为轮询 IAsyncInfo.Status 等待异步完成。 // 渲染统一丢到线程池(Task.Run),避免 STA 线程被轮询卡死。全部自包含。 using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Windows.Data.Pdf; using Windows.Foundation; using Windows.Storage; using Windows.Storage.Streams; namespace GtPdf2Img { /* ───────────── 核心:PDF 渲染操作 ───────────── */ public static class PdfOps { /* 轮询等待 WinRT 异步操作(替代 await 扩展) */ public static T WaitOp(IAsyncOperation op) { while (op.Status == AsyncStatus.Started) Thread.Sleep(15); if (op.Status == AsyncStatus.Error) throw op.ErrorCode; if (op.Status != AsyncStatus.Completed) throw new InvalidOperationException("异步操作被取消"); return op.GetResults(); } static void WaitAction(IAsyncAction act) { while (act.Status == AsyncStatus.Started) Thread.Sleep(15); if (act.Status == AsyncStatus.Error) throw act.ErrorCode; if (act.Status != AsyncStatus.Completed) throw new InvalidOperationException("异步操作被取消"); } /* 页码范围解析:"1-3,5"、"2-"、"5";空 = 全部页。返回 1 起页码(升序去重)。 */ public static List ParseRange(string spec, int pageCount) { List result = new List(); if (string.IsNullOrWhiteSpace(spec)) { for (int i = 1; i <= pageCount; i++) result.Add(i); return result; } string[] parts = spec.Split(new char[] { ',', ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string raw in parts) { string p = raw.Trim(); if (p.Length == 0) continue; int dash = p.IndexOf('-'); int lo, hi; if (dash < 0) { int n; if (!int.TryParse(p, out n)) throw new ArgumentException("页码范围格式不对:" + spec); lo = hi = n; } else { string a = p.Substring(0, dash).Trim(); string b = p.Substring(dash + 1).Trim(); if (a.Length == 0) lo = 1; else if (!int.TryParse(a, out lo)) throw new ArgumentException("页码范围格式不对:" + spec); if (b.Length == 0) hi = pageCount; else if (!int.TryParse(b, out hi)) throw new ArgumentException("页码范围格式不对:" + spec); } if (lo < 1) lo = 1; if (hi > pageCount) hi = pageCount; for (int i = lo; i <= hi; i++) result.Add(i); } // 去重保序 List uniq = new List(); foreach (int n in result) if (!uniq.Contains(n)) uniq.Add(n); return uniq; } /* 读 PDF 页数 */ public static int GetPageCount(string pdfPath) { return Task.Run(() => { PdfDocument doc = OpenDoc(pdfPath); return (int)doc.PageCount; }).GetAwaiter().GetResult(); } static PdfDocument OpenDoc(string pdfPath) { if (string.IsNullOrEmpty(pdfPath) || !File.Exists(pdfPath)) throw new FileNotFoundException("找不到 PDF 文件:" + pdfPath); string abs = Path.GetFullPath(pdfPath); StorageFile file = WaitOp(StorageFile.GetFileFromPathAsync(abs)); return WaitOp(PdfDocument.LoadFromFileAsync(file)); } /* 引擎渲染缩放系数(= 系统 DPI / 96),进程内缓存一次。 做法:试渲染 DestWidth=1000,量实际像素宽,1000 DIP → W 像素,比例即得。 (不用 page.Size:Windows.Foundation.Size 的属性投影会拖进 System.Runtime.WindowsRuntime.dll 依赖,必须绕开。) */ static double _scale = 0; static readonly object _scaleLock = new object(); static double DetectScale(PdfDocument doc) { lock (_scaleLock) { if (_scale > 0) return _scale; PdfPage page = doc.GetPage(0); try { InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream(); PdfPageRenderOptions ro = new PdfPageRenderOptions(); ro.DestinationWidth = 1000; WaitAction(page.RenderToStreamAsync(ms, ro)); byte[] png = ReadStreamBytes(ms); using (MemoryStream pms = new MemoryStream(png)) using (Bitmap b = new Bitmap(pms)) { _scale = b.Width / 1000.0; } } finally { page.Dispose(); } if (_scale <= 0) _scale = 1.0; return _scale; } } /* 渲染选项 */ public class RenderOptions { public int DestWidth; // 0 = 引擎默认(约 134 DPI 高清) public string Format = "png"; // png / jpg public int JpegQuality = 90; // 10-100 public string PageRange = ""; // 空 = 全部 public bool SubFolder = true; // 输出到「PDF转图片_文件名」子文件夹 } /* 单个 PDF 批量导出,返回写出的文件路径列表 */ public static List RenderPdf(string pdfPath, RenderOptions opt) { return Task.Run(() => RenderPdfCore(pdfPath, opt)).GetAwaiter().GetResult(); } static List RenderPdfCore(string pdfPath, RenderOptions opt) { List written = new List(); PdfDocument doc = OpenDoc(pdfPath); int pageCount = (int)doc.PageCount; if (pageCount <= 0) return written; List pages = ParseRange(opt.PageRange, pageCount); string dir = Path.GetDirectoryName(Path.GetFullPath(pdfPath)); string baseName = Path.GetFileNameWithoutExtension(pdfPath); if (opt.SubFolder) { dir = Path.Combine(dir, "PDF转图片_" + baseName); Directory.CreateDirectory(dir); } string ext = opt.Format == "jpg" ? ".jpg" : ".png"; foreach (int pageNo in pages) { PdfPage page = doc.GetPage((uint)(pageNo - 1)); InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream(); try { if (opt.DestWidth > 0) { PdfPageRenderOptions ro = new PdfPageRenderOptions(); // DestinationWidth 是 DIP 单位,实际像素会被系统 DPI 缩放。 // GDI+ 的 DpiX 在 DPI-unaware 进程里拿不到真实值, // 所以用「试渲染一页、用实际宽/页面 DIP 宽反推缩放」的方式校正。 ro.DestinationWidth = (uint)Math.Ceiling(opt.DestWidth / DetectScale(doc)); WaitAction(page.RenderToStreamAsync(ms, ro)); } else { WaitAction(page.RenderToStreamAsync(ms)); } byte[] bytes = ReadStreamBytes(ms); string outPath = Path.Combine(dir, baseName + "_p" + pageNo.ToString("000") + ext); if (opt.Format == "jpg") { using (MemoryStream pms = new MemoryStream(bytes)) using (Bitmap bmp = new Bitmap(pms)) { SaveJpeg(bmp, outPath, opt.JpegQuality); } } else { File.WriteAllBytes(outPath, bytes); } written.Add(outPath); } finally { page.Dispose(); } } return written; } /* 随机访问流 → 字节数组(不走 AsBuffer 扩展) */ public static byte[] ReadStreamBytes(IRandomAccessStream stream) { uint size = (uint)stream.Size; DataReader dr = new DataReader(stream.GetInputStreamAt(0)); try { WaitOp(dr.LoadAsync(size)); byte[] bytes = new byte[size]; dr.ReadBytes(bytes); return bytes; } finally { dr.DetachStream(); } } /* 按质量保存 JPEG */ public static void SaveJpeg(Bitmap bmp, string path, long quality) { if (quality < 10) quality = 10; if (quality > 100) quality = 100; ImageCodecInfo jpeg = null; foreach (ImageCodecInfo ici in ImageCodecInfo.GetImageEncoders()) if (ici.MimeType == "image/jpeg") { jpeg = ici; break; } if (jpeg == null) throw new InvalidOperationException("系统没有 JPEG 编码器"); using (EncoderParameters ep = new EncoderParameters(1)) using (EncoderParameter p = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality)) { ep.Param[0] = p; bmp.Save(path, jpeg, ep); } } /* 输出文件名规则(000 补零) */ public static string PageFileName(string baseName, int pageNo, bool jpg) { return baseName + "_p" + pageNo.ToString("000") + (jpg ? ".jpg" : ".png"); } /* 是不是 PDF(按扩展名,宽容大小写) */ public static bool IsPdfPath(string path) { return !string.IsNullOrEmpty(path) && string.Equals(Path.GetExtension(path), ".pdf", StringComparison.OrdinalIgnoreCase); } } /* ───────────── 界面 ───────────── */ public class Pdf2ImgForm : Form { public bool headless; ListBox _files; ComboBox _fmt, _widthMode; NumericUpDown _quality, _width; TextBox _range; CheckBox _sub; Button _go; Label _status; List _paths = new List(); public Pdf2ImgForm() { Text = "PDF 转图片 — 绿色工具箱"; Font = new Font("Microsoft YaHei UI", 9F); Size = new Size(560, 520); FormBorderStyle = FormBorderStyle.FixedSingle; MaximizeBox = false; StartPosition = FormStartPosition.CenterScreen; AllowDrop = true; DragEnter += OnDragEnter; DragDrop += OnDragDrop; int y = 12; Controls.Add(MakeLabel("拖入 PDF 文件(可多个),或:", 12, y, 320)); y += 26; Button browse = MakeButton("选择 PDF…", 12, y, 100); browse.Click += delegate { Browse(); }; Controls.Add(browse); y += 34; _files = new ListBox(); _files.SetBounds(12, y, 520, 150); _files.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; Controls.Add(_files); y += 160; Controls.Add(MakeLabel("输出格式", 12, y + 4, 60)); _fmt = new ComboBox(); _fmt.DropDownStyle = ComboBoxStyle.DropDownList; _fmt.Items.Add("PNG(无损)"); _fmt.Items.Add("JPG(体积小)"); _fmt.SelectedIndex = 0; _fmt.SetBounds(78, y, 110, 24); _fmt.SelectedIndexChanged += delegate { _quality.Enabled = _fmt.SelectedIndex == 1; }; Controls.Add(_fmt); Controls.Add(MakeLabel("JPG 质量", 200, y + 4, 56)); _quality = new NumericUpDown(); _quality.Minimum = 10; _quality.Maximum = 100; _quality.Value = 90; _quality.SetBounds(260, y, 56, 24); _quality.Enabled = false; Controls.Add(_quality); Controls.Add(MakeLabel("输出宽度", 330, y + 4, 56)); _widthMode = new ComboBox(); _widthMode.DropDownStyle = ComboBoxStyle.DropDownList; _widthMode.Items.Add("默认高清"); _widthMode.Items.Add("自定义宽度"); _widthMode.SelectedIndex = 0; _widthMode.SetBounds(390, y, 90, 24); _widthMode.SelectedIndexChanged += delegate { _width.Enabled = _widthMode.SelectedIndex == 1; }; Controls.Add(_widthMode); _width = new NumericUpDown(); _width.Minimum = 100; _width.Maximum = 10000; _width.Value = 800; _width.SetBounds(484, y, 48, 24); _width.Enabled = false; Controls.Add(_width); y += 34; Controls.Add(MakeLabel("页码范围(如 1-3,5,空=全部)", 12, y + 4, 180)); _range = new TextBox(); _range.SetBounds(200, y, 180, 24); Controls.Add(_range); _sub = new CheckBox(); _sub.Text = "输出到「PDF转图片_文件名」子文件夹"; _sub.Checked = true; _sub.SetBounds(12, y + 32, 300, 22); Controls.Add(_sub); y += 62; _go = MakeButton("开始转换", 12, y, 110); _go.Click += delegate { StartConvert(); }; Controls.Add(_go); _status = MakeLabel("就绪", 140, y + 6, 380); Controls.Add(_status); if (headless) return; } Label MakeLabel(string text, int x, int y, int w) { Label l = new Label(); l.Text = text; l.SetBounds(x, y, w, 22); l.AutoSize = false; return l; } Button MakeButton(string text, int x, int y, int w) { Button b = new Button(); b.Text = text; b.SetBounds(x, y, w, 28); return b; } void Browse() { using (OpenFileDialog od = new OpenFileDialog()) { od.Filter = "PDF 文件|*.pdf|所有文件|*.*"; od.Multiselect = true; if (od.ShowDialog(this) == DialogResult.OK) AddFiles(od.FileNames); } } void OnDragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; } void OnDragDrop(object sender, DragEventArgs e) { string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); AddFiles(files); } void AddFiles(string[] files) { int added = 0; foreach (string f in files) { if (PdfOps.IsPdfPath(f) && File.Exists(f) && !_paths.Contains(Path.GetFullPath(f))) { _paths.Add(Path.GetFullPath(f)); _files.Items.Add(f); added++; } } _status.Text = added > 0 ? "已添加 " + added + " 个 PDF" : "没有可添加的 PDF 文件"; } void StartConvert() { if (_paths.Count == 0) { MessageBox.Show("请先拖入或选择 PDF 文件"); return; } PdfOps.RenderOptions opt = new PdfOps.RenderOptions(); opt.Format = _fmt.SelectedIndex == 1 ? "jpg" : "png"; opt.JpegQuality = (int)_quality.Value; opt.DestWidth = _widthMode.SelectedIndex == 1 ? (int)_width.Value : 0; opt.PageRange = _range.Text; opt.SubFolder = _sub.Checked; List snapshot = new List(_paths); _go.Enabled = false; _status.Text = "正在转换…"; ThreadPool.QueueUserWorkItem(delegate { int total = 0, okFiles = 0; List errors = new List(); string lastDir = null; foreach (string pdf in snapshot) { try { List written = PdfOps.RenderPdf(pdf, opt); total += written.Count; okFiles++; if (written.Count > 0) lastDir = Path.GetDirectoryName(written[0]); BeginInvoke((MethodInvoker)delegate { _status.Text = "已转换 " + okFiles + "/" + snapshot.Count + " 个文件,共 " + total + " 张图"; }); } catch (Exception ex) { errors.Add(Path.GetFileName(pdf) + ":" + ex.Message); } } BeginInvoke((MethodInvoker)delegate { _go.Enabled = true; if (errors.Count > 0) _status.Text = "完成," + errors.Count + " 个文件失败:" + errors[0]; else _status.Text = "全部完成:共导出 " + total + " 张图片"; if (lastDir != null && total > 0) { try { System.Diagnostics.Process.Start("explorer.exe", "/select,\"" + lastDir + "\""); } catch { } } }); }); } protected override void SetVisibleCore(bool value) { base.SetVisibleCore(headless ? false : value); } } /* ───────────── 自测 ───────────── */ public static class Pdf2ImgSelfTest { static int _pass, _fail; static List _lines = new List(); static void Check(string name, object got, object want) { bool ok = string.Equals(got == null ? "" : got.ToString(), want == null ? "" : want.ToString()); if (ok) { _pass++; _lines.Add(" [ok] " + name); } else { _fail++; _lines.Add(" [!!] " + name + " got=" + got + " want=" + want); } } static void CheckTrue(string name, bool cond) { Check(name, cond, true); } /* ── 自带最小 PDF 生成器(文本 + 彩色矩形,多页),自测专用 ── */ public static void MakeTestPdf(string path, string[] texts) { MemoryStream outMs = new MemoryStream(); Action w = delegate (string s) { byte[] b = Encoding.ASCII.GetBytes(s); outMs.Write(b, 0, b.Length); }; float[][] colors = new float[][] { new float[] { 1f, 0f, 0f }, new float[] { 0f, 0.6f, 0f }, new float[] { 0f, 0f, 1f }, }; List pageObjNums = new List(); int nextNum = 3; Dictionary bodies = new Dictionary(); for (int i = 0; i < texts.Length; i++) { int pageObj = nextNum++; int contObj = nextNum++; pageObjNums.Add(pageObj); float[] c = colors[i % colors.Length]; // 内容加多层彩色矩形(形成渐变),让 JPG 质量差异可测 StringBuilder cs = new StringBuilder(); cs.Append("BT /F1 20 Tf 30 240 Td (").Append(texts[i]).Append(") Tj ET\r\n"); for (int k = 0; k < 36; k++) { float t = k / 35f; cs.Append("0.5 ").Append((0.2 + 0.8 * t).ToString("0.###")).Append(" ") .Append((1 - t).ToString("0.###")).Append(" rg ") .Append((15 + k * 3)).Append(" ").Append((35 + k * 4)).Append(" ") .Append((350 - k * 4)).Append(" ").Append((200 - k * 3)) .Append(" re f\r\n"); } cs.Append("4 w ").Append(c[0].ToString("0.##")).Append(" ") .Append(c[1].ToString("0.##")).Append(" ").Append(c[2].ToString("0.##")) .Append(" RG 20 40 360 220 re S"); string content = cs.ToString(); byte[] cb = Encoding.ASCII.GetBytes(content); string contDict = "<< /Length " + cb.Length + " >>\r\nstream\r\n" + content + "\r\nendstream"; bodies[pageObj] = Encoding.ASCII.GetBytes( "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 400 300] /Contents " + contObj + " 0 R /Resources << /Font << /F1 " + (3 + texts.Length * 2) + " 0 R >> >> >>"); bodies[contObj] = Encoding.ASCII.GetBytes(contDict); } bodies[1] = Encoding.ASCII.GetBytes("<< /Type /Catalog /Pages 2 0 R >>"); StringBuilder kids = new StringBuilder(); foreach (int n in pageObjNums) kids.Append(n).Append(" 0 R "); bodies[2] = Encoding.ASCII.GetBytes( "<< /Type /Pages /Kids [" + kids.ToString() + "] /Count " + texts.Length + " >>"); bodies[3 + texts.Length * 2] = Encoding.ASCII.GetBytes( "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"); w("%PDF-1.4\r\n"); Dictionary offsets = new Dictionary(); int pos = (int)outMs.Length; List nums = new List(bodies.Keys); nums.Sort(); foreach (int n in nums) { offsets[n] = (int)outMs.Length; w(n + " 0 obj\r\n"); byte[] bb = bodies[n]; outMs.Write(bb, 0, bb.Length); w("\r\nendobj\r\n"); } int xref = (int)outMs.Length; int maxn = nums.Count + 1; w("xref\r\n0 " + maxn + "\r\n"); w("0000000000 65535 f \r\n"); for (int i = 1; i < maxn; i++) { if (offsets.ContainsKey(i)) w(offsets[i].ToString("D10") + " 00000 n \r\n"); else w("0000000000 65535 f \r\n"); } w("trailer\r\n<< /Size " + maxn + " /Root 1 0 R >>\r\nstartxref\r\n" + xref + "\r\n%%EOF\r\n"); File.WriteAllBytes(path, outMs.ToArray()); } public static int Run(string dir) { _pass = 0; _fail = 0; _lines = new List(); _lines.Add("PDF转图片 自测 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); string baseDir = string.IsNullOrEmpty(dir) ? Path.Combine(Path.GetTempPath(), "gt-pdf2img-" + Guid.NewGuid().ToString("N").Substring(0, 8)) : dir; try { Directory.CreateDirectory(baseDir); try { Console.OutputEncoding = Encoding.UTF8; } catch { } string pdf1 = Path.Combine(baseDir, "one.pdf"); string pdf3 = Path.Combine(baseDir, "three.pdf"); MakeTestPdf(pdf1, new string[] { "PDF RENDER TEST 2026" }); MakeTestPdf(pdf3, new string[] { "PAGE ONE ALPHA", "PAGE TWO BETA", "PAGE THREE GAMMA" }); // 1. 页数 Check("单页 PDF 页数", PdfOps.GetPageCount(pdf1), 1); Check("三页 PDF 页数", PdfOps.GetPageCount(pdf3), 3); // 2. 全部渲染:3 个 PNG,命名补零 PdfOps.RenderOptions opt = new PdfOps.RenderOptions(); opt.SubFolder = false; List files = PdfOps.RenderPdf(pdf3, opt); Check("全部渲染张数", files.Count, 3); Check("文件名 p001", Path.GetFileName(files[0]), "three_p001.png"); Check("文件名 p003", Path.GetFileName(files[2]), "three_p003.png"); CheckTrue("PNG 魔数", IsPng(File.ReadAllBytes(files[0]))); // 3. 默认渲染保持页面纵横比 4:3(400x300) using (Bitmap b0 = new Bitmap(files[0])) { double ratio = (double)b0.Width / b0.Height; Check("默认纵横比 4:3", Math.Abs(ratio - 4.0 / 3.0) < 0.05, true); CheckTrue("默认宽度不低于 500px", b0.Width >= 500); // 4. 像素内容:红框存在(第 1 页红描边矩形) int reds = 0; for (int yy = 0; yy < b0.Height; yy += 3) for (int xx = 0; xx < b0.Width; xx += 3) { Color px = b0.GetPixel(xx, yy); if (px.R > 150 && px.G < 80 && px.B < 80) reds++; } CheckTrue("红框渲染存在", reds > 5); } // 5. 自定义宽度 800 → 宽 800±2(引擎内部取整)、高约 600 PdfOps.RenderOptions optW = new PdfOps.RenderOptions(); optW.SubFolder = false; optW.DestWidth = 800; List fw = PdfOps.RenderPdf(pdf1, optW); using (Bitmap b = new Bitmap(fw[0])) { CheckTrue("宽 800 渲染宽度在容差内", Math.Abs(b.Width - 800) <= 2); CheckTrue("宽 800 高度等比", Math.Abs(b.Height - 600) <= 2); } // 6. JPG 输出 + 质量 PdfOps.RenderOptions optJ = new PdfOps.RenderOptions(); optJ.SubFolder = false; optJ.Format = "jpg"; optJ.JpegQuality = 90; List fj = PdfOps.RenderPdf(pdf1, optJ); CheckTrue("JPG 魔数", File.ReadAllBytes(fj[0])[0] == 0xFF && File.ReadAllBytes(fj[0])[1] == 0xD8); // JPG 质量参数生效:程序内生成噪声位图,q30 应明显小于 q90 string q90Path = Path.Combine(baseDir, "q90.jpg"); string q30Path = Path.Combine(baseDir, "q30.jpg"); using (Bitmap noise = new Bitmap(320, 320, PixelFormat.Format24bppRgb)) { int seed = 12345; for (int yy = 0; yy < 320; yy++) for (int xx = 0; xx < 320; xx++) { seed = seed * 1103515245 + 12345; int r = (seed >> 16) & 0xFF; seed = seed * 1103515245 + 12345; int g = (seed >> 16) & 0xFF; seed = seed * 1103515245 + 12345; int bch = (seed >> 16) & 0xFF; noise.SetPixel(xx, yy, Color.FromArgb(r, g, bch)); } PdfOps.SaveJpeg(noise, q90Path, 90); PdfOps.SaveJpeg(noise, q30Path, 30); } CheckTrue("低质量 JPG 更小", new FileInfo(q30Path).Length < new FileInfo(q90Path).Length); // 7. 页码范围解析 Check("范围 2-3", ListStr(PdfOps.ParseRange("2-3", 3)), "2,3"); Check("范围 1,3", ListStr(PdfOps.ParseRange("1,3", 3)), "1,3"); Check("范围 2- 剩余", ListStr(PdfOps.ParseRange("2-", 3)), "2,3"); Check("范围 5 越界裁掉", ListStr(PdfOps.ParseRange("5", 3)), ""); Check("范围带空格", ListStr(PdfOps.ParseRange(" 2 - 3 ", 3)), "2,3"); Check("范围去重", ListStr(PdfOps.ParseRange("1,1,2", 3)), "1,2"); Check("空范围=全部", ListStr(PdfOps.ParseRange("", 3)), "1,2,3"); try { PdfOps.ParseRange("abc", 3); Check("非法范围抛异常", false, true); } catch (ArgumentException) { Check("非法范围抛异常", true, true); } // 8. 范围渲染:2-3 → p002/p003 PdfOps.RenderOptions optR = new PdfOps.RenderOptions(); optR.SubFolder = false; optR.PageRange = "2-3"; List fr = PdfOps.RenderPdf(pdf3, optR); Check("范围渲染张数", fr.Count, 2); Check("范围渲染文件名", Path.GetFileName(fr[0]), "three_p002.png"); // 9. 子文件夹输出 PdfOps.RenderOptions optS = new PdfOps.RenderOptions(); optS.SubFolder = true; List fs = PdfOps.RenderPdf(pdf3, optS); Check("子文件夹输出", Path.GetFileName(Path.GetDirectoryName(fs[0])), "PDF转图片_three"); CheckTrue("子文件夹已建", Directory.Exists( Path.Combine(baseDir, "PDF转图片_three"))); // 10. 异常输入 try { PdfOps.GetPageCount(Path.Combine(baseDir, "nope.pdf")); Check("缺文件抛异常", false, true); } catch (FileNotFoundException) { Check("缺文件抛异常", true, true); } string fake = Path.Combine(baseDir, "fake.pdf"); File.WriteAllBytes(fake, new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A }); try { PdfOps.GetPageCount(fake); Check("非 PDF 抛异常", false, true); } catch (Exception) { Check("非 PDF 抛异常", true, true); } // 11. 命名规则 Check("补零命名 png", PdfOps.PageFileName("doc", 7, false), "doc_p007.png"); Check("补零命名 jpg", PdfOps.PageFileName("doc", 12, true), "doc_p012.jpg"); // 12. 多文件批量 PdfOps.RenderOptions optM = new PdfOps.RenderOptions(); optM.SubFolder = false; int total = PdfOps.RenderPdf(pdf1, optM).Count + PdfOps.RenderPdf(pdf3, optM).Count; Check("多文件批量张数", total, 4); // 13. Form 层 Pdf2ImgForm form = new Pdf2ImgForm(); form.headless = true; Check("窗体控件就绪", form.Controls.Count > 5, true); // 14. 大量页去重保序 Check("范围 3,1,2 保序", ListStr(PdfOps.ParseRange("3,1,2", 3)), "3,1,2"); } catch (Exception ex) { _lines.Add("异常: " + ex.GetType().Name + ": " + ex.Message); _fail++; } _lines.Add("结果: " + _pass + " 通过, " + _fail + " 失败"); string all = string.Join("\r\n", _lines.ToArray()); Console.WriteLine(all); try { File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "selftest-pdf2img.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } static bool IsPng(byte[] b) { return b != null && b.Length >= 4 && b[0] == 0x89 && b[1] == 0x50 && b[2] == 0x4E && b[3] == 0x47; } static string ListStr(List list) { return string.Join(",", list.ConvertAll(delegate (int n) { return n.ToString(); }).ToArray()); } } /* ───────────── 入口 ───────────── */ static class Program { [STAThread] static int Main(string[] args) { if (args.Length >= 1 && args[0] == "--selftest") return Pdf2ImgSelfTest.Run(args.Length >= 2 ? args[1] : null); if (args.Length >= 2 && args[0] == "--count") { try { Console.WriteLine(PdfOps.GetPageCount(args[1])); return 0; } catch (Exception ex) { Console.WriteLine("ERR: " + ex.Message); return 1; } } using (Mutex mutex = new Mutex(true, "GT-PDF2IMG-单实例")) { if (!mutex.WaitOne(0, false)) return 0; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Pdf2ImgForm()); } return 0; } } }