csharp: using Acrobat.dll pdf convert images in winform

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
// 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
 
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/// <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();
        }

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
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

posted @   ®Geovin Du Dream Park™  阅读(496)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2016-06-24 csharp:VerifyCode in winform or webform
2015-06-24 csharp:获取 DNS、网关、子网掩码、IP
2015-06-24 csharp: using wininet.dll
2013-06-24 csharp:汉字转带拼音声调
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示