Click here to Skip to main content
12,243,721 members (41,168 online)
Click here to Skip to main content

Tagged as

Stats

61.8K views
3.5K downloads
43 bookmarked
Posted

Word2CHM, Convert a Word Document to a CHM File

, 17 Nov 2010 CPOL
Word2CHM, convert a Word document to a CHM file
/***************************************************************************

  Word2CHM

  Copyright (c) 2010 sinosoft , written by yuans.
  http://www.sinoreport.net

  This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License
  as published by the Free Software Foundation; either version 2
  of the License, or (at your option) any later version.
  
  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
  
  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

****************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Word2CHM.CHMDom ;
using System.Runtime.InteropServices;

namespace Word2CHM
{
    public partial class frmWord2CHM : Form
    {
        public frmWord2CHM()
        {
            InitializeComponent();
        }

        private CHMDocument myDocument = new CHMDocument();
        public CHMDocument Document
        {
            get
            {
                return myDocument;
            }
            set
            {
                myDocument = value;
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            this.Document.HelpHeaderHtml = Word2CHM.Properties.Settings.Default.DefaultHeaderHTML;
            this.Document.HelpFooterHtml = Word2CHM.Properties.Settings.Default.DefaultFooterHtml;

            base.OnLoad(e);
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            // Save config settings
            Word2CHM.Properties.Settings.Default.Save();
        }

        public void RefreshView()
        {
            this.tvwCHM.BeginUpdate();
            this.tvwCHM.Nodes.Clear();
            TreeNode rootNode = new TreeNode(myDocument.Title);
            rootNode.ImageIndex = 0;
            rootNode.SelectedImageIndex = 0;
            rootNode.Tag = myDocument;
            AddNodes(myDocument.Nodes, rootNode);
            tvwCHM.Nodes.Add(rootNode);
            rootNode.ExpandAll();
            this.tvwCHM.EndUpdate();
        }

        private void AddNodes(CHMNodeList list, System.Windows.Forms.TreeNode RootNode)
        {
            if (list == null || list.Count == 0)
                return;

            foreach (CHMNode node in list)
            {
                System.Windows.Forms.TreeNode n = new TreeNode(node.Name);
                n.Tag = node;
                if (node.Nodes.Count > 0)
                    n.ImageIndex = 1;
                else
                    n.ImageIndex = 2;
                n.SelectedImageIndex = n.ImageIndex;
                RootNode.Nodes.Add(n);
                if (node.Nodes.Count > 0)
                    AddNodes(node.Nodes, n);
            }
        }

        private void btnBrowseExportPath_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog dlg = new FolderBrowserDialog())
            {
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    txtOutputPath.Text = dlg.SelectedPath;
                }
            }
        }

        private void Alert(string msg)
        {
            MessageBox.Show(this, msg, this.Text);
        }

        private void btnOpenWord_Click(object sender, EventArgs e)
        {
            string dir = txtOutputPath.Text.Trim();
            if (System.IO.Directory.Exists(dir) == false)
            {
                Alert("Not exist Output path:" + dir);
                return;
            }
            using (OpenFileDialog dlg = new OpenFileDialog())
            {
                dlg.Filter = "Word2000/2003 document(*.doc)|*.doc";
                dlg.CheckFileExists = true;
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    LoadWordDocument(dlg.FileName, dir);
                }
            }
        }

        private bool LoadWordDocument(string fileName, string outputPath)
        {
            string dir = txtOutputPath.Text.Trim();
            if (System.IO.Directory.Exists(dir) == false)
            {
                Alert("Director no exist " + dir);
                return false;
            }
            if (System.IO.File.Exists(fileName) == false)
            {
                Alert("File no exist " + fileName);
                return false;
            }
            myDocument.Name = System.IO.Path.GetFileNameWithoutExtension(fileName);
            string htmlFile = System.IO.Path.Combine(dir, myDocument.Name + ".html");
            this.Cursor = Cursors.WaitCursor;

            SaveWordToHtml(fileName, htmlFile);

            this.Cursor = Cursors.WaitCursor;
            using (dlgImportWordHtml dlg2 = new dlgImportWordHtml())
            {
                dlg2.Document = this.Document;
                if (dlg2.ShowDialog(this) == DialogResult.OK)
                {
                    myDocument.LoadWordHtml(htmlFile);
                    this.RefreshView();
                    this.Cursor = Cursors.Default;
                    return true;
                }
            }
            this.Cursor = System.Windows.Forms.Cursors.Default;
            return false;
        }

        private bool SaveWordToHtml(string docFileName, string htmlFileName)
        {
            // check doc file name
            if (System.IO.File.Exists(docFileName) == false)
            {
                this.Alert("File '" + docFileName + "' not exist!");
                return false;
            }
            // check output directory
            string dir = System.IO.Path.GetDirectoryName(htmlFileName);
            if (System.IO.Directory.Exists(dir) == false)
            {
                this.Alert("Directory '" + dir + "' not exist!");
                return false;
            }

            object trueValue = true;
            object falseValue = false;
            object missValue = System.Reflection.Missing.Value;
            object fileNameValue = docFileName;

            // create word application instance
            Microsoft.Office.Interop.Word.Application app = null;
            Microsoft.Office.Interop.Word.Document doc = null;
            try
            {
                app = new Microsoft.Office.Interop.Word.ApplicationClass();
                // set word application visible
                // if something is error and quit , user can close word application by self.
                app.Visible = true;
                // open document
                doc = app.Documents.Open(
                    ref fileNameValue,
                    ref missValue,
                    ref trueValue,
                    ref missValue,
                    ref missValue,
                    ref missValue,
                    ref missValue,
                    ref missValue,
                    ref missValue,
                    ref missValue,
                    ref missValue,
                    ref missValue,
                    ref missValue,
                    ref missValue,
                    ref missValue,
                    ref missValue);
                // save document as a html file
                object htmlFileNameValue = htmlFileName;
                object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatFilteredHTML;
                doc.SaveAs(
                    ref htmlFileNameValue,
                    ref format,
                    ref missValue,
                    ref missValue,
                    ref missValue,
                    ref missValue,
                    ref missValue,
                    ref missValue,
                    ref missValue,
                    ref missValue,
                    ref missValue,
                    ref missValue,
                    ref missValue,
                    ref missValue,
                    ref missValue,
                    ref missValue);
            }
            finally
            {
                // close document and release resource
                if (doc != null)
                {
                    doc.Close(ref falseValue, ref missValue, ref missValue);
                }
                if (app != null)
                {
                    app.Quit(ref falseValue, ref missValue, ref missValue);
                }
                if (doc != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
                    doc = null;
                }
                if (app != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
                    app = null;
                }
            }
            return true;
        }

        private void tvwCHM_AfterSelect(object sender, TreeViewEventArgs e)
        {
            System.Windows.Forms.TreeNode node = tvwCHM.SelectedNode;
            if (node == null)
            {
                MessageBox.Show("Please select a node.");
                //bolLockEvent = false;
            }
            else
            {
                if (node.Tag is CHMDocument)
                {
                    CHMDocument doc = (CHMDocument)node.Tag;
                    //this.txtName.Text = doc.Title;
                    //this.txtPageFile.Text = doc.DefaultTopic;
                    this.myWebBrowser.Navigate("about:blank");
                }
                else if (node.Tag is CHMNode)
                {
                    CHMNode cn = (CHMNode)node.Tag;
                    //txtName.Text = cn.Name;
                    if (CHMDocument.HasContent(cn.Local))
                    {
                        this.myWebBrowser.Navigate(myDocument.GetAbsPath(cn.Local));
                    }
                    else
                    {
                        myWebBrowser.Navigate("about:blank");
                    }
                }
            }
        }

        private void Properties_Click(object sender, EventArgs e)
        {
            using (dlgDocumentProperties dlg = new dlgDocumentProperties())
            {
                dlg.Document = myDocument;
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    tvwCHM.Nodes[0].Text = myDocument.Title;
                }
            }
        }

        private void frmWord2CHM_Load(object sender, EventArgs e)
        {
            RefreshView();
        }

        private void btnCompile_Click(object sender, EventArgs e)
        {
            string hhcPath = Word2CHM.Properties.Settings.Default.HHCExePath;
            if (System.IO.File.Exists(hhcPath) == false)
            {
                MessageBox.Show("Can not find execute file '"
                    + hhcPath + "' of 'HTML Help Workshop'!");
                return;
            }
            try
            {
                string name = System.IO.Path.ChangeExtension(
                    this.myDocument.FileName, "hhp");
                this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                name = myDocument.CompileProject(
                    hhcPath,
                    Word2CHM.Properties.Settings.Default.DeleteTempFile);
                this.Cursor = System.Windows.Forms.Cursors.Default;
                System.Diagnostics.Debug.WriteLine(myDocument.OutputText);
                if (name == null)
                    Alert("Compile error!");
                else
                    Alert("Genereate file " + name);
            }
            catch (Exception ext)
            {
                Alert("App error:" + ext.Message);
            }
        }

        private void btnConfig_Click(object sender, EventArgs e)
        {
            using (dlgConfig dlg = new dlgConfig())
            {
                dlg.ShowDialog(this);
            }
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            this.Document.Nodes.Clear();
            this.RefreshView();
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

yuan yong fu
Web Developer duchang soft
China China
yuan yong fu of duchang soft , come from CHINA , 2008 Microsoft MVP,Use GDI+,XML/XSLT, site:http://www.cnblogs.com/xdesigner/

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160426.1 | Last Updated 17 Nov 2010
Article Copyright 2010 by yuan yong fu
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid