本文采用Adobe Acrobat9.0的COM組件,將Pdf文件的每一頁轉換成對應的圖片文件。
開發環境:VS2010,.Net Framework4.0,Adobe Acrobat9.0。
工程中添加COM引用:Adobe Acrobat 9.0 Type Library(必須裝了Adobe Acrobat9.0才會有)。
?
思路:
1、需要用到的COM對象:
??? 1)CAcroPDDoc:Acrobat文檔對象。
??? 2)CAcroPDPage:頁對象。
??? 3)CAcroRect:用來描述頁中一個矩形區域的對象。
??? 4)CAcroPoint:實際上代表的是Size。
?
2、轉換過程:
???1)打開文檔。
???2)取出每一頁。
?? 3)獲取每一頁的大小,生成一個表示該頁的矩形區域。
?? 4)將當前頁的指定區域編碼成圖片,并且復制到剪貼板中。
?? 5)將剪貼板中的圖片取出,保存為圖片文件。
?
轉換函數代碼:
public static void ConvertPdf2Image(string pdfFilePath, string imageDirectoryPath,int beginPageNum, int endPageNum, ImageFormat format, double zoom = 1) {Acrobat.CAcroPDDoc pdfDoc = null;Acrobat.CAcroPDPage pdfPage = null;Acrobat.CAcroRect pdfRect = null;Acrobat.CAcroPoint pdfPoint = null;//1)//生成操作Pdf文件的Com對象pdfDoc = (Acrobat.CAcroPDDoc)Microsoft.VisualBasic.Interaction.CreateObject("AcroExch.PDDoc", "");//檢查輸入參數if (!pdfDoc.Open(pdfFilePath)) {throw new FileNotFoundException(string.Format("源文件{0}不存在!", pdfFilePath));}if (!Directory.Exists(imageDirectoryPath)) {Directory.CreateDirectory(imageDirectoryPath);}if (beginPageNum <= 0) {beginPageNum = 1;}if (endPageNum > pdfDoc.GetNumPages() || endPageNum <= 0) {endPageNum = pdfDoc.GetNumPages();}if (beginPageNum > endPageNum) {throw new ArgumentException("參數\"beginPageNum\"必須小于\"endPageNum\"!");}if (format == null) {format = ImageFormat.Png;}if (zoom <= 0) {zoom = 1;}//轉換for (int i = beginPageNum; i <= endPageNum; i++) {//2)//取出當前頁pdfPage = (Acrobat.CAcroPDPage)pdfDoc.AcquirePage(i - 1);//3)//得到當前頁的大小pdfPoint = (Acrobat.CAcroPoint)pdfPage.GetSize();//生成一個頁的裁剪區矩形對象pdfRect = (Acrobat.CAcroRect)Microsoft.VisualBasic.Interaction.CreateObject("AcroExch.Rect", "");//計算當前頁經縮放后的實際寬度和高度,zoom==1時,保持原比例大小int imgWidth = (int)((double)pdfPoint.x * zoom);int imgHeight = (int)((double)pdfPoint.y * zoom);//設置裁剪矩形的大小為當前頁的大小pdfRect.Left = 0;pdfRect.right = (short)imgWidth;pdfRect.Top = 0;pdfRect.bottom = (short)imgHeight;//4)//將當前頁的裁剪區的內容編成圖片后復制到剪貼板中pdfPage.CopyToClipboard(pdfRect, 0, 0, (short)(100 * zoom));//5)IDataObject clipboardData = Clipboard.GetDataObject();//檢查剪貼板中的對象是否是圖片,如果是圖片則將其保存為指定格式的圖片文件if (clipboardData.GetDataPresent(DataFormats.Bitmap)) {Bitmap pdfBitmap = (Bitmap)clipboardData.GetData(DataFormats.Bitmap);pdfBitmap.Save(Path.Combine(imageDirectoryPath, i.ToString("0000") + "." + format.ToString()), format);pdfBitmap.Dispose();}}//關閉和釋放相關COM對象 pdfDoc.Close();Marshal.ReleaseComObject(pdfRect);Marshal.ReleaseComObject(pdfPoint);Marshal.ReleaseComObject(pdfPage);Marshal.ReleaseComObject(pdfDoc);}
轉自:http://www.cnblogs.com/kongxianghai/archive/2012/04/09/2438321.html
源代碼敬上:http://files.cnblogs.com/kongxianghai/Pdf2ImageWithAcrobat.rar
?
網上有一篇搜集的非常全的將Pdf文件轉換成圖片的各種方法,拿出來分享:
http://topic.csdn.net/u/20120219/20/4888d128-3b77-47bc-aa21-cb02c014bc1f.html?84661?