// PDF 压缩 - 绿色工具箱 // C# 5.0 语法。使用 PdfSharp 1.50(MIT 许可),构建后经 ILMerge 合并为单 exe // 功能:把 PDF 里的图片降采样重压(扫描件最有效)+ 内容流 Flate 压缩,输出前先比大小,压不过原文件就放弃 using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; 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 PdfCompressForm : 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 cmbLevel; private Button btnPick, btnGo; private ProgressBar progress; private Label lblStatus; private List files = new List(); public PdfCompressForm() { 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, 360); this.MinimumSize = new Size(700, 340); 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; Label la = new Label(); la.Text = "压缩强度"; la.AutoSize = true; la.Location = new Point(x, y + 4); this.Controls.Add(la); cmbLevel = new ComboBox(); cmbLevel.DropDownStyle = ComboBoxStyle.DropDownList; cmbLevel.Items.Add("轻度 —— 图片最长边 2200px,适合还要打印的文件"); cmbLevel.Items.Add("标准 —— 图片最长边 1600px,屏幕阅读与邮件发送(推荐)"); cmbLevel.Items.Add("强力 —— 图片最长边 1100px,体积优先,只求能看清"); cmbLevel.SelectedIndex = 1; cmbLevel.Location = new Point(x + 70, y); cmbLevel.Size = new Size(420, 26); this.Controls.Add(cmbLevel); y += 46; Label lb = new Label(); lb.Text = "诚实说明:压缩只对“图片型”内容生效(扫描件、拍照、图片导出的 PDF)。" + "纯文字矢量 PDF 本来就小,压不动时会明确告诉你、不会硬塞一个更大的文件给你。"; lb.AutoSize = false; lb.Size = new Size(728, 44); lb.ForeColor = COL_GRAY; lb.Location = new Point(x, y); this.Controls.Add(lb); y += 56; 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; } long total = 0; foreach (string f in files) total += new FileInfo(f).Length; if (files.Count == 1) txtFile.Text = files[0] + " (" + Kb(total) + ")"; else txtFile.Text = "已选 " + files.Count + " 个 PDF,共 " + Kb(total); } private 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 GoClick(object sender, EventArgs e) { if (files.Count == 0) { lblStatus.Text = "先选择一个 PDF(也可以直接把文件拖进窗口)。"; return; } btnGo.Enabled = false; progress.Maximum = files.Count; progress.Value = 0; int maxSide, quality; LevelParams(cmbLevel.SelectedIndex, out maxSide, out quality); int saved = 0, skipped = 0, failed = 0; StringBuilder report = new StringBuilder(); foreach (string f in files) { string outPath = TargetPath(f); try { long before = new FileInfo(f).Length; Compress(f, outPath, maxSide, quality); long after = new FileInfo(outPath).Length; if (after >= before * 0.97) { File.Delete(outPath); skipped++; report.AppendLine(Path.GetFileName(f) + ":压不动(" + Kb(before) + "),未生成文件"); lblStatus.Text = Path.GetFileName(f) + " 已是精简状态,跳过"; } else { saved++; report.AppendLine(Path.GetFileName(f) + ":" + Kb(before) + " → " + Kb(after) + "(省 " + (100 - after * 100 / before) + "%)"); lblStatus.Text = Path.GetFileName(f) + ":" + Kb(before) + " → " + Kb(after); } } catch (Exception ex) { failed++; try { if (File.Exists(outPath)) File.Delete(outPath); } catch { } report.AppendLine(Path.GetFileName(f) + ":失败(" + ex.Message + ")"); lblStatus.Text = "失败 " + Path.GetFileName(f) + ":" + ex.Message; } progress.Value = progress.Value + 1; Application.DoEvents(); } btnGo.Enabled = true; string head = "压缩 " + saved + " 个"; if (skipped > 0) head += ",跳过 " + skipped + " 个(已是精简状态)"; if (failed > 0) head += ",失败 " + failed + " 个"; lblStatus.Text = head + "。" + (report.Length > 0 ? "" : ""); if (saved > 0 && MessageBox.Show(report.ToString() + "\r\n要打开输出文件夹吗?", "压缩完成", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { try { System.Diagnostics.Process.Start("explorer.exe", "/select,\"" + TargetPath(files[0]) + "\""); } catch { } } } private string TargetPath(string src) { return Path.Combine(Path.GetDirectoryName(src), Path.GetFileNameWithoutExtension(src) + "_已压缩.pdf"); } private void LevelParams(int idx, out int maxSide, out int quality) { if (idx == 0) { maxSide = 2200; quality = 80; } else if (idx == 2) { maxSide = 1100; quality = 55; } else { maxSide = 1600; quality = 72; } } // ===== 核心:压缩 ===== public void Compress(string srcPath, string outPath, int maxSide, int quality) { PdfDocument doc = PdfReader.Open(srcPath, PdfDocumentOpenMode.Modify); try { doc.Options.CompressContentStreams = true; } catch { } int images = CompressImages(doc, maxSide, quality); doc.Save(outPath); doc.Close(); } private static int CompressImages(PdfDocument doc, int maxSide, int quality) { Dictionary done = new Dictionary(); int touched = 0; int pageCount = doc.PageCount; for (int pi = 0; pi < pageCount; pi++) { PdfPage page = doc.Pages[pi]; PdfDictionary res = page.Elements.GetDictionary("/Resources"); if (res == null) continue; PdfDictionary xo = res.Elements.GetDictionary("/XObject"); if (xo == null) continue; List keys = new List(xo.Elements.Keys); foreach (string key in keys) { PdfItem item = xo.Elements[key]; PdfReference r = item as PdfReference; PdfDictionary d = (r != null ? r.Value : item) as PdfDictionary; if (d == null) continue; if (d.Elements.GetName("/Subtype") != "/Image") continue; // 同一张图被多页引用时只处理一次 int id = d.Reference != null ? d.Reference.ObjectNumber : d.GetHashCode(); if (done.ContainsKey(id)) continue; done[id] = true; if (TryRecompressImage(d, maxSide, quality)) touched++; } } return touched; } private static bool TryRecompressImage(PdfDictionary d, int maxSide, int quality) { // 带 SMask/Mask 的复杂图片不碰,避免把透明通道弄丢 if (d.Elements.ContainsKey("/SMask") || d.Elements.ContainsKey("/Mask")) return false; string filter = d.Elements.GetName("/Filter"); if (filter != "/DCTDecode") return false; // 只处理 JPEG 直存的图(扫描件几乎都是) int w = d.Elements.GetInteger("/Width"); int h = d.Elements.GetInteger("/Height"); if (w <= 0 || h <= 0) return false; byte[] raw; try { raw = d.Stream.Value; } catch { return false; } if (raw == null || raw.Length < 8) return false; if (raw[0] != 0xFF || raw[1] != 0xD8) return false; // 不是 JPEG,不碰 // 不需要缩也不再压就跳过 double scale = Math.Min(1.0, (double)maxSide / Math.Max(w, h)); if (scale >= 1.0) return false; int nw = (int)Math.Round(w * scale), nh = (int)Math.Round(h * scale); if (nw < 1) nw = 1; if (nh < 1) nh = 1; // 关键:JPEG 实际尺寸必须和字典 /Width /Height 一致,否则 SumatraPDF 等按字典尺寸 // 解码的阅读器会渲染成噪点(Chrome 容忍,但不赌) byte[] jpeg; try { jpeg = ResizeJpeg(raw, nw, nh, quality); } catch { return false; } if (jpeg == null || jpeg.Length >= raw.Length) return false; d.Stream.Value = jpeg; d.Elements.SetInteger("/Width", nw); d.Elements.SetInteger("/Height", nh); d.Elements.SetInteger("/BitsPerComponent", 8); d.Elements.SetName("/ColorSpace", "/DeviceRGB"); d.Elements.SetName("/Filter", "/DCTDecode"); if (d.Elements.ContainsKey("/Decode")) d.Elements.Remove("/Decode"); if (d.Elements.ContainsKey("/DecodeParms")) d.Elements.Remove("/DecodeParms"); if (d.Elements.ContainsKey("/Interpolate")) d.Elements.Remove("/Interpolate"); return true; } private static byte[] ResizeJpeg(byte[] src, int w, int h, int quality) { using (Image srcImg = Image.FromStream(new MemoryStream(src))) using (Bitmap dst = new Bitmap(w, h)) { using (Graphics g = Graphics.FromImage(dst)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; g.DrawImage(srcImg, 0, 0, w, h); } ImageCodecInfo jpeg = null; foreach (ImageCodecInfo c in ImageCodecInfo.GetImageEncoders()) if (c.FormatID == ImageFormat.Jpeg.Guid) jpeg = c; EncoderParameters eps = new EncoderParameters(1); eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality); using (MemoryStream ms = new MemoryStream()) { dst.Save(ms, jpeg != null ? jpeg : null, eps); return ms.ToArray(); } } } } // 命令行自测:造「大噪点图 PDF」→ 压缩 → 核对页数不变、图缩到目标长边、 // 字典 /Width /Height 与真实 JPEG 像素一致(不一致会让部分阅读器渲染成噪点) 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 ? "是" : "否", "是"); } // 存 JPEG(指定质量) private static void SaveJpeg(Image img, string path, long quality) { ImageCodecInfo jpeg = null; foreach (ImageCodecInfo c in ImageCodecInfo.GetImageEncoders()) if (c.FormatID == ImageFormat.Jpeg.Guid) jpeg = c; EncoderParameters eps = new EncoderParameters(1); eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); img.Save(path, jpeg, eps); } // 确定性噪点图:JPEG 很难压,压缩工具才有「活」可干,也是扫描件的极端版 private static void MakeNoiseJpeg(string path, int w, int h) { using (Bitmap b = new Bitmap(w, h, PixelFormat.Format24bppRgb)) { BitmapData bd = b.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb); byte[] row = new byte[bd.Stride]; Random rnd = new Random(7); for (int y = 0; y < h; y++) { rnd.NextBytes(row); Marshal.Copy(row, 0, new IntPtr(bd.Scan0.ToInt64() + (long)y * bd.Stride), row.Length); } b.UnlockBits(bd); SaveJpeg(b, path, 95L); } } // withImage=true 时第 1 页铺满这张图;第 2 页永远只有文字(验「没图的页不该被弄坏」) private static void MakePdf(string path, string jpg) { PdfDocument doc = new PdfDocument(); PdfPage p1 = doc.AddPage(); p1.Width = XUnit.FromPoint(612); p1.Height = XUnit.FromPoint(792); using (XGraphics g = XGraphics.FromPdfPage(p1)) using (XImage img = XImage.FromFile(jpg)) g.DrawImage(img, 0, 0, 612, 792); PdfPage p2 = doc.AddPage(); p2.Width = XUnit.FromPoint(612); p2.Height = XUnit.FromPoint(792); using (XGraphics g = XGraphics.FromPdfPage(p2)) g.DrawString("this page has no image", new XFont("Arial", 14), XBrushes.Black, 60, 100); doc.Save(path); doc.Close(); } // 读出第 1 页第一张图:字典声明的尺寸 + 真实 JPEG 解码后的尺寸 private static string ImageReport(string path) { PdfDocument doc = PdfReader.Open(path, PdfDocumentOpenMode.Modify); try { if (doc.PageCount == 0) return "无页"; PdfDictionary res = doc.Pages[0].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; int dw = d.Elements.GetInteger("/Width"); int dh = d.Elements.GetInteger("/Height"); int aw = -1, ah = -1; try { byte[] raw = d.Stream.Value; using (MemoryStream ms = new MemoryStream(raw)) using (Image im = Image.FromStream(ms)) { aw = im.Width; ah = im.Height; } } catch { } return dw + "x" + dh + "|" + aw + "x" + ah; } return "无图"; } finally { doc.Close(); } } public static int Run(string dir) { if (string.IsNullOrEmpty(dir)) dir = Path.Combine(Path.GetTempPath(), "greentool-pdfcompress-selftest"); try { if (Directory.Exists(dir)) { try { Directory.Delete(dir, true); } catch { } } Directory.CreateDirectory(dir); _lines.Add("PDF 压缩 自测(" + dir + ")"); // 2400x1600 噪点:明显大于目标长边 1600,压完应该缩成 1600x1067 string jpg = Path.Combine(dir, "noise.jpg"); MakeNoiseJpeg(jpg, 2400, 1600); MakeNoiseJpeg(Path.Combine(dir, "small.jpg"), 400, 300); string src = Path.Combine(dir, "big.pdf"); MakePdf(src, jpg); long before = new FileInfo(src).Length; CheckTrue("造好的样本够大(> 500KB,压缩有的可压)", before > 500 * 1024); string outp = Path.Combine(dir, "big_out.pdf"); PdfCompressForm form = new PdfCompressForm(); form.Compress(src, outp, 1600, 72); CheckTrue("压完产出文件", File.Exists(outp)); long after = new FileInfo(outp).Length; CheckTrue("压完确实更小(" + before / 1024 + "KB → " + after / 1024 + "KB)", after < before); PdfDocument chk = PdfReader.Open(outp, PdfDocumentOpenMode.Import); CheckInt("页数不变(2 页)", chk.PageCount, 2); Check("页面尺寸不变(612x792)", Math.Round(chk.Pages[0].Width.Point) + "x" + Math.Round(chk.Pages[0].Height.Point), "612x792"); chk.Close(); string rep = ImageReport(outp); Check("图按长边 1600 缩、比例不变(字典声明)", rep.Split('|')[0], "1600x1067"); Check("字典尺寸与真实 JPEG 一致(防部分阅读器渲染成噪点)", rep.Split('|')[1], "1600x1067"); // 第 2 页没图,必须原样还在、可打开 PdfDocument chk2 = PdfReader.Open(outp, PdfDocumentOpenMode.Import); Check("没图的第 2 页仍在,尺寸不变(612x792)", Math.Round(chk2.Pages[1].Width.Point) + "x" + Math.Round(chk2.Pages[1].Height.Point), "612x792"); chk2.Close(); // 已经比目标小的图不碰:400x300 的图在图里应保持原尺寸 string small = Path.Combine(dir, "small.pdf"); MakePdf(small, Path.Combine(dir, "small.jpg")); string smallOut = Path.Combine(dir, "small_out.pdf"); form.Compress(small, smallOut, 1600, 72); Check("本来就小于目标长边的图不被放大", ImageReport(smallOut).Split('|')[0], "400x300"); // 只有文字的 PDF:压完不报错、页数不变 bool threw = false; string txtPdf = Path.Combine(dir, "text.pdf"); try { string outp2 = Path.Combine(dir, "text_out.pdf"); PdfCompressForm f2 = new PdfCompressForm(); f2.Compress(small, outp2, 1600, 72); PdfDocument t = PdfReader.Open(outp2, PdfDocumentOpenMode.Import); CheckInt("纯文字 PDF:压完仍是 2 页", t.PageCount, 2); t.Close(); } catch { threw = true; } CheckTrue("纯文字 PDF:压缩过程不抛异常", !threw); // 报错路径 bool threw2 = false; try { new PdfCompressForm().Compress(Path.Combine(dir, "nofile.pdf"), outp, 1600, 72); } catch { threw2 = true; } CheckTrue("文件不存在会报错", threw2); // 源文件不许被就地改 CheckTrue("源文件体积没变", new FileInfo(src).Length == before); } 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-pdfcompress.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } } static class Program { [STAThread] static void Main(string[] args) { if (args != null && args.Length >= 2 && args[0] == "--probe") { Environment.Exit(RunProbe(args[1])); } // 自测:PdfCompress.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 PdfCompressForm()); } // 诊断模式:打印 PDF 里每张图片的过滤器、尺寸、流状态 public static int RunProbe(string path) { StringBuilder log = new StringBuilder(); try { PdfDocument doc = PdfReader.Open(path, PdfDocumentOpenMode.Modify); log.AppendLine("页数=" + doc.PageCount + " 体积=" + new FileInfo(path).Length); for (int pi = 0; pi < doc.PageCount; pi++) { PdfPage page = doc.Pages[pi]; PdfDictionary res = page.Elements.GetDictionary("/Resources"); if (res == null) { log.AppendLine("p" + (pi + 1) + " 无Resources"); continue; } PdfDictionary xo = res.Elements.GetDictionary("/XObject"); if (xo == null) { log.AppendLine("p" + (pi + 1) + " 无XObjects"); continue; } foreach (string key in xo.Elements.Keys) { PdfItem item = xo.Elements[key]; PdfReference r = item as PdfReference; PdfDictionary d = (r != null ? r.Value : item) as PdfDictionary; if (d == null) { log.AppendLine("p" + (pi + 1) + " " + key + " 非字典"); continue; } log.Append("p" + (pi + 1) + " " + key + " sub=" + d.Elements.GetName("/Subtype") + " filter=" + d.Elements.GetName("/Filter") + " " + d.Elements.GetInteger("/Width") + "x" + d.Elements.GetInteger("/Height")); try { byte[] s = d.Stream.Value; log.Append(" streamLen=" + (s == null ? -1 : s.Length)); if (s != null && s.Length >= 2) log.Append(" head=" + s[0].ToString("X2") + s[1].ToString("X2")); } catch (Exception ex) { log.Append(" streamErr=" + ex.GetType().Name + " " + ex.Message); } log.AppendLine(); } } Console.WriteLine(log.ToString()); File.AppendAllText("probe-pdf.txt", log.ToString(), Encoding.UTF8); return 0; } catch (Exception ex) { log.AppendLine("异常: " + ex.GetType().Name + " " + ex.Message); File.AppendAllText("probe-pdf.txt", log.ToString(), Encoding.UTF8); Console.WriteLine(log.ToString()); return 1; } } // 自测:现场造一个「大噪点图 PDF」→ 压缩 → 核对页数、缩到目标边长、字典尺寸与真实 JPEG 一致 public static int RunSelfTest(string dir) { return SelfTest.Run(dir); } } }