说明:

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

项目引用到的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:

界面布局:
源码:

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 图片转PDFpublic 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文件,转换结束会有提示
(转换过的图片将自动移动到对应的文件夹,防止多次转换)

过程展示:


进一步延伸:

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

源码下载:

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

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

  1. Day 3 Linux(目录篇 、文件操作篇 、压缩解压相关命令, 编辑器vi 、编译器gcc 、调试器gdb、 makefile工程管理器初学)

    一.目录篇: 1.文件处理命令:cp 英文原意:copy 语法:cp -rp[源文件或目录][目的目录] 源文件可以同时是多个,即同时复制到多个文件 -r 复制目录 -p保留文件属性,比如文件创建时间 ...

  2. 如何自动翻译整篇PDF文件?教你两种自动翻译方法

    怎么把整篇PDF文件自动翻译呢?PDF文件我们经常会使用,有时候我们在网站上下载一些文件都会是PDF文件格式,遇到一些英文文件我们看不懂,或者是需要将手头上的文件翻译成英文或者是其它语言,我们该怎么翻 ...

  3. Python文件及目录操作(基本文件操作篇)

    ​ 活动地址:CSDN21天学习挑战赛 学习的最大理由是想摆脱平庸,早一天就多一份人生的精彩:迟一天就多一天平庸的困扰. 学习日记 目录 学习日记 一.前言 二.基本文件操作 1.创建和打开文件 2. ...

  4. 怎么翻译PDF文件内容?教你一招轻松翻译整篇PDF文件

    怎么把PDF文件中的内容给翻译成其他语言呢?PDF是很多人在办公或学习中必不可少的文件格式,但当我们收到或者是下载到一份不怎么认识的PDF文件时,想要知道文件具体的内容,我们就需要将文件进行翻译,那么 ...

  5. 将图片直接转换成xml文件_如何将jpg在线转换成pdf?jpg图片可以转换成pdf吗?

    可不要以为jpg就一定只是一张简单的图片,一张图片中可以包含的信息是很多的,除了有景象之外,也可能会有文字,有表格.当然,我们今天要讨论的,并不是一张jpg的图片中可能会存在哪些信息,而是要如何将jp ...

  6. [Python从零到壹] 三.语法基础之文件操作、CSV文件读写及面向对象

    欢迎大家来到"Python从零到壹",在这里我将分享约200篇Python系列文章,带大家一起去学习和玩耍,看看Python这个有趣的世界.所有文章都将结合案例.代码和作者的经验讲 ...

  7. pkpm弹性时程分析计算书怎么出_弹性时程分析——PKPM软件操作篇.pdf

    弹性时程分析--PKPM软件操作篇.pdf PKPM软件弹性时程分析操作小结 操作菜单 1 Satwe分析设计--弹性时程分析 2 常用活动菜单--选波+分析参数+计算+时程分析结果 选波 第一级对话 ...

  8. 读取Java文件到byte数组的三种方式及Java文件操作大全(包括文件加密,String加密)

    读取Java文件到byte数组的三种方式 package zs;import java.io.BufferedInputStream; import java.io.ByteArrayOutputSt ...

  9. php操作外部文件,php文件操作-将其他文件的数据添加到本文件中

    本篇文章的内容是php文件操作-将其他文件的数据添加到本文件中,现在分享给大家,有需要的朋友可以参考一下 GitHub源码 其实我们的程序基于下面的问题写的答案: 有两个文本文件 A.txt B.tx ...

  10. py遍历文件夹合并pdf文件

    以前写了一个遍历文件夹下所有文件夹中pdf文件并合并成一个的代码 folder=os.listdir(dir_path) #遍历文件夹#处理 def merge_pdf(name,file_all,t ...

最新文章

  1. [转] 一个OpenSource的评价图
  2. PM——【1】维护功能位置主数据
  3. 解决datagrid单元格不能设置100%问题
  4. 窗口类的注册生成和消息循环
  5. java windows 取所有任务_Win下,通过Jstack截取Java进程中的堆栈信息
  6. [POJ2157]Maze(DFS)
  7. Linux kernel之SMP初始化
  8. chroot函数使用_PHP chroot()函数与示例
  9. 屏幕距离和坐便转换工具_【软件推荐】你和大神的距离,只差这几个效率工具!...
  10. mybatis association 问题
  11. 用 Doc2Vec 得到文档/段落/句子的向量表达
  12. 如何删除尾随换行符?
  13. CSS(Cascading Style Shee)
  14. 华为BFD的配置规范
  15. python网络爬虫从入门到精通吕云翔pdf_Python 网络爬虫从入门到精通
  16. 人工智能——特征工程思维导图
  17. 计算机专业课程设计收获及总结,课程设计的心得体会
  18. 领导带好团队需要有的3个能力
  19. ps使图片边缘模糊且融入背景色
  20. PowerPMAC技术培训------2、PowerPMAC产品介绍

热门文章

  1. 答题系统 html源码,答题系统.html
  2. 程序员也需要掌握的常用Linux网络命令汇总
  3. 工程师一定要有 “Owner 意识”
  4. Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Access denied for user
  5. 什么是OEM、ODM、OBM
  6. Window环境PHP7使用Protobuf开发详解
  7. 英语作文《健康的重要性》
  8. 选择变色镜片——爱眼护眼
  9. 可靠性评价类毕业论文文献都有哪些?
  10. vue项目报错[Vue warn]: Property “visible“ must be accessed with “$data.visible“ because properties start