C#中PDF转文本/可搜索PDF工具的按钮功能重构及变量复用问题
优化重构方案
核心问题分析
你的代码重复冗余主要来自三个方面:
- 重复创建
OpenFileDialog并配置筛选器 - 重复初始化
IronTesseract和设置LicenseKey Result是按钮事件的局部变量,无法跨方法访问
以下是分步优化方案:
1. 提取公共方法与类级字段
- 新增私有字段
_ocrResult存储OCR结果,让所有按钮事件可访问 - 提取打开PDF文件的公共方法
SelectPdfFile() - 提取执行OCR的公共方法
PerformOcr(string filePath) - 将LicenseKey初始化移到构造函数,避免重复设置
2. 重构后的完整代码
using IronOcr; using System; using System.Windows.Forms; namespace ocr { public partial class Form1 : Form { // 类级字段存储OCR结果,供所有按钮事件复用 private OcrResult _ocrResult; private readonly IronTesseract _tesseract; public Form1() { InitializeComponent(); // 仅初始化一次OCR实例和LicenseKey IronOcr.License.LicenseKey = "SOMELICENSEKEY"; _tesseract = new IronTesseract(); } // 提取公共的PDF文件选择逻辑 private string SelectPdfFile() { using var ofd = new OpenFileDialog(); ofd.Filter = "pdf files (*.pdf)|*.pdf|All Files (*.*)|*.*"; return ofd.ShowDialog() == DialogResult.OK ? ofd.FileName : null; } // 提取公共的OCR执行逻辑 private OcrResult PerformOcr(string filePath) { if (string.IsNullOrEmpty(filePath)) return null; using var input = new OcrInput(); input.AddPdf(filePath, "password"); return _tesseract.Read(input); } private void button1_Click(object sender, EventArgs e) { var filePath = SelectPdfFile(); if (filePath == null) return; textBox1.Text = filePath; _ocrResult = PerformOcr(filePath); if (_ocrResult != null) { Console.WriteLine(_ocrResult.Text); richTextBox1.Text = _ocrResult.Text; } } private void button2_Click(object sender, EventArgs e) { // 优先复用已有的OCR结果,没有则重新选择文件执行OCR if (_ocrResult == null) { var filePath = SelectPdfFile(); if (filePath == null) return; textBox1.Text = filePath; _ocrResult = PerformOcr(filePath); } _ocrResult?.SaveAsTextFile("pdf.txt"); } private void button3_Click(object sender, EventArgs e) { // 同button2逻辑,复用已有结果或重新生成 if (_ocrResult == null) { var filePath = SelectPdfFile(); if (filePath == null) return; textBox1.Text = filePath; _ocrResult = PerformOcr(filePath); } _ocrResult?.SaveAsSearchablePdf("pdfpesquisavel.pdf"); } } }
3. 关键优化点说明
- 减少重复代码:把文件选择、OCR执行的通用逻辑抽离,避免三次重复编写
- 结果复用:通过类字段
_ocrResult存储OCR结果,button2/button3可以直接复用,无需重复执行OCR - 资源优化:
IronTesseract实例只初始化一次,LicenseKey只设置一次,提升性能 - 空值安全:添加空值判断,避免空引用异常
内容的提问来源于stack exchange,提问作者Julio Cezar
相关产品推荐
相关产品推荐

