首页 > 代码库 > c#控制和切图 PDF文档

c#控制和切图 PDF文档

1、添加 AcroPDFLib.dll和 AxAcroPDFLib.dll

本例使用Winform,在设计器工具箱中会找不到AxAcroPDFLib.AxAcroPDF 控件,需在选择项中COM组件添加Adobe PDF Reader和Adobe Aceobat DC BrowerControl Implementation

2、打开pdf文档 

(1)打开文档路径

 

private void btnSelect_Click(object sender, EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
DialogResult result = openFile.ShowDialog();

if (result == DialogResult.Cancel)
{
return;
}
string strFileName = openFile.FileName;

string strFileNameDup = strFileName;

if (strFileNameDup.ToUpper().EndsWith(".PDF"))
{
txtFilePath.Text = strFileName;
}
else
{
MessageBox.Show("!!", "请选择PDF文件", MessageBoxButtons.OK, MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
}
}

 

(2)打开PDF

 

private void btnOpen_Click(object sender, EventArgs e)
{
if (txtFilePath.TextLength == 0)
{
MessageBox.Show("请选择文件");
}
StringBuilder shortFileName = new StringBuilder(4089);
uint shortFileNameSize = (uint)shortFileName.Capacity;
if (GetShortPathName(txtFilePath.Text, shortFileName, shortFileNameSize) != 0)
{
axAcroPDF.LoadFile(shortFileName.ToString());
}
else
{
MessageBox.Show("未找到文件");
}
}

 

3、页面操作

 (1)简单页面操控axAcroPDF.gotoPreviousPage();//上页

axAcroPDF.gotoNextPage();//下页

 axAcroPDF.gotoFirstPage();//首页

axAcroPDF.gotoLastPage();//尾页

(2)跳转到指定页

 axAcroPDF.setCurrentPage(Convert.ToInt32(txtIputPage.Text));

其中txtIputPage.Text为见面控件text传入 的值。

4、pdf转换成图片

添加O2S.Components.PDFRender4NET.dll的引用

(1)获取PDF文档页数

FileStream fs = new FileStream(pdfPath, FileMode.Open, FileAccess.Read);
StreamReader r = new StreamReader(fs);
string pdfText = r.ReadToEnd();//获取PDF文本
Regex rx1 = new Regex(@"/Type\s*/Page[^s]");//使用正则表达式计算:"/Type /Page" 标记出现的次数,计算pdf有多少页
MatchCollection matches = rx1.Matches(pdfText);

 

(2)转换图片

public static void PDFTOImage(string InputPath, string imageOutputPath,
int startPageNum, int endPageNum, ImageFormat imageFormat)
{
PDFFile pdfFile = PDFFile.Open(InputPath);
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 * 5);
pageImage.Save(imageOutputPath + "Convent" + i.ToString() + "." + imageFormat.ToString(), imageFormat);
pageImage.Dispose();
}
pdfFile.Dispose();
}

 

c#控制和切图 PDF文档