csharp: using Acrobat.dll pdf convert images in winform

来源:https://www.cnblogs.com/geovindu/archive/2020/06/24/13186506.html
-Advertisement-
Play Games

// A delegate type for hooking up change notifications. public delegate void ProgressChangingEventHandler(object sender, string e); /// <summary> /// ...


 

    // A delegate type for hooking up change notifications.
    public delegate void ProgressChangingEventHandler(object sender, string  e);


    /// <summary>
    /// Author:ESMAEEL ZENDEHDEL [email protected]
    /// DATE: 88/11/17
    /// Description: A Class For Exporting Image From PDF Files
    /// License : Free For All
    /// //Acrobat com
    /// </summary>
    class PDFConvertor
    {
        public int pageCount = 0;
        Acrobat.CAcroPDDoc pdfDoc = new Acrobat.AcroPDDoc();
        Acrobat.CAcroPDPage pdfPage = null;
        Acrobat.CAcroRect pdfRect = new Acrobat.AcroRect();
        Acrobat.AcroPoint pdfPoint =new Acrobat.AcroPoint();

        

        public event ProgressChangingEventHandler  ExportProgressChanging;

        protected virtual void OnExportProgressChanging(string e)
        {
            Thread.SpinWait(100);
          if (ExportProgressChanging != null)
                ExportProgressChanging(this, e);
        }

        #region Convert
        /// <summary>
        /// Converting PDF Files TO Specified Image Format
        /// </summary>
        /// <param name="sourceFileName">Source PDF File Path</param>
        /// <param name="DestinationPath">Destination PDF File Path</param>
        /// <param name="outPutImageFormat">Type Of Exported Image</param>
        /// <returns>Returns Count Of Exported Images</returns>
        public int Convert(string sourceFileName, string DestinationPath, ImageFormat outPutImageFormat)
        {


            if (pdfDoc.Open(sourceFileName))
            {

                // pdfapp.Hide();
                pageCount = pdfDoc.GetNumPages();

                for (int i = 0; i < pageCount; i++)
                {
                    pdfPage = (Acrobat.CAcroPDPage)pdfDoc.AcquirePage(i);


                    pdfPoint = (Acrobat.AcroPoint)pdfPage.GetSize();
                    pdfRect.Left = 0;
                    pdfRect.right = pdfPoint.x;
                    pdfRect.Top = 0;
                    pdfRect.bottom = pdfPoint.y;

                    pdfPage.CopyToClipboard(pdfRect, 0, 0, 100);

                    string outimg = "";
                    string filename=sourceFileName.Substring(sourceFileName.LastIndexOf("\\")); 

                    if (pageCount == 1)
                        outimg = DestinationPath + "\\" + filename + "." + outPutImageFormat.ToString();
                    else
                        outimg = DestinationPath + "\\" + filename + "_" + i.ToString() + "." + outPutImageFormat.ToString();
                    
                    Clipboard.GetImage().Save(outimg, outPutImageFormat);

                    ////////////Firing Progress Event 
                    OnExportProgressChanging(outimg);
                }

                  Dispose();
            }
            else
            {
                Dispose();
                throw new System.IO.FileNotFoundException(sourceFileName +" Not Found!");

            }
            return pageCount;
        }
        #endregion

        #region Convert With Zoom
        /// <summary>
        /// Converting PDF Files TO Specified Image Format
        /// </summary>
        /// <param name="sourceFileName">Source PDF File Path</param>
        /// <param name="DestinationPath">Destination PDF File Path</param>
        /// <param name="outPutImageFormat">Type Of Exported Image</param>
        /// <param name="width">Width Of Exported Images</param>
        /// <param name="height">Heiht Of Exported Images</param>
        /// <param name="zoom">Zoom Percent</param>
        /// <returns>Returns Count Of Exported Images</returns>
        public int Convert(string sourceFileName, string DestinationPath, ImageFormat outPutImageFormat, short width, short height, short zoom)
        {



            if (pdfDoc.Open(sourceFileName))
            {

                // pdfapp.Hide();
                pageCount = pdfDoc.GetNumPages();

                for (int i = 0; i < pageCount; i++)
                {
                    pdfPage = (Acrobat.CAcroPDPage)pdfDoc.AcquirePage(i);


                    //  pdfPoint = (Acrobat.CAcroPoint)pdfPage.GetSize();
                    pdfRect.Left = 0;
                    pdfRect.right = width; //pdfPoint.x;
                    pdfRect.Top = 0;
                    pdfRect.bottom = height; //pdfPoint.y;

                    pdfPage.CopyToClipboard(pdfRect, 0, 0, zoom);

                    string outimg = "";
                    string filename = sourceFileName.Substring(sourceFileName.LastIndexOf("\\"));

                    if (pageCount == 1)
                        outimg = DestinationPath + "\\" + filename + "." + outPutImageFormat.ToString();
                    else
                        outimg = DestinationPath + "\\" + filename + "_" + i.ToString() + "." + outPutImageFormat.ToString();

                    
                    Clipboard.GetImage().Save(outimg, outPutImageFormat);
                 
                    ////////////Firing Progress Event 
                    OnExportProgressChanging(outimg);
                }
                Dispose();

            }
            else
            {
                Dispose();
                throw new System.IO.IOException("Specified File Not Found!");
            }
            return pageCount;
        }
        #endregion



    


        #region Destractor
        ~PDFConvertor()
        {
            GC.Collect();
            if (pdfPage!=null)
                Marshal.ReleaseComObject(pdfPage);
            Marshal.ReleaseComObject(pdfPoint);
            Marshal.ReleaseComObject(pdfRect);
            Marshal.ReleaseComObject(pdfDoc);
        }
        public void Dispose()
        {
            GC.Collect();
            if (pdfPage != null)
                Marshal.ReleaseComObject(pdfPage);
            Marshal.ReleaseComObject(pdfPoint);
            Marshal.ReleaseComObject(pdfRect);
            Marshal.ReleaseComObject(pdfDoc);
        }
        #endregion

    }

  

/// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConvert_Click(object sender, EventArgs e)
        {
            ImageFormat imageFormat = new ImageFormat(Guid.Empty);
            switch (comboBox1.SelectedItem.ToString() )
            {
                case "Jpeg": imageFormat = ImageFormat.Jpeg; break;
                case "Bmp": imageFormat = ImageFormat.Bmp; break;
                case "Png": imageFormat = ImageFormat.Png; break;
                case "Gif": imageFormat = ImageFormat.Gif; break;
            }

            pdf = new PDFConvertor();
            pdf.ExportProgressChanging += new ProgressChangingEventHandler(p_ExportProgressChanging);
      
            progressBar1.Visible = true;
            int filescount= pdf.Convert(txtInput.Text, txtOutPut.Text, imageFormat);
            progressBar1.Visible = false ;
            progressBar1.Value = 0;
            this.Text = filescount + " Items Exported!";
            lblCurrentFileName.Text = "";

           System.Diagnostics.Process.Start(txtOutPut.Text);
           
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void p_ExportProgressChanging(object sender, string e)
        {
            
            lblCurrentFileName.Text = " Extracting " + e.Substring(e.LastIndexOf("\\")) + " !";
            progressBar1.Maximum = pdf.pageCount;
            progressBar1.Value += 1;
            this.Text=lblCount.Text =string.Format("{0}/{1} Extracted!",progressBar1.Value,progressBar1.Maximum);

            lblCount.Update();
            lblCurrentFileName.Update();
        }

  

 pdf = new PDFConvertor();
            imageFormat = ImageFormat.Jpeg;
            inputfile = Server.MapPath("pdffile/Top1000WorldBanks2014.pdf");
            outpubfile = Server.MapPath("exportimage");


            //WEB不可以
            // int filescount = pdf.Convert(inputfile, outpubfile, imageFormat);


            DateTime startTime = DateTime.Now;

           // string inputFile = files[n].ToString();
            string outputFile = outpubfile + inputfile.Substring(inputfile.LastIndexOf(@"\") + 1).Replace(".pdf", ".png");

           

            pdfDoc = (Acrobat.CAcroPDDoc)Microsoft.VisualBasic.Interaction.CreateObject("AcroExch.PDDoc", "");

            bool ret = pdfDoc.Open(inputfile);
            if (!ret)
            {
                throw new FileNotFoundException();
            }

            // Get the number of pages (to be used later if you wanted to store that information)
            int pageCount = pdfDoc.GetNumPages();

            // Get the first page
            pdfPage = (Acrobat.CAcroPDPage)pdfDoc.AcquirePage(0);

            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;

            int numPages = pdfDoc.GetNumPages();
            //System.Web.HttpContext.Current.Response.Write("numPages: " + numPages);
            //System.Web.HttpContext.Current.Response.Write("Size: " + pdfPoint.x + "x" + pdfPoint.y);

            double ratio = (double)pdfPoint.x / (double)pdfPoint.y;

            // Render to clipboard, scaled by 100 percent (ie. original size)
            // Even though we want a smaller image, better for us to scale in .NET
            // than Acrobat as it would greek out small text
            // see http://www.adobe.com/support/techdocs/1dd72.htm

            

            bool copyToClipBoardSuccess = pdfPage.CopyToClipboard(pdfRect, 0, 0, 100);

            IDataObject clipboardData = Clipboard.GetDataObject();

             Response.Write("copyToClipBoardSuccess: " + copyToClipBoardSuccess + ", Clipboard.ContainsImage: " + Clipboard.ContainsImage() + ", Clipboard.ContainsData: " + Clipboard.ContainsData(DataFormats.Bitmap));

            //if (clipboardData.GetDataPresent(DataFormats.Bitmap))
            //{
            //    Bitmap pdfBitmap = (Bitmap)clipboardData.GetData(DataFormats.Bitmap);

            //    // Size of generated thumbnail in pixels
            //    int biggestSize = 500;
            //    int thumbnailWidth = 0;
            //    int thumbnailHeight = 0;

            //    if (pdfPoint.x >= pdfPoint.y)
            //    {
            //        thumbnailWidth = biggestSize;
            //        thumbnailHeight = Convert.ToInt32((double)thumbnailWidth * ratio);
            //    }
            //    else
            //    {
            //        thumbnailHeight = biggestSize;
            //        thumbnailWidth = Convert.ToInt32((double)thumbnailHeight * ratio);
            //    }


            //    // Render to small image using the bitmap class
            //    System.Drawing.Image pdfImage = pdfBitmap.GetThumbnailImage(thumbnailWidth, thumbnailHeight, null, IntPtr.Zero);

            //    // Create new blank bitmap					 
            //    Bitmap thumbnailBitmap = new Bitmap(thumbnailWidth, thumbnailHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            //    using (Graphics thumbnailGraphics = Graphics.FromImage(thumbnailBitmap))
            //    {
            //        // Draw rendered pdf image to new blank bitmap
            //        thumbnailGraphics.DrawImage(pdfImage, 2, 2, thumbnailWidth, thumbnailHeight);

            //        // Save as .png file
            //        thumbnailBitmap.Save(outputFile, System.Drawing.Imaging.ImageFormat.Png);

            //        //System.Web.HttpContext.Current.Response.Write("Generated thumbnail... " + outputFile);
            //    }

            //    pdfDoc.Close();

            //    // Not sure how why it is to do this, but Acrobat is not the best behaved COM object
            //    // see http://blogs.msdn.com/yvesdolc/archive/2004/04/17/115379.aspx
            //    Marshal.ReleaseComObject(pdfPage);
            //    Marshal.ReleaseComObject(pdfRect);
            //    Marshal.ReleaseComObject(pdfDoc);



             //   TimeSpan ts = new TimeSpan(DateTime.Now.Ticks - startTime.Ticks);
              //  //System.Web.HttpContext.Current.Response.Write("Parsning tog: " + ts.TotalMilliseconds + " ms");
              //  //System.Web.HttpContext.Current.Response.Write("");

            //}

  

from: https://www.codeproject.com/articles/57100/simple-and-free-pdf-to-image-conversion


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1、新建一個dockerfile文件 touch test.Dockerfile 2、找一個centos基礎鏡像 可以去docker hub上尋找,鏈接:docker-hub 在搜索框搜索'centos',或者直接點擊docker-hub-centos。裡面有從centos 6 到最新的centos ...
  • 作者:jasonGeng88 www.github.com/jasonGeng88/blog 打開這篇文章的同學,想必對 docker 都不會陌生。docker 是一種虛擬容器技術,它上手比較簡單,只需在宿主機上起一個 docker engine,然後就能愉快的玩耍了,如:拉鏡像、起容器、掛載數據、 ...
  • 如果你是一名20多歲或30多歲的軟體開發人員,那麼你已成長在一個由Linux主導的世界中。數十年來,它一直是數據中心的重要參與者,儘管很難找到明確的操作系統市場份額的報告,但Linux在數據中心操作系統上的份額可能高達70%,而Windows變體幾乎涵蓋了所有剩餘的比例。 使用任何主流公共雲的開發人 ...
  • Blazor支持漸進式應用開發也就是PWA。使用PWA模式可以使得web應用有原生應用般的體驗。 什麼是PWA PWA應用是指那些使用指定技術和標準模式來開發的web應用,這將同時賦予它們web應用和原生應用的特性。 例如,web應用更加易於發現——相比於安裝應用,訪問一個網站顯然更加容易和迅速,並 ...
  • from:https://www.ghostscript.com/download/gsdnld.html https://www.codeproject.com/Articles/317700/Convert-a-PDF-into-a-series-of-images-using-Csharp h ...
  • 基於角色的訪問控制 (RBAC) 是將系統訪問限製為授權用戶的一種方法,是圍繞角色和特權定義的與策略無關的訪問控制機制,RBAC的組件使執行用戶分配變得很簡單。 在組織內部,將為各種職務創建角色。執行某些操作的許可權已分配給特定角色。成員或職員(或其他系統用戶)被分配了特定角色,並且通過這些角色分配獲 ...
  • 剛開始學習VBA的時候,保存自定義數據用的隱藏工作表;後來學了VSTO,把自定義數據保存到XML文件中;最近繼續深入學習,發現可以直接在xlsx文件中保存自定義數據,這裡就列出使用方法。 除了以上幾種保存方式,還可以保存為JSON格式,或者直接在xlsx文件中寫入xml。各種方式都有適合的應用場景, ...
  • 用好數據映射,MongoDB via Dotnet Core開發變會成一件超級快樂的事。 一、前言 MongoDB這幾年已經成為NoSQL的頭部資料庫。 由於MongoDB free schema的特性,使得它在互聯網應用方面優於常規資料庫,成為了相當一部分大廠的主數據選擇;而它的快速佈署和開發簡單 ...
一周排行
    -Advertisement-
    Play Games
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...
  • 目錄前言PostgreSql安裝測試額外Nuget安裝Person.cs模擬運行Navicate連postgresql解決方案Garnet為什麼要選擇Garnet而不是RedisRedis不再開源Windows版的Redis是由微軟維護的Windows Redis版本老舊,後續可能不再更新Garne ...
  • C#TMS系統代碼-聯表報表學習 領導被裁了之後很快就有人上任了,幾乎是無縫銜接,很難讓我不想到這早就決定好了。我的職責沒有任何變化。感受下來這個系統封裝程度很高,我只要會調用方法就行。這個系統交付之後不會有太多問題,更多應該是做小需求,有大的開發任務應該也是第二期的事,嗯?怎麼感覺我變成運維了?而 ...
  • 我在隨筆《EAV模型(實體-屬性-值)的設計和低代碼的處理方案(1)》中介紹了一些基本的EAV模型設計知識和基於Winform場景下低代碼(或者說無代碼)的一些實現思路,在本篇隨筆中,我們來分析一下這種針對通用業務,且只需定義就能構建業務模塊存儲和界面的解決方案,其中的數據查詢處理的操作。 ...
  • 對某個遠程伺服器啟用和設置NTP服務(Windows系統) 打開註冊表 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer 將 Enabled 的值設置為 1,這將啟用NTP伺服器功 ...
  • title: Django信號與擴展:深入理解與實踐 date: 2024/5/15 22:40:52 updated: 2024/5/15 22:40:52 categories: 後端開發 tags: Django 信號 松耦合 觀察者 擴展 安全 性能 第一部分:Django信號基礎 Djan ...
  • 使用xadmin2遇到的問題&解決 環境配置: 使用的模塊版本: 關聯的包 Django 3.2.15 mysqlclient 2.2.4 xadmin 2.0.1 django-crispy-forms >= 1.6.0 django-import-export >= 0.5.1 django-r ...
  • 今天我打算整點兒不一樣的內容,通過之前學習的TransformerMap和LazyMap鏈,想搞點不一樣的,所以我關註了另外一條鏈DefaultedMap鏈,主要調用鏈為: 調用鏈詳細描述: ObjectInputStream.readObject() DefaultedMap.readObject ...
  • 後端應用級開發者該如何擁抱 AI GC?就是在這樣的一個大的浪潮下,我們的傳統的應用級開發者。我們該如何選擇職業或者是如何去快速轉型,跟上這樣的一個行業的一個浪潮? 0 AI金字塔模型 越往上它的整個難度就是職業機會也好,或者說是整個的這個運作也好,它的難度會越大,然後越往下機會就會越多,所以這是一 ...
  • @Autowired是Spring框架提供的註解,@Resource是Java EE 5規範提供的註解。 @Autowired預設按照類型自動裝配,而@Resource預設按照名稱自動裝配。 @Autowired支持@Qualifier註解來指定裝配哪一個具有相同類型的bean,而@Resourc... ...