프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / PDF_TO_IMAGE / ConvertImage.cs @ bef3613f

이력 | 보기 | 이력해설 | 다운로드 (17.2 KB)

1
using System;
2
using System.Collections.Generic;
3
using System.ComponentModel;
4
using System.Data;
5
using System.Drawing;
6
using System.Drawing.Imaging;
7
using System.IO;
8
using System.Linq;
9
using System.Text;
10
using System.Threading.Tasks;
11
using System.Windows.Forms;
12
using DevExpress.Pdf;
13

    
14
namespace PDF_TO_IMAGE
15
{
16
    public partial class ConvertImage : Form
17
    {
18
        public ConvertImage()
19
        {
20
            InitializeComponent();
21

    
22
            Combo_Scale.SelectedIndex = Properties.Settings.Default._Scale;
23
            Combo_LengthType.SelectedIndex = Properties.Settings.Default._LengthType;
24
            Txt_Length.Text = Properties.Settings.Default._Length;
25
            Chk_Scale.Checked = Properties.Settings.Default._UseScale;
26
            SacleCheckedChange();
27
        }
28

    
29
        private void ConvertImage_FormClosing(object sender, FormClosingEventArgs e)
30
        {
31
            Properties.Settings.Default._Scale = Combo_Scale.SelectedIndex;
32
            Properties.Settings.Default._LengthType = Combo_LengthType.SelectedIndex;
33
            Properties.Settings.Default._Length = Txt_Length.Text;
34
            Properties.Settings.Default._UseScale = Chk_Scale.Checked;
35
            Properties.Settings.Default.Save();
36
        }
37

    
38
        private void Btn_LoadPDF_Click(object sender, EventArgs e)
39
        {
40
            FolderBrowserDialog dia = new FolderBrowserDialog();
41
            if (dia.ShowDialog() == DialogResult.OK)
42
            {
43
                Txt_PDFPath.Text = dia.SelectedPath;
44
            }
45

    
46
            return;
47
            OpenFileDialog OFD = new OpenFileDialog() { Filter = "PDF Files (.PDF)|*.PDF" };
48
            OFD.Multiselect = true;
49
            if (OFD.ShowDialog() == DialogResult.OK)
50
            {
51
                if (OFD.FileNames.Length > 1)
52
                {
53
                    if (MessageBox.Show("여러 파일을 하나로 합치고 진행하시겠습니까?", "Question", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
54
                    {
55
                        SaveFileDialog saveFileDialog = new SaveFileDialog();
56
                        saveFileDialog.Filter = "PDF Files (.PDF)|*.PDF";
57
                        if (saveFileDialog.ShowDialog() == DialogResult.OK)
58
                        {
59
                            int iScale = 0;
60
                            double iLength = 0;
61
                            bool bResult = true;
62

    
63
                            if (Chk_Scale.Checked)
64
                                iScale = Convert.ToInt32(Combo_Scale.SelectedItem.ToString().Split(new char[] { ' ' })[1]);
65
                            else
66
                            {
67
                                if (!double.TryParse(Txt_Length.Text, out iLength) || iLength < 300)
68
                                    bResult = false;
69

    
70
                            }
71

    
72
                            if (bResult)
73
                            {
74
                                splashScreenManager1.ShowWaitForm();
75
                                splashScreenManager1.SetWaitFormCaption("Convert Pdf File to Image Files");
76

    
77
                                PdfDocumentProcessor pdp = new PdfDocumentProcessor();
78
                                pdp.CreateEmptyDocument();
79
                                foreach (var fileName in OFD.FileNames)
80
                                {
81
                                    PdfDocumentProcessor selectFile = new PdfDocumentProcessor();
82
                                    selectFile.LoadDocument(fileName);
83
                                    foreach (var page in selectFile.Document.Pages)
84
                                        pdp.Document.Pages.Add(page);
85
                                    selectFile.CloseDocument();
86
                                    selectFile.Dispose();
87
                                    selectFile = null;
88
                                }
89

    
90
                                pdp.SaveDocument(saveFileDialog.FileName);
91

    
92
                                string sPathNonExtension = saveFileDialog.FileName.Replace(Path.GetExtension(saveFileDialog.FileName), "");
93

    
94

    
95
                                try
96
                                {
97
                                    int iPage = pdp.Document.Pages.Count;
98
                                    string sPage = iPage.ToString();
99
                                    for (int i = 0; i < pdp.Document.Pages.Count; i++)
100
                                    {
101
                                        int iPercent = i * 100 / iPage;
102
                                        splashScreenManager1.SetWaitFormDescription(i + " / " + sPage + " Pages ( " + iPercent + "% )");
103
                                        PdfPage page = pdp.Document.Pages[i];
104

    
105
                                        double dWidth = page.CropBox.Width;
106
                                        double dHeight = page.CropBox.Height;
107

    
108
                                        if (Chk_Scale.Checked)
109
                                        {
110
                                            dWidth = dWidth * iScale;
111
                                            dHeight = dHeight * iScale;
112
                                        }
113
                                        else
114
                                        {
115
                                            if (Combo_LengthType.SelectedItem.ToString() == "Width")
116
                                            {
117
                                                double dScale = dWidth / iLength;
118
                                                dWidth = iLength;
119
                                                dHeight = dHeight / dScale;
120
                                            }
121
                                            else
122
                                            {
123
                                                double dScale = dHeight / iLength;
124
                                                dHeight = iLength;
125
                                                dWidth = dWidth / dScale;
126
                                            }
127
                                        }
128

    
129
                                        double dMax = Math.Max(dWidth, dHeight);
130

    
131
                                        using (Bitmap bitmap = pdp.CreateBitmap(i + 1, (int)dMax))
132
                                        {
133
                                            bitmap.Save(sPathNonExtension + "_Page" + (i + 1) + ".png");
134
                                        }
135

    
136
                                        iPercent = (i + 1) * 100 / iPage;
137
                                        splashScreenManager1.SetWaitFormDescription((i + 1) + " / " + sPage + " Pages ( " + iPercent + "% )");
138
                                    }
139

    
140
                                    MessageBox.Show("변환완료");
141
                                }
142
                                catch (Exception ex)
143
                                {
144
                                    MessageBox.Show("변환 이미지의 사이즈를 줄여주십시오");
145
                                }
146

    
147
                                pdp.CloseDocument();
148
                                splashScreenManager1.CloseWaitForm();
149
                            }
150
                            else
151
                            {
152
                                MessageBox.Show("PDF 경로와 Scale 또는 Width or Height를 확인해주세요");
153
                            }
154
                        }
155
                    }
156
                }
157
                else
158
                {
159
                    string pdfpath = OFD.FileName;
160
                    Txt_PDFPath.Text = pdfpath;
161
                }
162
            }
163
        }
164

    
165
        private void Chk_Scale_CheckedChanged(object sender, EventArgs e)
166
        {
167
            SacleCheckedChange();
168
        }
169

    
170
        private void SacleCheckedChange()
171
        {
172
            if (Chk_Scale.Checked)
173
            {
174
                Txt_Length.Enabled = false;
175
                Combo_LengthType.Enabled = false;
176
                Combo_Scale.Enabled = true;
177
            }
178
            else
179
            {
180
                Txt_Length.Enabled = true;
181
                Combo_LengthType.Enabled = true;
182
                Combo_Scale.Enabled = false;
183
            }
184
        }
185

    
186
        /// <summary>
187
        /// export selected all pdf files to image files
188
        /// </summary>
189
        /// <param name="sender"></param>
190
        /// <param name="e"></param>
191
        private void Btn_Convert_Click(object sender, EventArgs e)
192
        {
193
            int iScale = 0;
194
            double iLength = 0;
195
            bool bResult = true;
196
            string sFilePath = Txt_PDFPath.Text;
197

    
198
            if (Chk_Scale.Checked)
199
                iScale = Convert.ToInt32(Combo_Scale.SelectedItem.ToString().Split(new char[] { ' ' })[1]);
200
            else
201
            {
202
                if (!double.TryParse(Txt_Length.Text, out iLength) || iLength < 300)
203
                    bResult = false;
204

    
205
            }
206

    
207
            if (System.IO.Directory.Exists(sFilePath) && bResult)
208
            {
209
                DirectoryInfo directory = new DirectoryInfo(Txt_PDFPath.Text);
210
                if (directory.Exists)
211
                {
212
                    bool result = true;
213
                    foreach (var item in directory.GetFiles("*.pdf", SearchOption.TopDirectoryOnly))
214
                    {
215
                        string sPathWithoutExt = Path.Combine(Path.GetDirectoryName(item.FullName), Path.GetFileNameWithoutExtension(item.FullName));
216
                        using (PdfDocumentProcessor pdp = new PdfDocumentProcessor())
217
                        {
218
                            pdp.LoadDocument(item.FullName, true);
219

    
220
                            /// read all words from pdf file
221
                            Dictionary<int, List<PageWord>> PageWordMap = new Dictionary<int, List<PageWord>>();
222
                            PdfPageWord currentWord = pdp.NextWord();
223
                            while (currentWord != null)
224
                            {
225
                                PageWord word = new PageWord(currentWord);
226
                                if(!PageWordMap.ContainsKey(word.PageNumber))
227
                                {
228
                                    PageWordMap[word.PageNumber] = new List<PageWord>();
229
                                }
230
                                PageWordMap[word.PageNumber].Add(word);
231
                                //Switch to the next word
232
                                currentWord = pdp.NextWord();
233
                            }
                            /// up to here
234
                            splashScreenManager1.ShowWaitForm();
235
                            splashScreenManager1.SetWaitFormCaption("Convert Pdf File to Image Files");
236
                            try
237
                            {
238
                                int iPage = pdp.Document.Pages.Count;
239
                                string sPage = iPage.ToString();
240
                                for (int i = 0; i < pdp.Document.Pages.Count; i++)
241
                                {
242
                                    int iPercent = i * 100 / iPage;
243
                                    splashScreenManager1.SetWaitFormDescription(i + " / " + sPage + " Pages ( " + iPercent + "% )");
244
                                    PdfPage page = pdp.Document.Pages[i];
245

    
246
                                    double dWidth = page.CropBox.Width;
247
                                    double dHeight = page.CropBox.Height;
248

    
249
                                    System.Drawing.Drawing2D.Matrix mat = new System.Drawing.Drawing2D.Matrix();
250
                                    mat.Rotate(page.Rotate);
251
                                    if (page.Rotate == 90 || page.Rotate == 270)
252
                                    {
253
                                        double tempValue = dWidth;
254
                                        dWidth = dHeight;
255
                                        dHeight = tempValue;
256
                                    }
257

    
258
                                    double dScale = iScale;
259
                                    if (Chk_Scale.Checked)
260
                                    {
261
                                        dWidth = dWidth * iScale;
262
                                        dHeight = dHeight * iScale;
263
                                    }
264
                                    else
265
                                    {
266
                                        if (Combo_LengthType.SelectedItem.ToString() == "Width")
267
                                        {
268
                                            dScale = iLength / dWidth;
269
                                            dWidth = iLength;
270
                                            dHeight = dHeight * dScale;
271
                                        }
272
                                        else
273
                                        {
274
                                            dScale = iLength / dHeight;
275
                                            dHeight = iLength;
276
                                            dWidth = dWidth * dScale;
277
                                        }
278
                                    }
279

    
280
                                    double dMax = Math.Max(dWidth, dHeight);
281
                                    using (Bitmap bitmap = pdp.CreateBitmap(i + 1, (int)dMax))
282
                                    {
283
                                        if (pdp.Document.Pages.Count != 1)
284
                                            bitmap.Save(sPathWithoutExt + "_Page" + (i + 1) + ".png", System.Drawing.Imaging.ImageFormat.Png);
285
                                        else
286
                                            bitmap.Save(sPathWithoutExt + ".png", System.Drawing.Imaging.ImageFormat.Png);
287
                                    }
288

    
289
                                    /// save text to file
290
                                    System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
291
                                    System.Xml.XmlNode xmlRoot = xmlDoc.CreateElement("Texts");
292
                                    foreach(PageWord word in PageWordMap[i + 1])
293
                                    {
294
                                        System.Xml.XmlNode xmlText = xmlDoc.CreateElement("Text");
295
                                        System.Xml.XmlAttribute pos = xmlDoc.CreateAttribute("Position");
296
                                        PointF[] array = { new PointF((float)(word.Left * dScale), (float)(word.Top * dScale)) };
297
                                        mat.TransformPoints(array);
298
                                        pos.Value = $"{System.Math.Abs(array[0].X)},{System.Math.Abs(array[0].Y)}";
299
                                        xmlText.Attributes.Append(pos);
300
                                        System.Xml.XmlAttribute angle = xmlDoc.CreateAttribute("Angle");
301
                                        double dAngle = (word.Angle - page.Rotate) >= 0 ? (word.Angle - page.Rotate) : 360 + (word.Angle - page.Rotate);
302
                                        angle.Value = $"{dAngle}";
303
                                        xmlText.Attributes.Append(angle);
304
                                        System.Xml.XmlAttribute xmlWidth = xmlDoc.CreateAttribute("Width");
305
                                        xmlWidth.Value = $"{word.Width * dScale}";
306
                                        xmlText.Attributes.Append(xmlWidth);
307
                                        System.Xml.XmlAttribute xmlHeight = xmlDoc.CreateAttribute("Height");
308
                                        xmlHeight.Value = $"{word.Height * dScale}";
309
                                        xmlText.Attributes.Append(xmlHeight);
310
                                        xmlText.InnerText = word.Text;
311

    
312
                                        xmlRoot.AppendChild(xmlText);
313
                                    }
314
                                    xmlDoc.AppendChild(xmlRoot);
315
                                    xmlDoc.Save($"{sPathWithoutExt}_Page{i + 1}.xml");
316
                                    /// up to here
317

    
318

    
319
                                    iPercent = (i + 1) * 100 / iPage;
320
                                    splashScreenManager1.SetWaitFormDescription((i + 1) + " / " + sPage + " Pages ( " + iPercent + "% )");
321
                                }
322
                            }
323
                            catch (Exception ex)
324
                            {
325
                                result = false;
326
                                MessageBox.Show("에러를 확인해 주세요: " + ex.Message, "에러", MessageBoxButtons.OK, MessageBoxIcon.Error);
327
                                break;
328
                            }
329

    
330
                            pdp.CloseDocument();
331
                            splashScreenManager1.CloseWaitForm();
332
                        }
333
                    }
334

    
335
                    if (result)
336
                        this.labelStatus.Text = "변환 완료";
337
                }
338
                else
339
                {
340
                    MessageBox.Show("PDF 경로와 Scale 또는 Width or Height를 확인해 주세요");
341
                }
342
            }
343
            else
344
            {
345
                MessageBox.Show("PDF 경로와 Scale 또는 Width or Height를 확인해 주세요");
346
            }
347
        }
348
    }
349
}
클립보드 이미지 추가 (최대 크기: 500 MB)