csharp: using Acrobat.dll pdf convert images in winform

天大地大妈咪最大 提交于 2020-10-03 17:28:31

 

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


    /// <summary>
    /// Author:ESMAEEL ZENDEHDEL zendehdell@yahoo.com
    /// 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!