C#【文件操作篇】PDF文件和图片互相转换

说明:

直接上程序,大家可以通过程序来学习!

项目引用到的dll:

itextsharp.dll
O2S.Components.PDFRender4NET.dll

引入的命名空间:

using O2S.Components.PDFRender4NET;

using iTextSharp.text;
using iTextSharp.text.pdf;

源码:

源码主要分为三部分:分别为主窗体MainForm、Pdf2Pic.cs、Pic2Pdf.cs,接下来我们一步一步来。

1.主窗体MainForm.cs:

界面布局:
《C#【文件操作篇】PDF文件和图片互相转换》源码:

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System.Windows.Forms;

using iTextSharp.text.pdf;//项目新添加


namespace PDF_Image
{ 
    public partial class MainForm : Form
    { 
        public static string sourcepath = "";//PDF文件源路径
        public static string targetpath = "";//PDF文件转化成Image保存的路径
        public static string movepath = "";//PDF文件转换后移动的路径

        public static string sourcepath1 = "";//Image文件源地址
        public static string targetpath1 = "";//Image文件转换成PDF文件保存的路径
        public static string movepath1 = "";//Image文件转换后移动的路径

        private Thread th_PDFtoImg = null; //PDF转图片线程 
        private Thread th_ImgtoPDF = null; //图片转PDF线程 

        public MainForm()
        { 
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }

        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        { 
            sourcepath = txt_PDF1.Text = AppDomain.CurrentDomain.BaseDirectory + @"PDF1";
            targetpath = txt_PDF2.Text = AppDomain.CurrentDomain.BaseDirectory + @"Image1";
            movepath = txt_PDF3.Text = AppDomain.CurrentDomain.BaseDirectory + @"Endswap1";

            sourcepath1 = txt_Image1.Text = AppDomain.CurrentDomain.BaseDirectory + @"Image2";
            targetpath1 = txt_Image2.Text = AppDomain.CurrentDomain.BaseDirectory + @"PDF2";
            movepath1 = txt_Image3.Text = AppDomain.CurrentDomain.BaseDirectory + @"Endswap2";
        }    
        #region PDF转图片
        public void PDFtoImage()
        { 
            Files_Copy(sourcepath);
        }
        /// <summary>
        /// 显示文件夹下所有子文件夹及文件的名称
        /// </summary>
        /// <param name="Sdir">文件夹目录</param>
        private void Files_Copy(string Sdir)
        { 
            DirectoryInfo dir = new DirectoryInfo(Sdir);
            try

            { 
                if (dir.Exists)//判断所指的文件或文件夹是否存在
                { 
                    DirectoryInfo dirD = dir as DirectoryInfo;//如果给定参数不是文件夹则退出
                    if (dirD != null)//判断文件夹是否为空
                    { 
                        FileSystemInfo[] files = dirD.GetFileSystemInfos();//获取文件夹中所有文件和文件夹
                        if (files.Length == 0)//判断文件夹是否为空
                        { 
                            MessageBox.Show("There are no files in the current folder!");
                            //Thread.Sleep(10000); 
                        }
                        else
                        { 
                            //对单个FileSystemInfo进行判断,如果是文件夹则进行递归操作
                            foreach (FileSystemInfo FSys in files)
                            { 
                                FileInfo file = FSys as FileInfo;
                                if (file != null)//如果是文件的话,进行文件的复制操作
                                { 
                                    FileInfo SFInfo = new FileInfo(file.DirectoryName + "\\" + file.Name);//获取文件所在的原始路径
                                    string pdfPath = SFInfo.FullName;
                                    PdfReader reader = new PdfReader(pdfPath);
                                    int iPageNum = reader.NumberOfPages;
                                    Pdf2Pic.ConvertPDF2Image(pdfPath, targetpath + "\\", DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_", 1, iPageNum, ImageFormat.Png, Pdf2Pic.Definition.Ten);
                                    
                                    //转换好后移动PDF文件
                                    if (File.Exists(movepath + "\\" + file.Name))
                                    { 
                                        //参数1:要删除的文件路径
                                        File.Delete(movepath + "\\" + file.Name);
                                    }
                                    File.Move(pdfPath, movepath + "\\" + file.Name);
                                }
                            }
                            MessageBox.Show("\"PDF to Image\" has finished!");
                        }
                    }
                }
                btn_PdfStart.Enabled = true;
                lbl_Pdf.Text = "End";
                lbl_Pdf.ForeColor = Color.Red;
            }
            catch (Exception ex)
            { 
                //MessageBox.Show(ex.Message);
                btn_PdfStart.Enabled = true;
                lbl_Pdf.Text = "End";
                lbl_Pdf.ForeColor = Color.Red;
                return;
            }
        }
        private void btn_PDF1_Click(object sender, EventArgs e)
        { 
            System.Diagnostics.Process.Start("explorer.exe", txt_PDF1.Text);
        }

        private void btn_PDF2_Click(object sender, EventArgs e)
        { 
            System.Diagnostics.Process.Start("explorer.exe", txt_PDF2.Text);
        }

        private void btn_PDF3_Click(object sender, EventArgs e)
        { 
            System.Diagnostics.Process.Start("explorer.exe", txt_PDF3.Text);
        }
        private void btn_PdfStart_Click(object sender, EventArgs e)
        { 
            if (th_PDFtoImg != null)
            { 
                th_PDFtoImg.Abort();
                th_PDFtoImg = null;
            }

            btn_PdfStart.Enabled = false;

            th_PDFtoImg = new Thread(new ThreadStart(PDFtoImage));   //创建一个线程
            th_PDFtoImg.IsBackground = true;
            th_PDFtoImg.Start(); //执行当前线程
            lbl_Pdf.Text = "Running...";
            lbl_Pdf.ForeColor = Color.Lime;
        }

        private void btn_PdfStop_Click(object sender, EventArgs e)
        { 
            if (th_PDFtoImg != null)
            { 
                th_PDFtoImg.Abort();
                th_PDFtoImg = null;
                btn_PdfStart.Enabled = true;
                lbl_Pdf.Text = "End";
                lbl_Pdf.ForeColor = Color.Red;
            }

        }

        #endregion

        #region 图片转PDF
        public void ImagetoPDF()
        { 
            Files_Copy1(sourcepath1);
        }

        private void Files_Copy1(string Sdir)
        { 
            DirectoryInfo dir = new DirectoryInfo(Sdir);
            try
            { 
                if (dir.Exists)//判断所指的文件或文件夹是否存在
                { 
                    DirectoryInfo dirD = dir as DirectoryInfo;//如果给定参数不是文件夹则退出
                    if (dirD != null)//判断文件夹是否为空
                    { 
                        FileSystemInfo[] files = dirD.GetFileSystemInfos();//获取文件夹中所有文件和文件夹
                        if (files.Length == 0)//判断文件夹是否为空
                        { 
                            MessageBox.Show("There are no files in the current folder!");
                            //Thread.Sleep(10000); 
                        }
                        else
                        { 
                            //对单个FileSystemInfo进行判断,如果是文件夹则进行递归操作
                            foreach (FileSystemInfo FSys in files)
                            { 
                                FileInfo file = FSys as FileInfo;
                                if (file != null)//如果是文件的话,进行文件的复制操作
                                { 
                                    FileInfo SFInfo = new FileInfo(file.DirectoryName + "\\" + file.Name);//获取文件所在的原始路径
                                    string frompath = SFInfo.FullName;
                                    string oldname = file.Name;
                                    string newfileName;
                                    if (oldname.Contains("Png"))
                                    { 
                                        newfileName = oldname.Replace(".Png", ".pdf");
                                        if (File.Exists(targetpath1 + "\\" + newfileName))
                                        { 
                                            //参数1:要删除的文件路径
                                            File.Delete(targetpath1 + "\\" + newfileName);
                                        }
                                        Pic2Pdf.ImageToPdf(frompath, targetpath1 + "\\" + newfileName);
                                    }
                                    else if (oldname.Contains("png"))
                                    { 
                                        newfileName = oldname.Replace(".png", ".pdf");
                                        if (File.Exists(targetpath1 + "\\" + newfileName))
                                        { 
                                            //参数1:要删除的文件路径
                                            File.Delete(targetpath1 + "\\" + newfileName);
                                        }
                                        Pic2Pdf.ImageToPdf(frompath, targetpath1 + "\\" + newfileName);
                                    }
                                    if (File.Exists(movepath1 + "\\" + file.Name))
                                    { 
                                        //参数1:要删除的文件路径
                                        File.Delete(movepath1 + "\\" + file.Name);
                                    }
                                    File.Move(frompath, movepath1 + "\\" + file.Name);

                                }
                            }
                            MessageBox.Show("\"Image to PDF\" has finished!");
                        }

                    }
                }
                btn_ImageStart.Enabled = true;
                lbl_Image.Text = "End";
                lbl_Image.ForeColor = Color.Red;

            }
            catch (Exception ex)
            { 
                //MessageBox.Show(ex.Message);
                btn_ImageStart.Enabled = true;
                lbl_Image.Text = "End";
                lbl_Image.ForeColor = Color.Red;
                return;
            }
        }
        private void btn_Image1_Click(object sender, EventArgs e)
        { 
            System.Diagnostics.Process.Start("explorer.exe", txt_Image1.Text);
        }

        private void btn_Image2_Click(object sender, EventArgs e)
        { 
            System.Diagnostics.Process.Start("explorer.exe", txt_Image2.Text);
        }

        private void btn_Image3_Click(object sender, EventArgs e)
        { 
            System.Diagnostics.Process.Start("explorer.exe", txt_Image3.Text);
        }
        private void btn_ImageStart_Click(object sender, EventArgs e)
        { 
            if (th_ImgtoPDF != null)
            { 
                th_ImgtoPDF.Abort();
                th_ImgtoPDF = null;
            }
            btn_ImageStart.Enabled = false;
            th_ImgtoPDF = new Thread(new ThreadStart(ImagetoPDF));   //创建一个线程
            th_ImgtoPDF.IsBackground = true;
            th_ImgtoPDF.Start(); //执行当前线程
                                 //Pic2Pdf.ImageToPdf(frompath, topath);
                                 //MessageBox.Show("转换成功1");
            lbl_Image.Text = "Running...";
            lbl_Image.ForeColor = Color.Lime;
       
        }

        private void btn_ImageStop_Click(object sender, EventArgs e)
        { 
            if (th_ImgtoPDF != null)
            { 
                th_ImgtoPDF.Abort();
                th_ImgtoPDF = null;
                btn_ImageStart.Enabled = true;
                lbl_Image.Text = "End";
                lbl_Image.ForeColor = Color.Red;
            }
        }
        #endregion
    }
}

2.Pdf2Pic.cs:

源码:

using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

using O2S.Components.PDFRender4NET;//添加的
namespace PDF_Image
{ 
	public static class Pdf2Pic
	{ 
        public enum Definition
        { 
            One = 1, Two = 2, Three = 3, Four = 4, Five = 5,
            Six = 6, Seven = 7, Eight = 8, Nine = 9, Ten = 10
        }
        /// <summary>
        /// 将PDF文档转换为图片的方法
        /// </summary>
        /// <param name="pdfInputPath">PDF文件路径</param>
        /// <param name="imageOutputPath">图片输出路径</param>
        /// <param name="imageName">生成图片的名字</param>
        /// <param name="startPageNum">从PDF文档的第几页开始转换</param>
        /// <param name="endPageNum">从PDF文档的第几页开始停止转换</param>
        /// <param name="imageFormat">设置所需图片格式</param>
        /// <param name="definition">设置图片的清晰度,数字越大越清晰</param>
        public static void ConvertPDF2Image(string pdfInputPath, string imageOutputPath,
            string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, Definition definition)
        { 
            PDFFile pdfFile = PDFFile.Open(pdfInputPath);
            if (!Directory.Exists(imageOutputPath))
            { 
                Directory.CreateDirectory(imageOutputPath);
            }
            if (startPageNum <= 0)
            { 
                startPageNum = 1;
            }
            if (endPageNum > pdfFile.PageCount)
            { 
                endPageNum = pdfFile.PageCount;
            }
            if (startPageNum > endPageNum)
            { 
                int tempPageNum = startPageNum;
                startPageNum = endPageNum;
                endPageNum = startPageNum;
            }
            for (int i = startPageNum; i <= endPageNum; i++)
            { 
                Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * (int)definition);
                pageImage.Save(imageOutputPath + imageName + i.ToString("000") + "." + imageFormat.ToString(), imageFormat);
                pageImage.Dispose();
            }
            pdfFile.Dispose();
        }
    }
}

3.Pic2Pdf.cs:

源码:

using System.IO;

using iTextSharp.text;//添加的
using iTextSharp.text.pdf;//添加的

namespace PDF_Image
{ 
	public static class Pic2Pdf
	{ 
		public static void ImageToPdf(string frompath, string topath)
		{ 
			System.Drawing.Image pic = System.Drawing.Image.FromFile(frompath);//strFilePath是该图片的绝对路径
			int intWidth = pic.Width;//长度像素值
			int intHeight = pic.Height;//高度像素值 
			pic.Dispose();
			iTextSharp.text.Rectangle pagesize = new iTextSharp.text.Rectangle(intWidth, intHeight);
			Document pdfdoc = new Document(pagesize);//建立Document对象的实例,并设置Document的大小与边距。

			PdfWriter writer = PdfWriter.GetInstance(pdfdoc, new FileStream(topath, FileMode.Create)); //建立一个Pdf Writer对象Writer与document对象关联,通过Writer可以将文档写入到磁盘中。
			pdfdoc.Open(); //打开文档。
			PdfContentByte cb = writer.DirectContent;

			iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(frompath);
			img.SetAbsolutePosition(0, 0);
            cb.AddImage(img); //向文档中添加图像数据。
			pdfdoc.NewPage();

			pdfdoc.Close(); //关闭文档,将缓冲区的内容写入磁盘以保存文件。
		}

	}
}

运行效果:

可实现功能:
1.PDF转换成图片:
将PDF文件按页转换成.Png图片格式,转换结束会有提示
(转换过的文件将自动移动到对应的文件夹,防止多次转换)

2.图片转换成PDF:
可以将单张照片(.Png/.png)分别转换成.pdf文件,转换结束会有提示
(转换过的图片将自动移动到对应的文件夹,防止多次转换)

过程展示:
《C#【文件操作篇】PDF文件和图片互相转换》《C#【文件操作篇】PDF文件和图片互相转换》
《C#【文件操作篇】PDF文件和图片互相转换》《C#【文件操作篇】PDF文件和图片互相转换》
《C#【文件操作篇】PDF文件和图片互相转换》

进一步延伸:

大家可以根据此源码,进一步扩展生成的图片格式(例.jpg等其他格式),以及转换成PDF文件的源图片的格式(例.jpg等其他格式),扩展程序的通用性。
另外,可以考虑如何把多个PDF文件进行合并。

源码下载:

https://blog.csdn.net/sinat_40003796?spm=1000.2115.3001.5343

    原文作者:明如正午
    原文地址: https://blog.csdn.net/sinat_40003796/article/details/123577455
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞