当前位置:网站首页>C [document operation] PDF files and pictures are converted to each other
C [document operation] PDF files and pictures are converted to each other
2022-04-23 06:39:00 【Tomorrow is like noon】
explain :
Go straight to the program , You can learn through the program !
Project references dll:
itextsharp.dll
O2S.Components.PDFRender4NET.dll
Introduced namespace :
using O2S.Components.PDFRender4NET;
using iTextSharp.text;
using iTextSharp.text.pdf;
Source code :
The source code is mainly divided into three parts : They are the main forms MainForm、Pdf2Pic.cs、Pic2Pdf.cs, Next, let's step by step .
1. Main form MainForm.cs:
Interface layout :
Source code :
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using iTextSharp.text.pdf;// New item added
namespace PDF_Image
{
public partial class MainForm : Form
{
public static string sourcepath = "";//PDF File source path
public static string targetpath = "";//PDF File to Image Saved path
public static string movepath = "";//PDF The path to move after file conversion
public static string sourcepath1 = "";//Image File source address
public static string targetpath1 = "";//Image File conversion to PDF The path of file saving
public static string movepath1 = "";//Image The path to move after file conversion
private Thread th_PDFtoImg = null; //PDF Turn picture thread
private Thread th_ImgtoPDF = null; // Picture turn PDF Threads
public MainForm()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
/// <summary>
/// Form loading
/// </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 Turn picture
public void PDFtoImage()
{
Files_Copy(sourcepath);
}
/// <summary>
/// Displays the names of all subfolders and files under the folder
/// </summary>
/// <param name="Sdir"> Folder Directory </param>
private void Files_Copy(string Sdir)
{
DirectoryInfo dir = new DirectoryInfo(Sdir);
try
{
if (dir.Exists)// Determine whether the file or folder you are referring to exists
{
DirectoryInfo dirD = dir as DirectoryInfo;// If the given parameter is not a folder, exit
if (dirD != null)// Determine if the folder is empty
{
FileSystemInfo[] files = dirD.GetFileSystemInfos();// Get all files and folders in the folder
if (files.Length == 0)// Determine if the folder is empty
{
MessageBox.Show("There are no files in the current folder!");
//Thread.Sleep(10000);
}
else
{
// For single FileSystemInfo Judge , If it is a folder, perform recursive operation
foreach (FileSystemInfo FSys in files)
{
FileInfo file = FSys as FileInfo;
if (file != null)// If it's a file , Copy files
{
FileInfo SFInfo = new FileInfo(file.DirectoryName + "\\" + file.Name);// Get the original path where the file is located
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);
// Move after conversion PDF file
if (File.Exists(movepath + "\\" + file.Name))
{
// Parameters 1: File path to delete
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)); // Create a thread
th_PDFtoImg.IsBackground = true;
th_PDFtoImg.Start(); // Execute the current thread
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 Picture turn PDF
public void ImagetoPDF()
{
Files_Copy1(sourcepath1);
}
private void Files_Copy1(string Sdir)
{
DirectoryInfo dir = new DirectoryInfo(Sdir);
try
{
if (dir.Exists)// Determine whether the file or folder you are referring to exists
{
DirectoryInfo dirD = dir as DirectoryInfo;// If the given parameter is not a folder, exit
if (dirD != null)// Determine if the folder is empty
{
FileSystemInfo[] files = dirD.GetFileSystemInfos();// Get all files and folders in the folder
if (files.Length == 0)// Determine if the folder is empty
{
MessageBox.Show("There are no files in the current folder!");
//Thread.Sleep(10000);
}
else
{
// For single FileSystemInfo Judge , If it is a folder, perform recursive operation
foreach (FileSystemInfo FSys in files)
{
FileInfo file = FSys as FileInfo;
if (file != null)// If it's a file , Copy files
{
FileInfo SFInfo = new FileInfo(file.DirectoryName + "\\" + file.Name);// Get the original path where the file is located
string frompath = SFInfo.FullName;
string oldname = file.Name;
string newfileName;
if (oldname.Contains("Png"))
{
newfileName = oldname.Replace(".Png", ".pdf");
if (File.Exists(targetpath1 + "\\" + newfileName))
{
// Parameters 1: File path to delete
File.Delete(targetpath1 + "\\" + newfileName);
}
Pic2Pdf.ImageToPdf(frompath, targetpath1 + "\\" + newfileName);
}
else if (oldname.Contains("png"))
{
newfileName = oldname.Replace(".png", ".pdf");
if (File.Exists(targetpath1 + "\\" + newfileName))
{
// Parameters 1: File path to delete
File.Delete(targetpath1 + "\\" + newfileName);
}
Pic2Pdf.ImageToPdf(frompath, targetpath1 + "\\" + newfileName);
}
if (File.Exists(movepath1 + "\\" + file.Name))
{
// Parameters 1: File path to delete
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)); // Create a thread
th_ImgtoPDF.IsBackground = true;
th_ImgtoPDF.Start(); // Execute the current thread
//Pic2Pdf.ImageToPdf(frompath, topath);
//MessageBox.Show(" Conversion success 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:
Source code :
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using O2S.Components.PDFRender4NET;// Added
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>
/// take PDF How to convert a document into a picture
/// </summary>
/// <param name="pdfInputPath">PDF File path </param>
/// <param name="imageOutputPath"> Picture output path </param>
/// <param name="imageName"> The name of the generated picture </param>
/// <param name="startPageNum"> from PDF The page number of the document begins to change </param>
/// <param name="endPageNum"> from PDF The page number of the document begins to stop converting </param>
/// <param name="imageFormat"> Set the desired picture format </param>
/// <param name="definition"> Set the sharpness of the picture , The bigger the number, the clearer </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:
Source code :
using System.IO;
using iTextSharp.text;// Added
using iTextSharp.text.pdf;// Added
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 Is the absolute path of the picture
int intWidth = pic.Width;// Pixel length value
int intHeight = pic.Height;// Height pixel value
pic.Dispose();
iTextSharp.text.Rectangle pagesize = new iTextSharp.text.Rectangle(intWidth, intHeight);
Document pdfdoc = new Document(pagesize);// establish Document Instance of object , And set up Document The size and margin of .
PdfWriter writer = PdfWriter.GetInstance(pdfdoc, new FileStream(topath, FileMode.Create)); // Build a Pdf Writer object Writer And document Object association , adopt Writer You can write documents to disk .
pdfdoc.Open(); // Open the document .
PdfContentByte cb = writer.DirectContent;
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(frompath);
img.SetAbsolutePosition(0, 0);
cb.AddImage(img); // Add image data to the document .
pdfdoc.NewPage();
pdfdoc.Close(); // close document , Write the contents of the buffer to disk to save the file .
}
}
}
Running effect :
Can realize the function :
1.PDF Convert to picture :
take PDF The file is converted into... By page .Png Image format , After the conversion, there will be a prompt
( The converted files will be automatically moved to the corresponding folder , Prevent multiple conversions )
2. Convert the picture to PDF:
You can put a single photo (.Png/.png) Convert to .pdf file , After the conversion, there will be a prompt
( The converted pictures will be automatically moved to the corresponding folder , Prevent multiple conversions )
Process demonstration :
To extend further :
You can use this source code , Further expand the generated image format ( example .jpg And so on ), And transform it into PDF The format of the source image of the file ( example .jpg And so on ), The universality of the extension program .
in addition , You can consider how to put multiple PDF File merge .
Source download :
https://blog.csdn.net/sinat_40003796?spm=1000.2115.3001.5343
版权声明
本文为[Tomorrow is like noon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230546377149.html
边栏推荐
- C语言循环结构程序
- Swagger2 generates API documents
- C#【文件操作篇】PDF文件和图片互相转换
- Wechat applet request encapsulation
- [UDS unified diagnostic service] IV. typical diagnostic service (5) - function / component test function unit (routine function unit 0x31)
- 修改注册表的值
- 圆整 round 的一点点小细节
- 拷贝构造函数
- 日志
- Graduation project, curriculum link, student achievement evaluation system
猜你喜欢
C语言循环结构程序
C#中?的这种形式
Graduation project, viewing screenshots of epidemic psychological counseling system
Robocode教程8——AdvancedRobot
C语言实用小技巧合集(持续更新)
【UDS统一诊断服务】四、诊断典型服务(4)— 在线编程功能单元(0x34-0x38)
文件查看命令和用户管理命令
Opencv uses genericindex for KNN search
PHP junior programmers, take orders and earn extra money
进程管理命令
随机推荐
The waterfall waterfall flow of uview realizes single column and loads more
pyppeteer爬虫
类和对象
[opencv] use filestorage to read and write eigenvectors
【UDS统一诊断服务】四、诊断典型服务(5)— 功能/元件测试功能单元(例行程序功能单元0x31)
gst-launch-1.0用法小记
拷贝构造函数
生成验证码
【UDS统一诊断服务】四、诊断典型服务(1)— 诊断和通信管理功能单元
P1018 maximum product solution
Class inheritance and derivation
Graduation project, curriculum link, student achievement evaluation system
非参数化相机畸变模型简介
for()循环参数调用顺序
Cross domain issues - allow origin header contains multiple values but only one is allowed
xlsxwriter.exceptions.FileCreateError: [Errno 13] Permission denied问题
clion安装教程
ArcGIS表转EXCEL超出上限转换失败
根据SQL语句查询出的结果集,将其封装为json
类和对象的初始化(构造函数与析构函数)