分享一个C#开发的Pdf转换工具,可以轻松实现转图片与word的转换
				
									
					
					
						 | 
						
							
							admin 
							
							
								2025年7月25日 12:53
								本文热度 1279
							
							 
						 | 
					 
					 
				 
				此工具可以轻松的实现将pdf文件按照顺序转换为图片文件与word文档,支持设置水印与清晰度操作也很简单,首先选择要转换的pdf文件,然后设置转换后保存的目录,提交等待即可。
 
1.工具截图           using Aspose.Pdf;using Aspose.Pdf.Generator;using Aspose.Pdf.Text;using System;using System.Collections.Concurrent;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Diagnostics;using System.Drawing;using System.IO;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;using System.Windows.Forms;using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button;
 namespace WindowsPdfToImg{    public partial class qyx : Form    {        public qyx()        {
             InitializeComponent();        }
         private void label1_Click(object sender, EventArgs e)        {
         }
                                                 private void button1_Click(object sender, EventArgs e)        {                        OpenFileDialog ofd = new OpenFileDialog();            ofd.Title = "选择文件";            ofd.Multiselect = true;            ofd.Filter = "(*.pdf)|*.pdf";
                         this.files.Text = "";            this.result.Text = "";            this.errorMsg.Text = "";
                         if (ofd.ShowDialog() == DialogResult.OK)            {
                 foreach (var item in ofd.FileNames)                {                    this.files.Text += item + "\r\n";                }            }        }
         private void Form1_Load(object sender, EventArgs e)        {                        img_radio.Checked = true;
             this.files.AllowDrop = true;
 
         }
                                                 private void selectDirectory_Click(object sender, EventArgs e)        {            FolderBrowserDialog fbd = new FolderBrowserDialog();            fbd.RootFolder = System.Environment.SpecialFolder.Desktop;            fbd.ShowNewFolderButton = true;            fbd.Description = "选择目录";
             if (fbd.ShowDialog() == DialogResult.OK)            {                this.directory.Text = fbd.SelectedPath.ToString();            }
         }
         private void label1_Click_1(object sender, EventArgs e)        {
         }
         private void files_TextChanged(object sender, EventArgs e)        {
         }
         private void files_DragEnter(object sender, DragEventArgs e)        {            e.Effect = DragDropEffects.All;        }
         private void files_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)        {            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);            foreach (string file in files)            {                if (Path.GetExtension(file) == ".pdf")                  {                    this.files.Text += file + "\r\n";                }            }        }
         private void label2_Click(object sender, EventArgs e)        {
         }
                                                 private void submit_Click(object sender, EventArgs e)        {            var file = this.files.Text;
 
             result.Text = "";            errorMsg.Text = "";            pdf_text.Text = "";
             if (string.IsNullOrEmpty(file))            {                MessageBox.Show("请选择要转换的Pdf文件!");                return;            }
             var directory = this.directory.Text;            if (string.IsNullOrEmpty(directory))            {                MessageBox.Show("请设置保存目录!");                return;            }
             var timeRadio = this.timeRadio.Checked;            var wordsRadio = this.wordsRadio.Checked;
                                                             
                         var img_radio = this.img_radio.Checked;
                         var word_radio = this.word_radio.Checked;
 
 
 
             this.submit.Enabled = false;            this.btnSelect.Enabled = false;            this.selectDirectory.Enabled = false;
             var dateTimePicker1 = this.dateTimePicker1.Value;            var watermarkWord = this.watermarkWord.Text;
             var text = "";            if (timeRadio)            {                text = dateTimePicker1.ToString();            }            else if (wordsRadio)            {                text = watermarkWord;            }
                         var type = 0;
             if (img_radio)            {                type = 1;            }            else if (word_radio)            {                type = 2;            }
 
             foreach (var i in file.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries))            {                var m = new Files                {                    Path = i,                    Text = text,                    Directory = directory,                    Name = "",                    Type = type                };
                 queue.Enqueue(m);            }
                         StartQueue();        }
 
 
         private void close_Click(object sender, EventArgs e)        {            Application.Exit();        }
         private void timeRadio_CheckedChanged(object sender, EventArgs e)        {
         }
         private void groupBox1_Enter(object sender, EventArgs e)        {
         }
         private void groupBox1_Enter_1(object sender, EventArgs e)        {
         }
                                                         public void CreatImg(string file, string text, string directory)        {            Stopwatch sw = new Stopwatch();            sw.Start();
 
             var qualityText = this.resolutionText.Text;            var quality = 80;
             var resolutionText = this.resolutionText.Text;            var reso = 80;
             if (!string.IsNullOrEmpty(qualityText))            {                quality = Convert.ToInt32(qualityText);
                 if (quality >= 128) { quality = 128; }            }
             if (!string.IsNullOrEmpty(resolutionText))            {                reso = Convert.ToInt32(resolutionText);            }
             Directory.CreateDirectory(directory);
             string filename = System.IO.Path.GetFileName(file);            string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(file);
                         Directory.CreateDirectory(directory + "\\" + fileNameWithoutExtension);
                         var imageOutputDirPath = directory;
                         var resolution = new Aspose.Pdf.Devices.Resolution(reso);
                         var pdf = new Aspose.Pdf.Document(file);
                         var count = pdf.Pages.Count;            this.progressBar1.Value = 0;            this.progressBar1.Style = ProgressBarStyle.Blocks;            this.progressBar1.Maximum = count;            this.progressBar1.Minimum = 0;            this.progressBar1.MarqueeAnimationSpeed = 100;            this.progressBar1.Step = 1;            this.lbl_progress.Text = "0%";            this.lbl_progress.Refresh();
 
 
             this.Invoke(new Action(() =>            {                result.Text += $"文件{file}已经开始处理{DateTime.Now},";            }));
 
             Page testpage = pdf.Pages[1];                        TextStamp textStamp = new TextStamp(text);
                         textStamp.XIndent = (testpage.PageInfo.Width / 2) - 200;            textStamp.YIndent = (testpage.PageInfo.Height / 2);
                         textStamp.TextState.Font = FontRepository.FindFont("SimSun");            textStamp.TextState.FontSize = 40.0F;            textStamp.TextState.FontStyle = FontStyles.Italic;            textStamp.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Gray);            textStamp.Opacity = 50;
                         textStamp.setStampId(123456);
             
 
             Document doc = new Document();            Page page = doc.Pages.Add();
             try            {                var i = 0;                foreach (Aspose.Pdf.Page item in pdf.Pages)                {                    i++;
                     this.Invoke(new Action(() =>                    {                        pdf_text.Text = $"正在转换文件:《{filename}》,总共{count}页,当前第{i}页,还剩余{count - i}页";                    }));
                     var filename2 = imageOutputDirPath + "/" + fileNameWithoutExtension + "/" + i + ".jpeg";
                                         Aspose.Pdf.Image image = new Aspose.Pdf.Image();
                                         item.AddStamp(textStamp);
                     new Aspose.Pdf.Devices.JpegDevice(resolution, quality).Process(item, filename2);
                                                             image.File = filename2; 
                     System.Drawing.Image srcImage = System.Drawing.Image.FromFile(filename2);                    int h = srcImage.Height;                    int w = srcImage.Width;
                                         
                     page.PageInfo.Height = (h);                    page.PageInfo.Width = (w);                    page.PageInfo.Margin.Bottom = (0);                    page.PageInfo.Margin.Top = (0);                    page.PageInfo.Margin.Right = (0);                    page.PageInfo.Margin.Left = (0);
                                         page.Paragraphs.Add(image);
                                         this.progressBar1.PerformStep();                                        double dCount = count, dProg = this.progressBar1.Value;                    this.lbl_progress.Text = Math.Round((dProg / dCount) * 100).ToString() + "%";                }
                 this.Invoke(new Action(() =>                {                    pdf_text.Text += $",新文件正在保存中...";                }));
                 var newFileName = fileNameWithoutExtension + "__已处理.pdf";                doc.Save(imageOutputDirPath + "/" + newFileName);
 
 
                 this.Invoke(new Action(() =>                {                    pdf_text.Text += $",新文件已经保存成功!";                }));
                 sw.Stop();                this.Invoke(new Action(() =>                {                    result.Text += $"已经处理完成,总共{i}页,{DateTime.Now},耗时{Tools.RevertToTime(sw.ElapsedMilliseconds)}\r\n";                }));
             }            catch (Exception ex)            {                this.Invoke(new Action(() =>                {                    errorMsg.Text += $"文件{file}异常:{ex.ToString()}\r\n";                }));
                 this.submit.Enabled = true;                this.btnSelect.Enabled = true;                this.selectDirectory.Enabled = true;            }
 
 
 
                                                             
 
             GC.Collect();        }
                                                 public void CreatWordTest(string file, string directory)        {                        Stopwatch sw = new Stopwatch();            sw.Start();
                         Directory.CreateDirectory(directory);
             string filename = System.IO.Path.GetFileName(file);            string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(file);
                         Directory.CreateDirectory(directory + "\\" + fileNameWithoutExtension);
                         var wordOutputDirPath = directory;
 
             try            {                                var pdf = new Aspose.Pdf.Document(file);
                                 var count = pdf.Pages.Count;                this.progressBar1.Value = 0;                this.progressBar1.Style = ProgressBarStyle.Blocks;                this.progressBar1.Maximum = count;                this.progressBar1.Minimum = 0;                this.progressBar1.MarqueeAnimationSpeed = 100;                this.progressBar1.Step = 1;                this.lbl_progress.Text = "0%";                this.lbl_progress.Refresh();
 
                 this.Invoke(new Action(() =>                {                    result.Text += $"文件{file}已经开始处理{DateTime.Now},";                }));
 
                 var filename2 = wordOutputDirPath + "/" + fileNameWithoutExtension + "/" + fileNameWithoutExtension + "_已转换.docx";
                                 this.progressBar1.PerformStep();                                double dCount = count, dProg = this.progressBar1.Value;                this.lbl_progress.Text = Math.Round((dProg / dCount) * 100).ToString() + "%";
                                 pdf.Save(filename2, SaveFormat.DocX);
                 this.Invoke(new Action(() =>                {                    pdf_text.Text += $",新文件已经保存成功!";                }));
 
 
 
                 sw.Stop();                this.Invoke(new Action(() =>                {                    result.Text += $"已经处理完成,{DateTime.Now},耗时{Tools.RevertToTime(sw.ElapsedMilliseconds)}\r\n";                }));            }            catch (Exception ex)            {
                 this.Invoke(new Action(() =>                {                    errorMsg.Text += $"文件{file}异常:{ex.ToString()}\r\n";                }));
                 this.submit.Enabled = true;                this.btnSelect.Enabled = true;                this.selectDirectory.Enabled = true;            }
 
             GC.Collect();
         }
 
                                                 public void CreatWord(string file, string directory)        {                        Stopwatch sw = new Stopwatch();            sw.Start();
             try            {                                string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(file);                string outputDir = Path.Combine(directory, fileNameWithoutExtension);                Directory.CreateDirectory(outputDir);  
                                 var wordOutputPath = Path.Combine(outputDir, $"{fileNameWithoutExtension}_已转换.docx");
                                 var pdf = new Aspose.Pdf.Document(file);
                                 var pageCount = pdf.Pages.Count;                this.progressBar1.Invoke(new Action(() =>                {                    this.progressBar1.Value = 0;                    this.progressBar1.Style = ProgressBarStyle.Blocks;                    this.progressBar1.Maximum = pageCount + 100;                     this.progressBar1.Minimum = 0;                    this.progressBar1.MarqueeAnimationSpeed = 100;                    this.progressBar1.Step = 1;                    this.lbl_progress.Text = "0%";                    this.lbl_progress.Refresh();                }));
                                 this.Invoke(new Action(() =>                {                    result.Text += $"文件{file}已经开始处理{DateTime.Now},";                }));
                                 int updateInterval = Math.Max(1, pageCount / 100);                for (int i = 1; i <= pageCount; i++)                {                                        if (i % updateInterval == 0)                    {                        this.progressBar1.Invoke(new Action(() =>                        {                            this.progressBar1.Value = i;                            double progressPercentage = (double)i / pageCount * 100;                            this.lbl_progress.Text = $"{Math.Round(progressPercentage)}%";                        }));                    }                }
                                 this.progressBar1.Invoke(new Action(() =>                {                    this.progressBar1.Value = pageCount;                 }));
                                 pdf.Save(wordOutputPath, SaveFormat.DocX);
                                 for (int i = pageCount; i <= pageCount + 100; i++)                 {                    int progress = i;                    this.progressBar1.Invoke(new Action(() =>                    {                        this.progressBar1.Value = progress;                        double progressPercentage = (double)progress / (pageCount + 100) * 100;                        this.lbl_progress.Text = $"{Math.Round(progressPercentage)}%";                    }));
                                         Thread.Sleep(10);                }
                 this.Invoke(new Action(() =>                {                    pdf_text.Text += $",新文件已经保存成功!";                }));
                                 sw.Stop();                this.Invoke(new Action(() =>                {                    result.Text += $"已经处理完成,{DateTime.Now},耗时{Tools.RevertToTime(sw.ElapsedMilliseconds)}\r\n";                }));            }            catch (Exception ex)            {                this.Invoke(new Action(() =>                {                    errorMsg.Text += $"文件{file}异常:{ex.ToString()}\r\n";                }));            }            finally            {                                this.Invoke(new Action(() =>                {                    submit.Enabled = true;                    btnSelect.Enabled = true;                    selectDirectory.Enabled = true;                }));            }        }
 
 
         private void result_TextChanged(object sender, EventArgs e)        {
         }
         #region 队列相关        private static ConcurrentQueue<Files> queue = new ConcurrentQueue<Files>();        private static bool hasQueue = false; 
 
                                 private void StartQueue()        {            if (hasQueue == false)            {
                 hasQueue = true;                System.Threading.Tasks.Task.Run(() =>                {                    QueueEach_Pdf();                });            }        }
                                         public async void QueueEach_Pdf()        {            Stopwatch sw = new Stopwatch();            sw.Start();
             while (hasQueue)            {                if (queue.Count > 0)                {                    List<Files> list = new List<Files>();
                     try                    {                        this.Invoke(new Action(() =>                        {                            result.Text = $"文件处理开始,总共{queue.Count}个文件,当前时间{DateTime.Now}\r\n";                        }));
                         var count = queue.Count;                        for (int i = 0; i < count; i++)                        {                            Files item = new Files();                            bool dequeueSuccesful = false;                            dequeueSuccesful = queue.TryDequeue(out item);
                             if (dequeueSuccesful)                            {                                                                if (item.Type == 1)                                {                                    CreatImg(item.Path, item.Text, item.Directory);                                }                                else if (item.Type == 2)                                {                                    CreatWord(item.Path,  item.Directory);                                }
 
                             }                        }
                         sw.Stop();                        this.Invoke(new Action(() =>                        {                            result.Text += $"文件处理结束{DateTime.Now},耗时{Tools.RevertToTime(sw.ElapsedMilliseconds)}\r\n";                        }));
                         this.submit.Enabled = true;                        this.btnSelect.Enabled = true;                        this.selectDirectory.Enabled = true;                    }                    catch (Exception ex)                    {
                         this.Invoke(new Action(() =>                        {                            errorMsg.Text += $"队列执行异常:{ex.ToString()}\r\n";                        }));
                         this.submit.Enabled = true;                        this.btnSelect.Enabled = true;                        this.selectDirectory.Enabled = true;                    }                }            }        }
 
         #endregion
         private void files_DockChanged(object sender, EventArgs e)        {
         }
         private void label5_Click(object sender, EventArgs e)        {
         }
         private void progressBar1_Click(object sender, EventArgs e)        {
         }
         private void lbl_progress_Click(object sender, EventArgs e)        {
         }
         private void progressBar2_Click(object sender, EventArgs e)        {
         }
         private void textBox1_TextChanged(object sender, EventArgs e)        {
         }
                                                 private void textBox1_KeyPress(object sender, KeyPressEventArgs e)        {                        if (!Char.IsDigit(e.KeyChar) && e.KeyChar != 8 &&          e.KeyChar != 1 && e.KeyChar != 3 && e.KeyChar != 22)            {                e.Handled = true;            }        }
         private void word_radio_CheckedChanged(object sender, EventArgs e)        {
         }
         private void wordsRadio_CheckedChanged(object sender, EventArgs e)        {
         }
         private void panel1_Paint(object sender, PaintEventArgs e)        {
         }    }} 
阅读原文:原文链接 
 该文章在 2025/7/25 14:55:05 编辑过
  
			 
		 | 
		
			
			
		 |