using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using MSWord = Microsoft.Office.Interop.Word;

namespace ConvertEquationToPng
{
    public partial class MainForm : Form
    {
        private MSWord.Application m_word;
        private MSWord.Document m_doc;

        public MainForm()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                var processes = Process.GetProcessesByName("winword");
                foreach (var process in processes)
                {
                    process.Kill();
                }
            }
            catch (Exception)
            {

            }
            m_word = new MSWord.Application();
            object filefullname =Application.StartupPath+@"\\845AD2AE-23C0-4AC4-AFE7-F832BD088673_ONLY_QUESTION.doc";
            var obj = Type.Missing;
            try
            {
                m_word.Documents.Open(ref filefullname,ref obj, ref obj, ref obj,ref obj, ref obj, ref obj,ref obj, ref obj,ref obj, ref obj, ref obj, ref obj,ref obj, ref obj, ref obj);
                m_word.Visible = false;

                var document = m_word.Documents[1];

                var count = 0;
                foreach (var c in document.Fields)
                {
                    count++;
                    var d = (MSWord.Field) c;
                    d.Copy();
                    d.Select();
                    m_word.Selection.PasteSpecial(Link: false, DisplayAsIcon: false,DataType: MSWord.WdPasteDataType.wdPasteEnhancedMetafile,Placement:MSWord.WdOLEPlacement.wdInLine);
                }
                var picPath =new DirectoryInfo("c:\\Pic");
                if (!picPath.Exists)
                {
                    picPath.Create();
                }
                var i = 0;
                for (var j=1;j<= document.InlineShapes.Count;j++)
                {
                    var ish = document.InlineShapes[j];

                    if (ish.Type == MSWord.WdInlineShapeType.wdInlineShapePicture)
                    {
                        ish.Select();
                        m_word.Selection.Copy();
                        var image = Clipboard.GetImage();
                        if (image != null)
                        {
                            var bitmap = new Bitmap(image);
                            var fi = new FileInfo(picPath +"\\"+ i + ".jpg");
                            var fiNew= new FileInfo(picPath + "\\"+ i + "_new.jpg");
                            bitmap.Save(fi.FullName);
                            Trim(fi.FullName, fiNew.FullName);
                            var img = Image.FromFile(fiNew.FullName);
                            Clipboard.SetDataObject(img);
                            ish.Delete();
                            m_word.Selection.Paste();
                        }
                        i++;
                    }
                }
                
                #region 关闭
                //避免弹出normal.dotm被使用的对话框,自动保存模板  
                m_word.NormalTemplate.Saved = true;

                document.SaveAs("c:\\result.doc");
                //先关闭打开的文档(注意saveChanges选项)  
                Object saveChanges = MSWord.WdSaveOptions.wdDoNotSaveChanges;
                Object originalFormat = Type.Missing;
                Object routeDocument = Type.Missing;
                m_word.Documents.Close(ref saveChanges, ref originalFormat, ref routeDocument);

                //若已经没有文档存在,则关闭应用程序  
                if (m_word.Documents.Count == 0)
                {
                    m_word.Quit(Type.Missing, Type.Missing, Type.Missing);
                }
                var r=MessageBox.Show("成功完成,请查看效果!","恭喜",MessageBoxButtons.OKCancel,MessageBoxIcon.Question);
                if (r == DialogResult.OK)
                {
                    var fileFullName = "c:\\result.doc";
                    var psi = new ProcessStartInfo("Explorer.exe")
                    {
                        Arguments = "/e,/select," + fileFullName
                    };
                    Process.Start(psi);
                }

                #endregion
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("打开Word文档出错:"+ex);
            }
        }

        public static void Trim(string sourceFileName, string targetFileName)
        {
            CommonUtil.ExecCommand(@"C:\Program Files\ImageMagick-6.9.3-Q16\convert.exe", sourceFileName + " -transparent white -trim " + targetFileName);
        }
    }
}