今天由于工作需要,研究了将PDF文件转换为图片的一些小方法。翻破网络都没有找到相关资料,一个偶然,庆幸自己找到准确信息(http://www.codeproject.com/KB/GDI-plus/pdfthumbnail.aspx),特将一些信息贴出来,供大家参考!
需要引用两个连接库,1、Com组件Acrobat(Adobe Acrobat Professional);2、.Net组件Microdoft.VisualBasic。
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Drawing;
using System.Runtime.InteropServices;
namespace AdaEniac
{
public class ConvertPdfToPicture
{
private Acrobat.CAcroPDDoc pdfDoc;
private Acrobat.CAcroPDPage pdfPage;
private Acrobat.CAcroRect pdfRect;
private Acrobat.CAcroPoint pdfPoint;
public ConvertPdfToPicture()
{
}
public void ConvertToPicture(string[] pcFileNames)
{
try
{
//Pdf 文件数量判断
for (int n = 0; n < 1; n++)
{
string lcFileName = pcFileNames[n].ToString();
string lcOutPutFile = lcFileName.Replace(“.pdf”, “”);
pdfDoc = (Acrobat.CAcroPDDoc)Microsoft.VisualBasic.Interaction.CreateObject(“AcroExch.PDDoc”, “”);
bool llRet = pdfDoc.Open(lcFileName);
if (!llRet)
{
throw new FileNotFoundException();
}
int pageCount = pdfDoc.GetNumPages();
for (int i = 0; i < pageCount; i++)
{
pdfPage = (Acrobat.CAcroPDPage)pdfDoc.AcquirePage(i);
pdfPoint = (Acrobat.CAcroPoint)pdfPage.GetSize();
pdfRect = (Acrobat.CAcroRect)Microsoft.VisualBasic.Interaction.CreateObject(“AcroExch.Rect”, “”);
pdfRect.Left = 0;
pdfRect.right = pdfPoint.x;
pdfRect.Top = 0;
pdfRect.bottom = pdfPoint.y;
pdfPage.CopyToClipboard(pdfRect, 0, 0, 100);
IDataObject loClipboardData = Clipboard.GetDataObject();
if (loClipboardData.GetDataPresent(DataFormats.Bitmap))
{
Bitmap pdfBitmap = (Bitmap)loClipboardData.GetData(DataFormats.Bitmap);
int loImgWidth = pdfPoint.x;
int loImgHeight = pdfPoint.y;
if (pdfPoint.x >= pdfPoint.y)
{
loImgWidth = loImgWidth ^ loImgHeight;
loImgHeight = loImgWidth ^ loImgHeight;
loImgWidth = loImgWidth ^ loImgHeight;
}
Bitmap loTemplateBitmap = new Bitmap(pdfPoint.x, pdfPoint.y);
Image loPdfImage = pdfBitmap.GetThumbnailImage(loImgWidth, loImgHeight, null, IntPtr.Zero);
Bitmap thumbnailBitmap = new Bitmap(loImgWidth + 7, loImgHeight + 7, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
// http://www.sellsbrothers.com/writing/default.aspx?content=dotnetimagerecoloring.htm
loTemplateBitmap.MakeTransparent();
using (Graphics poGraphics = Graphics.FromImage(thumbnailBitmap))
{
poGraphics.DrawImage(loPdfImage, 2, 2, loImgWidth, loImgHeight);
poGraphics.DrawImage(loTemplateBitmap, 0, 0);
//保存图象文件
string lcSaveFileName = lcOutPutFile + i.ToString() + “.png”;
thumbnailBitmap.Save(lcSaveFileName, System.Drawing.Imaging.ImageFormat.Png);
}
loTemplateBitmap.Dispose();
loPdfImage.Dispose();
thumbnailBitmap.Dispose();
}
}
pdfDoc.Close();
// see http://blogs.msdn.com/yvesdolc/archive/2004/04/17/115379.aspx
Marshal.ReleaseComObject(pdfPage);
Marshal.ReleaseComObject(pdfRect);
Marshal.ReleaseComObject(pdfDoc);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}