Beispiel #1
0
        public CounterData getCounters(String filePath)
        {
            CounterData counters = new CounterData {
                wordCount = 0, charCount = 0, paraCount = 0, pageCount = 0
            };
            string fileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);

            log.Info("Counting " + fileName);
            Microsoft.Office.Interop.Word.Application word = null;
            Microsoft.Office.Interop.Word.Document    doc  = null;

            object missing     = Type.Missing;
            object saveChanges = false;
            object includeFootnotesAndEndnotes = true;

            Microsoft.Office.Interop.Word.WdStatistic wordStats = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticWords;
            Microsoft.Office.Interop.Word.WdStatistic charStats = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticCharacters;
            Microsoft.Office.Interop.Word.WdStatistic paraStats = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticParagraphs;
            Microsoft.Office.Interop.Word.WdStatistic pageStats = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages;

            try
            {
                word = new Microsoft.Office.Interop.Word.Application();
                doc  = new Microsoft.Office.Interop.Word.Document();
                object objFilePath = @filePath;

                /*
                 * Document OpenNoRepairDialog(ref Object FileName,
                 *          ref Object ConfirmConversions, ref Object ReadOnly, ref Object AddToRecentFiles, ref Object PasswordDocument,
                 *      ref Object PasswordTemplate, ref Object Revert, ref Object WritePasswordDocument, ref Object WritePasswordTemplate,
                 *          ref Object Format, ref Object Encoding, ref Object Visible, ref Object OpenAndRepair,
                 *          ref Object DocumentDirection, ref Object NoEncodingDialog, ref Object XMLTransform
                 *  )
                 */
                doc = word.Documents.OpenNoRepairDialog(ref objFilePath,
                                                        ref missing, true, ref missing, ref missing,
                                                        ref missing, ref missing, ref missing, ref missing,
                                                        ref missing, ref missing, ref missing, ref missing,
                                                        ref missing, ref missing, ref missing);
                if (doc != null)
                {
                    doc.Activate();

                    counters.wordCount = doc.ComputeStatistics(wordStats, ref includeFootnotesAndEndnotes);
                    counters.charCount = doc.ComputeStatistics(charStats, ref includeFootnotesAndEndnotes);
                    counters.paraCount = doc.ComputeStatistics(paraStats, ref includeFootnotesAndEndnotes);
                    counters.pageCount = doc.ComputeStatistics(pageStats, ref includeFootnotesAndEndnotes);
                    log.Info(counters);
                }
                //doc.Save();
                word.Quit(ref saveChanges, ref missing, ref missing);
            }
            catch (Exception ex)
            {
                word.Quit(ref saveChanges, ref missing, ref missing);
                log.Error(ex);
            }

            return(counters);
        }
Beispiel #2
0
        public int getpage(object file)
        {
            try
            {
                Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
                object nullobj = System.Reflection.Missing.Value;

                Microsoft.Office.Interop.Word.Document doc = app.Documents.Open(
                    ref file, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj);
                doc.ActiveWindow.Selection.WholeStory();
                doc.ActiveWindow.Selection.Copy();
                IDataObject data = Clipboard.GetDataObject();

                // get number of pages
                Microsoft.Office.Interop.Word.WdStatistic stat = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages;
                int pages = doc.ComputeStatistics(stat, Type.Missing);

                //string text = data.GetData(DataFormats.Text).ToString();  //获取具体内容,此项目不需要

                doc.Close(ref nullobj, ref nullobj, ref nullobj);
                app.Quit(ref nullobj, ref nullobj, ref nullobj);


                return(pages);
            }
            catch (Exception ex)
            {
                ex.ToString();
                return(0);
            }
        }
Beispiel #3
0
        //public static int GetWordPageCount1(string path)
        //{

        //    XWPFDocument m_Docx = new XWPFDocument();
        //    m_Docx.
        //    System.IO.File doc = File("/Users/oushuuryuu/Desktop", "rirekisyo_jis.doc");
        //    Stream inStream = new FileStream(doc);
        //    m_Docx.Document.GetHashCode();
        //    //File doc = new System.IO.File("/Users/oushuuryuu/Desktop", "rirekisyo_jis.doc");
        //    var document = DocX.Load(path);
        //    Stream stream = new FileStream();
        //    MemoryStream stream2 = new MemoryStream();
        //    PostCreation(ref Package.Open(stream2, FileMode.Create, FileAccess.ReadWrite));
        //    Docx cx= Load(stream2);
        //    cx.stream = stream;
        //}

        #region --获取word文件的页数--
        /// <summary>
        /// 获得word文档页数
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public int GetWordPageCount(string path)
        {
            //try
            //{
            Microsoft.Office.Interop.Word.Application myWord = new Microsoft.Office.Interop.Word.ApplicationClass();
            object oMiss = System.Reflection.Missing.Value;

            myWord.Visible = false;
            object filePath = path;     //这里是Word文件的路径

            //打开文件
            Microsoft.Office.Interop.Word.Document myWordDoc = myWordApp.Documents.Open(
                ref filePath, ref oMiss, ref oMiss, ref oMiss,
                ref oMiss, ref oMiss, ref oMiss, ref oMiss,
                ref oMiss, ref oMiss, ref oMiss, ref oMiss,
                ref oMiss, ref oMiss, ref oMiss, ref oMiss);
            //下面是取得打开文件的页数
            int pages = myWordDoc.ComputeStatistics(WdStatistic.wdStatisticPages, ref oMiss);

            myWordDoc.Close(ref oMiss, ref oMiss, ref oMiss);
            return(pages);
            //}
            //catch (Exception ex)
            //{
            //    return 0;
            //}
        }
Beispiel #4
0
 /// <summary>
 /// 获取word页码数
 /// </summary>
 /// <param name="strSourceFile">要转换的Word文档</param>
 /// <returns>页码数</returns>
 public int getWordPages(object strSourceFile)
 {
     try
     {
         int pages = 0;
         if (File.Exists(strSourceFile.ToString()))
         {
             object Nothing = System.Reflection.Missing.Value;
             //创建一个名为WordApp的组件对象
             WORD.Application wordApp = new WORD.ApplicationClass();
             //创建一个名为WordDoc的文档对象并打开
             WORD.Document doc = wordApp.Documents.Open(ref strSourceFile, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
                                                        ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
             //下面是取得打开文件的页数
             pages = doc.ComputeStatistics(WORD.WdStatistic.wdStatisticPages, ref Nothing);
             //关闭文档对象
             object saveOption = WORD.WdSaveOptions.wdDoNotSaveChanges;
             ((Microsoft.Office.Interop.Word._Document)doc).Close(ref saveOption, ref Nothing, ref Nothing);
             //推出组建
             wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
         }
         return(pages);
     }
     catch (Exception ex)
     {
         classLims_NPOI.WriteLog(ex, "");
         return(0);
     }
 }
Beispiel #5
0
        //计算word文档段落数
        private string ParagraphDoc(string filePath)
        {
            // 使用Microsoft.Office.Interop.Word库来读取word文档
            var wordApp = new MSWord.Application();

            Microsoft.Office.Interop.Word.Document doc = null;
            string ret = "";
            int    paragraphs;

            try
            {
                wordApp.Visible = false;
                doc             = wordApp.Documents.Open(filePath);
                // 调用库的字数计算属性直接获取段落数

                paragraphs = doc.ComputeStatistics(WdStatistic.wdStatisticParagraphs, true);
                ret        = paragraphs.ToString();
            }
            catch (Exception e)
            {
                ret = "计算出错";
            }
            finally
            {
                doc.Close();
            }

            return(ret);
        }
Beispiel #6
0
        private void button1_Click(object sender, RibbonControlEventArgs e)
        {
            object Miss  = System.Reflection.Missing.Value;
            object What  = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToPage;
            object Which = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToAbsolute;
            object Start;
            object End;
            object CurrentPageNumber;
            object NextPageNumber;
            String fileNameDirectory = "C:\\excel\\";

            FolderBrowserDialog fbd = new FolderBrowserDialog();

            fbd.Description = "Seleccione el directorio donde se guardaran las imágenes";

            if (fbd.ShowDialog() == DialogResult.OK)
            {
                fileNameDirectory = fbd.SelectedPath.Replace(@"\", @"\\") + @"\\";
            }
            else
            {
                MessageBox.Show("Seleccione el directorio donde se guardaran las imágenes ",
                                "Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);

                return;
            }

            Debug.WriteLine(fileNameDirectory + " ............ ");

            //Obtain Current Document
            Word.Document Doc = Globals.ThisAddIn.Application.ActiveDocument;

            // Get pages count
            Microsoft.Office.Interop.Word.WdStatistic PagesCountStat = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages;
            int PagesCount = Doc.ComputeStatistics(PagesCountStat, ref Miss);


            for (int Index = 1; Index < PagesCount + 1; Index++)
            {
                CurrentPageNumber = (Convert.ToInt32(Index.ToString()));
                NextPageNumber    = (Convert.ToInt32((Index + 1).ToString()));

                // Get start position of current page
                Start = Globals.ThisAddIn.Application.Selection.GoTo(ref What, ref Which, ref CurrentPageNumber, ref Miss).Start;

                // Get end position of current page
                End = Globals.ThisAddIn.Application.Selection.GoTo(ref What, ref Which, ref NextPageNumber, ref Miss).End;

                saveImage(Doc, Start, End, fileNameDirectory, Index);
            }
            MessageBox.Show("Se creo correctamente las imágenes", "Super");
            Process.Start(fileNameDirectory);

            //  Debug.WriteLine(PagesCount);
        }
Beispiel #7
0
        static void Main(string[] args)
        {
            Word.Application _app     = null;
            Word.Document    document = null;
            object           missing  = System.Reflection.Missing.Value;

            _app = new Word.Application();
            string wordFilePath = @"D:\work\53002\20160823\131163876229304835\6\2062\20160822003\中共陕西省委党校2016年论文\2013210084-陈伟丽.doc";

            document = _app.Documents.Open(wordFilePath, false, false, false, ref missing, missing, false, missing, missing, missing, missing, false, false, missing, true, missing);
            object What  = Word.WdGoToItem.wdGoToSection;
            object Which = Word.WdGoToDirection.wdGoToNext;

            Word.WdStatistic staticword = Word.WdStatistic.wdStatisticPages;
            int ipagecount = document.ComputeStatistics(staticword);//获得word文档的页数

            //跳转到指定的页数
            object pWhat  = Word.WdGoToItem.wdGoToPage;
            object pWhich = Word.WdGoToDirection.wdGoToAbsolute;

            Word.Document P_document = _app.Documents.Add(ref missing, ref missing, ref missing);
            for (int i = 1; i <= ipagecount; i++)
            {
                if (i > 10)
                {
                    break;
                }
                Word.Range wrg1;
                Word.Range wrg2;
                Word.Range wrg;
                wrg1 = document.GoTo(ref pWhat, ref pWhich, i);
                wrg2 = wrg1.GoToNext(Word.WdGoToItem.wdGoToPage);
                wrg  = document.Range(wrg1.Start, wrg2.Start); //指定页的范围

                string strContent = wrg.Text;                  //获取该页内容

                Console.WriteLine(strContent);

                if (strContent.Contains("答辩日期"))
                {
                    wrg.Copy();
                    P_document.ActiveWindow.Selection.GoTo(ref What, ref Which, ref missing, ref missing);
                    P_document.ActiveWindow.Selection.Paste();
                }
            }
            P_document.ExportAsFixedFormat(@"D:\work\53002\20160823\131163876229304835\6\2062\20160822003\中共陕西省委党校2016年论文\xxxx.pdf", Word.WdExportFormat.wdExportFormatPDF);
            Console.WriteLine("over");
            P_document.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
            document.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
            _app.Quit();
            Console.ReadKey();
        }
Beispiel #8
0
        private static int ConvertWordToPdf(string sourcePath, string targetPath)
        {
            int    result       = -1;
            object paramMissing = Type.Missing;

            WORD.Application wordApplication = null;
            WORD.Document    wordDocument    = null;
            try
            {
                object source = sourcePath;
                wordApplication               = new WORD.Application();
                wordApplication.Visible       = false;
                wordApplication.DisplayAlerts = WORD.WdAlertLevel.wdAlertsNone;
                try
                {
                    wordDocument = wordApplication.Documents.OpenNoRepairDialog(
                        source, AddToRecentFiles: false,
                        ReadOnly: true, PasswordDocument: "IN_VA_LI______D");
                }
                catch
                {
                    return(result);
                }
                if (wordDocument != null)
                {
                    WORD.WdStatistic stat = WORD.WdStatistic.wdStatisticPages;
                    int num = wordDocument.ComputeStatistics(stat);

                    wordDocument.ExportAsFixedFormat(targetPath, WORD.WdExportFormat.wdExportFormatPDF, IncludeDocProps: true);
                    result = num;
                }
            }
            finally
            {
                if (wordDocument != null)
                {
                    wordDocument.Close(SaveChanges: false);
                    wordDocument = null;
                }
                if (wordApplication != null)
                {
                    wordApplication.Quit(SaveChanges: false);
                    wordApplication = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return(result);
        }
Beispiel #9
0
 //获取文档页数
 public int GetPageCount(string path)
 {
     try
     {
         myWordApp.Visible = false;
         object filePath = path; //这里是Word文件的路径
         //打开文件
         Microsoft.Office.Interop.Word.Document myWordDoc = myWordApp.Documents.Open(
             ref filePath, ref oMissing);
         //下面是取得打开文件的页数
         int pages = myWordDoc.ComputeStatistics(WdStatistic.wdStatisticPages, ref oMissing);
         myWordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
         return(pages);
     }
     catch (Exception ex)
     {
         return(0);
     }
 }
        /// <summary>
        /// Gets information about a document, such as page count, title, and author.
        /// </summary>
        /// <returns>A <see cref="DocumentProperties" /> object.</returns>
        public override DocumentProperties GetProperties()
        {
            DocumentProperties properties = new DocumentProperties(File);

            try
            {
                using (WordApp app = new WordApp())
                {
                    WordDocument document = app.Open(File);

                    // Page count must be calculated first - strange results otherwise
                    properties.Pages = (short)document.ComputeStatistics(WdStatistic.wdStatisticPages);

                    // Get the page orientation
                    switch (document.PageSetup.Orientation)
                    {
                    case WdOrientation.wdOrientPortrait:
                        properties.Orientation = Orientation.Portrait;
                        break;

                    case WdOrientation.wdOrientLandscape:
                        properties.Orientation = Orientation.Landscape;
                        break;
                    }

                    // Retrieve built-in document properties
                    properties.Title       = document.BuiltInDocumentProperties.Item["Title"].Value;
                    properties.Author      = document.BuiltInDocumentProperties.Item["Author"].Value;
                    properties.Application = document.BuiltInDocumentProperties.Item["Application Name"].Value;
                }
            }
            catch (COMException ex)
            {
                // Log the error, then return whatever properties have been collected.
                LogWarn("Failure retrieving properties: " + ex.Message);
            }

            return(properties);
        }
Beispiel #11
0
        public bool ReadPdf(string pdfFile, ref Documents doc, ref int pages)
        {
            bool success = false;

            try
            {
                if (pdfFile.ToLower().Contains("pdf"))
                {
                    StringBuilder textBuilder = new StringBuilder();
                    PdfReader     r           = new PdfReader(pdfFile);
                    pages = r.NumberOfPages;

                    for (int i = 1; i <= pages; i++)
                    {
                        PdfReaderContentParser  parser = new PdfReaderContentParser(r);
                        ITextExtractionStrategy st     = parser.ProcessContent <SimpleTextExtractionStrategy>(i, new SimpleTextExtractionStrategy());
                        string text = st.GetResultantText().Trim('\r', '\n', '\t', (char)32, (char)160);

                        if (!string.IsNullOrEmpty(text))
                        {
                            doc.DocBodyDic.Add(i, text);
                        }
                        else
                        {
                            text = PdfTextExtractor.GetTextFromPage(r, i).Trim('\r', '\n', '\t', (char)32, (char)160);

                            if (!string.IsNullOrEmpty(text))
                            {
                                doc.DocBodyDic.Add(i, text);
                            }
                        }
                    }

                    r.Close();
                    success = true;
                }
                else if (pdfFile.ToLower().Contains("doc"))
                {
                    MsWord.Application newApp = null;
                    MsWord.Document    msdoc  = null;

                    try
                    {
                        int retry = 2;
                        while (retry > 0)
                        {
                            try
                            {
                                //newApp = (MsWord.Application)Marshal.GetActiveObject("Word.Application");
                                newApp = newApp == null ? new MsWord.Application() : newApp;
                                System.Threading.Thread.Sleep(1000);
                                //msdoc = newApp.ActiveDocument;
                                msdoc = newApp.Documents.Open(pdfFile);
                                System.Threading.Thread.Sleep(1000);
                                object             nothing = Missing.Value;
                                MsWord.WdStatistic stat    = MsWord.WdStatistic.wdStatisticPages;
                                int num = msdoc.ComputeStatistics(stat, ref nothing);

                                for (int i = 1; i <= num; i++)
                                {
                                    if (doc.DocBodyDic.ContainsKey(i))
                                    {
                                        continue;
                                    }

                                    object objWhat  = MsWord.WdGoToItem.wdGoToPage;
                                    object objWhich = MsWord.WdGoToDirection.wdGoToAbsolute;

                                    object       objPage = (object)i;
                                    MsWord.Range range1  = msdoc.GoTo(ref objWhat, ref objWhich, ref objPage, ref nothing);
                                    MsWord.Range range2  = range1.GoToNext(MsWord.WdGoToItem.wdGoToPage);

                                    object objStart = range1.Start;
                                    object objEnd   = range2.Start;
                                    if (range1.Start == range2.Start)
                                    {
                                        objEnd = msdoc.Characters.Count;
                                    }

                                    Console.ForegroundColor = ConsoleColor.Red;
                                    Console.WriteLine("DEBUG: Path: {0}, {1}-{2}........", pdfFile, objStart, objEnd);
                                    Console.ResetColor();

                                    if ((int)objStart <= (int)objEnd)
                                    {
                                        string innerText = msdoc.Range(ref objStart, ref objEnd).Text;
                                        doc.DocBodyDic.Add(i, innerText);
                                    }
                                }

                                success = true;
                                break;
                            }
                            catch (Exception ex)
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("Retry to read word {0}, Exception: {1}..", pdfFile, ex.ToString());
                                Console.ResetColor();
                                System.Threading.Thread.Sleep(1000);
                                retry--;
                            }
                            finally
                            {
                                if (newApp != null)
                                {
                                    newApp.NormalTemplate.Saved = true;

                                    if (msdoc != null)
                                    {
                                        msdoc.Close(false);
                                    }

                                    newApp.Quit();
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                    }
                }
            }
            catch (Exception ex)
            {
            }

            return(success);
        }
Beispiel #12
0
    //static MSWord.Application wordApp = new MSWord.Application();

    private static string SaveDocx(object sourceFileName, bool isDelContext = false)
    {
        MSWord.Application wordApp = new MSWord.Application();
        wordApp.Visible = false;
        object targetFileName = Path.ChangeExtension((string)sourceFileName, "docx");
        object missingValue   = System.Reflection.Missing.Value;

        try
        {
            MSWord.Document doc = wordApp.Documents.Open(
                ref sourceFileName,
                ref missingValue, ref missingValue, ref missingValue, ref missingValue,
                ref missingValue, ref missingValue, ref missingValue, ref missingValue,
                ref missingValue, ref missingValue, ref missingValue, ref missingValue,
                ref missingValue, ref missingValue, ref missingValue);

            if (isDelContext)
            {
                doc.Tables[1].Range.Delete(missingValue, missingValue);
                doc.Tables[1].Delete();//.Range.Delete(missingValue, missingValue);
                var sectionCount = wordApp.ActiveDocument.Sections.Count;
                for (int i = 1; i <= sectionCount; i++)
                {
                    wordApp.ActiveDocument.Sections[i].Headers[MSWord.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Delete();
                    wordApp.ActiveDocument.Sections[i].Footers[MSWord.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Delete();
                }

                //---------------------------------------------

                object Unit1     = (int)MSWord.WdUnits.wdCharacter;
                object Count1    = 1;
                var    firstLine = doc.Paragraphs.First.Range;
                var    content   = firstLine.Text.Trim();
                while (string.IsNullOrEmpty(content))
                {
                    firstLine.Delete(ref Unit1, ref Count1);
                    firstLine = doc.Paragraphs.First.Range;
                    content   = firstLine.Text.Trim();
                }
                //------------------------删除空白页-------------------
                int    pages    = doc.ComputeStatistics(MSWord.WdStatistic.wdStatisticPages, ref missingValue);
                object objWhat  = MSWord.WdGoToItem.wdGoToPage;
                object objWhich = MSWord.WdGoToDirection.wdGoToAbsolute;
                object objPage  = 1;//指定页

                MSWord.Range range1 = doc.GoTo(ref objWhat, ref objWhich, ref objPage, ref missingValue);

                MSWord.Range range2 = range1.GoToNext(MSWord.WdGoToItem.wdGoToPage);

                object objStart = range1.Start;

                object objEnd = range2.Start;

                if (range1.Start == range2.Start)
                {
                    objEnd = doc.Characters.Count;//最后一页
                }
                string str = doc.Range(ref objStart, ref objEnd).Text;
                Console.WriteLine(str);

                if (string.IsNullOrEmpty(str.Trim()))
                {
                    object Unit  = (int)MSWord.WdUnits.wdCharacter;
                    object Count = 1;
                    doc.Range(ref objStart, ref objEnd).Delete(ref Unit, ref Count);
                }
            }


            object FileFormat              = MSWord.WdSaveFormat.wdFormatDocumentDefault;
            object LockComments            = false;
            object Password                = missingValue;
            object AddToRecentFiles        = false;
            object WritePassword           = missingValue;
            object ReadOnlyRecommended     = false;
            object EmbedTrueTypeFonts      = true;
            object SaveNativePictureFormat = missingValue;
            object SaveFormsData           = missingValue;
            object SaveAsAOCELetter        = missingValue;
            object Encoding                = missingValue;
            object InsertLineBreaks        = missingValue;
            object AllowSubstitutions      = missingValue;
            object LineEnding              = missingValue;
            object AddBiDiMarks            = missingValue;
            object CompatibilityMode       = missingValue;

            doc.SaveAs(ref targetFileName, ref FileFormat,
                       ref LockComments, ref Password, ref AddToRecentFiles, ref WritePassword,
                       ref ReadOnlyRecommended, ref EmbedTrueTypeFonts, ref SaveNativePictureFormat, ref SaveFormsData,
                       ref SaveAsAOCELetter, ref Encoding, ref InsertLineBreaks, ref AllowSubstitutions,
                       ref LineEnding, ref AddBiDiMarks);

            wordApp.Documents.Close(ref missingValue, ref missingValue, ref missingValue);

            //关闭进程
            object saveOption = MSWord.WdSaveOptions.wdDoNotSaveChanges;
            wordApp.Application.Quit(ref saveOption, ref missingValue, ref missingValue);
        }
        catch (Exception ex)
        {
            Console.WriteLine("转换错误=====" + ex.Message);
            object saveOption = MSWord.WdSaveOptions.wdDoNotSaveChanges;

            wordApp.Application.Quit(ref saveOption, ref missingValue, ref missingValue);
        }
        return(targetFileName as string);
    }
        public RtfParser(string path)
        {
            Application word = new Application();

            Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();
            Frames frames = null;

            object fileName = path;

            // Define an object to pass to the API for missing parameters
            object missing = System.Type.Missing;

            try
            {
                doc = word.Documents.Open(ref fileName,
                                          ref missing, ref missing, ref missing, ref missing,
                                          ref missing, ref missing, ref missing, ref missing,
                                          ref missing, ref missing, ref missing, ref missing,
                                          ref missing, ref missing, ref missing);

                this.Company   = new Dictionary <string, string>();
                this.Documents = new List <Dictionary <string, string> >();
                this.Rows      = new List <Dictionary <string, string> >();

                frames = doc.Frames;

                //Example delivery note "005.rtf":
                //
                //       <Company>
                //   4 -  <Name>FTORR Corp.</Name>
                //   5 -  <Address>5283 Laoreet St.</Address>
                //   6 -  <Zip>71272</Zip>
                //   6 -  <City>Bangor</City>
                //   6 -  <State>ME</State>
                //        <Country>United States</Country>
                //   15 - <FiscalCode>06392640964</FiscalCode>
                //        <VatCode>06392640964</VatCode>
                //       </Company>
                //       <Documents>
                //         <Document>
                //   50 -    <CustomerCode>5476</CustomerCode>
                //   19 -    <SoldToName>Pellentesque Consulting</SoldToName>
                //   18 -    <ShipToName>Neque Et Associates</ShipToName>
                //   21 -    <ShipToAddress>Ap #327-6373 Fusce St.</ShipToAddress>
                //   23 -    <ShipToZip>47019</ShipToZip>
                //   23 -    <ShipToCity>Essex</ShipToCity>
                //   23 -    <ShipToState>VI</ShipToState>


                //   37 -    <Date>2019-01-22</Date> //Document date


                //   39 -    <Number>152</Number>
                //   54 -    <TransportReason>Sale</TransportReason>
                //   145 -    <TransportDateTime>22/01/2019 17:28</TransportDateTime>
                //           <Rows>
                //             <Row>
                //               <Code>2014</Code>
                //               <Description>Glipizide</Description>
                //               <Qty>12,00</Qty>
                //             </Row>
                //              ...
                //         </Document>
                //       </Documents>
                //
                // Note: not all fields are used.

                this.Company.Add("Name", frames[4].Range.Text);

                this.Company.Add("Address", frames[5].Range.Text);

                string[] companyLocationZipCityState = frames[6].Range.Text.Split(' ');

                this.Company.Add("Zip", companyLocationZipCityState[0]);

                StringBuilder City = new StringBuilder();

                for (int i = 1; i < companyLocationZipCityState.Length - 1; i++)
                {
                    City.Append(companyLocationZipCityState[i]);

                    if (i != companyLocationZipCityState.Length - 2)
                    {
                        City.Append(" ");
                    }
                }

                this.Company.Add("City", City.ToString());

                this.Company.Add("State", companyLocationZipCityState[companyLocationZipCityState.Length - 1]);

                this.Company.Add("Country", "United States");

                //this.Company.Add("FiscalCode", frames[15].Range.Text);

                //this.Company.Add("VatCode", frames[15].Range.Text);

                Dictionary <string, string> document = new Dictionary <string, string>();

                document.Add("CustomerCode", frames[50].Range.Text);

                ExcelSheetParser xlsParser
                    = new ExcelSheetParser(string.Format(@"{0}",
                                                         CodeManager.CustomerDataFilePath));

                this.Discounts = xlsParser.GetDiscounts(document["CustomerCode"]);

                document.Add("CustomerName", frames[19].Range.Text);

                document.Add("DeliveryName", frames[18].Range.Text);

                City = new StringBuilder();

                string[] deliveryLocationZipCityState = frames[23].Range.Text.Split(' ');

                for (int i = 1; i < deliveryLocationZipCityState.Length - 1; i++)
                {
                    City.Append(deliveryLocationZipCityState[i]);

                    if (i != deliveryLocationZipCityState.Length - 2)
                    {
                        City.Append(" ");
                    }
                }

                document.Add("DeliveryAddress", frames[21].Range.Text);

                document.Add("DeliveryZip", deliveryLocationZipCityState[0]);

                document.Add("DeliveryCity", City.ToString());

                document.Add("DeliveryState", deliveryLocationZipCityState[deliveryLocationZipCityState.Length - 1]);

                // document.Add("DocumentType", "D");

                string[] documentDateArray = frames[37].Range.Text.Split('/');
                Array.Reverse(documentDateArray);
                string documentDateString = String.Join("-", documentDateArray);

                document.Add("Date", documentDateString);

                document.Add("Number", (frames[39].Range.Text).Trim());

                //document1.Add("TransportReason", frames[54].Range.Text);

                //document1.Add("TransportDateTime", frames[145].Range.Text);

                this.Documents.Add(document);

                //Calculate number of pages
                Microsoft.Office.Interop.Word.WdStatistic numOfPagesStat
                    = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages;

                int numOfPages  = doc.ComputeStatistics(numOfPagesStat, ref missing);
                int currentPage = 1;

                int itemCodePos = 0;

                //Repeat code in the "while" block for each page
                while (currentPage <= numOfPages)
                {
                    //First item code (in each page) is always at the 62th position.
                    if (frames[62].Range.Text != null) //Check whether items exist
                    {
                        //In each page, the first item position can be found at multiple of 62
                        itemCodePos += 62;

                        int loopCounter = 0;

                        //frames[itemCodePos+4] is the "Qty" column of the first item. If this is empty, it means customer name and
                        //address lines have been incorrectly used as the article description for one or more articles.
                        while (frames[itemCodePos + 4].Range.Text == null)
                        {
                            //Let's explain this with an example: (see example file: "customer-data-in-description-field.rtf"
                            //
                            //if three lines of article description contain:
                            //
                            //   DESCRIPTION
                            //
                            //   Eu Corp.
                            //   3019 A, Av.
                            //   23807 Tulsa OK
                            //
                            //then: itemCodePos+3 is: "3019 A, Av."
                            //      itemCodePos+6 is: "23807 Tulsa OK"
                            //
                            //and so on incrementing by multiples of three
                            itemCodePos += 3;

                            //We know when at the next iteration we'll find the first item code, because at that
                            //point frames[itemCodePos + 4] is going to contain the first item description, hence it will
                            //not be empty anymore
                            if (frames[itemCodePos + 4].Range.Text != null)
                            {
                                //Again, referring to previous example, if frames[itemCodePos + 4] contains an item description,
                                //this means we are on the last line of the customer address (in the description column).
                                //
                                //If this is the last line of a customer address, then moving three positions onward, we'll find
                                //our first item code.
                                //
                                //So, here we move where the item code is and before exiting the loop.
                                itemCodePos += 3;

                                //Before exiting the loop, warn the user that the item description incorrectly contains the personal
                                //data of a customer
                                System_Windows_Forms.MessageBox.Show("Warning: the customer data in this delivery note has been incorrectly placed in the \"DESCRIPTION\" field of one or more items.\n\nThe XML file will be generated anyway.",
                                                                     "Document not well formed",
                                                                     System_Windows_Forms.MessageBoxButtons.OK,
                                                                     System_Windows_Forms.MessageBoxIcon.Warning);
                            }

                            //Just in case, if for any reason the code logic here turns into an infinite loop, exit
                            //after max 10000 iterations
                            if (loopCounter > 10000)
                            {
                                throw new Exception("error while fetching item data.");
                            }

                            loopCounter++;
                        }

                        int itemDescriptionPos = itemCodePos + 1;

                        //Oddly enough, quantity for the first item comes before its code
                        int itemQtyPos = itemCodePos - 1;

                        do
                        {
                            Dictionary <string, string> row = new Dictionary <string, string>();

                            string itemCode = frames[itemCodePos].Range.Text;

                            row.Add("Code", itemCode);
                            row.Add("Description", frames[itemDescriptionPos].Range.Text);
                            row.Add("Qty", frames[itemQtyPos].Range.Text);
                            row.Add("Discounts", this.Discounts);

                            this.Rows.Add(row);

                            if ((frames[itemDescriptionPos + 2].Range.Text != null) &&
                                (frames[itemDescriptionPos + 2].Range.Text.Trim().ToUpper() == "EXTERNAL PACKAGE"))
                            {
                                //itemDescriptionPos + 2 is the position of the frame containg the string: "EXTERNAL PACKAGE".
                                //Add 15 to it to move to the last frame in the page (it's in the footer on the right and i's empty)
                                //Remember, in each page the first item position can be found at multiple of 62
                                itemCodePos = itemDescriptionPos + 2 + 15;

                                //Used for testing:
                                //string testValue = frames[nextItemCodePos].Range.Text ?? "NULL";

                                break;
                            }

                            itemCodePos       += 5;
                            itemDescriptionPos = itemCodePos + 1;
                            itemQtyPos         = itemCodePos - 1;
                        } while (true);
                    }

                    currentPage++;
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                //Release com objects to fully kill Word process from running in
                //the background
                CodeManager.ReleaseComObject(frames);
                frames = null;

                //Close and release
                ((_Document)doc).Close();
                CodeManager.ReleaseComObject(doc);
                doc = null;

                //Quit and release
                if (word != null)
                {
                    ((_Application)word).Quit();
                }

                CodeManager.ReleaseComObject(word);
                word = null;

                GC.Collect();
            }
        }
Beispiel #14
0
        /// <summary>
        /// 生成word测试报告
        /// </summary>
        public void CreateWordReport()
        {
            object nothing = Missing.Value;

            wordDoc = wordApp.Documents.Add(ref nothing, ref nothing, ref nothing, ref nothing);
            //页面参数设置
            wordApp.ActiveDocument.PageSetup.SectionStart = WdSectionStart.wdSectionContinuous;//节的起始位置:新建页

            object Unit   = Microsoft.Office.Interop.Word.WdUnits.wdStory;
            object Extend = Microsoft.Office.Interop.Word.WdMovementType.wdMove;

            //wordDoc.ActiveWindow.Selection.EndKey(ref Unit, ref Extend);
            //wordDoc.ActiveWindow.Selection.TypeParagraph();

            #region 标题部分

            strcontent = "中国人民解放军六一一九五部队第三计量站\n";
            InsertContent(WdParagraphAlignment.wdAlignParagraphCenter, strcontent, 16, 1, "宋体", 0);                 //三号
            strcontent = "The third Metrology Station of the PLA Unit 61195 \n";
            InsertContent(WdParagraphAlignment.wdAlignParagraphCenter, strcontent, 10.5f, 0, "Times New Roman", 0); //五号

            strcontent = "测 试 报 告\n";
            InsertContent(WdParagraphAlignment.wdAlignParagraphCenter, strcontent, 36, 10, "隶书", 0);   //小初
            strcontent = "Test Certificate\n\r";
            InsertContent(WdParagraphAlignment.wdAlignParagraphCenter, strcontent, 10.5f, 0, "宋体", 0); //五号

            strcontent = "证书编号:";
            InsertContent(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 12, 0, "黑体", 0);
            strcontent = "RX12174\n";
            InsertContent(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 12, 0, "Times New Roman", 0);
            strcontent = "Certificate No.\n\r\r\r";
            InsertContent(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 9.0f, 0, "Times New Roman", 1);//小五

            #endregion

            #region 添加第一个表格

            start = wordDoc.Content.End - 1;
            ///绘制表格
            AddTables(2, 1, "0.8", 10.5f); //两行,一列
            AddTables(2, 2, "0.8", 10.5f); //两行,两列

            //[1,1]
            InsertContToCell(1, WdParagraphAlignment.wdAlignParagraphLeft, 1, 1, "送检单位:   \nApplicant", "宋体", 10.5f, 0, 0);
            //指定内容
            end   = wordDoc.Content.End - 5;
            start = int.Parse(end.ToString()) - 16;
            SetStyles(WdParagraphAlignment.wdAlignParagraphLeft, "Times New Roman", 9.0f, 0, 1);

            start = wordDoc.Content.End - 10;
            //[2,1]
            InsertContToCell(1, WdParagraphAlignment.wdAlignParagraphLeft, 2, 1, "地址:北京市\nAddres", "宋体", 10.5f, 0, 0);
            end   = wordDoc.Content.End - 9;
            start = int.Parse(end.ToString()) - 6;
            SetStyles(WdParagraphAlignment.wdAlignParagraphLeft, "Times New Roman", 9.0f, 0, 1);

            start = wordDoc.Content.End - 1;
            //[3,1]
            InsertContToCell(1, WdParagraphAlignment.wdAlignParagraphLeft, 3, 1, "仪器名称:超短波数字化接收机\nInstrument name", "宋体", 10.5f, 0, 0);
            //指定内容
            end   = wordDoc.Content.End - 7;
            start = int.Parse(end.ToString()) - 15;
            SetStyles(WdParagraphAlignment.wdAlignParagraphLeft, "Times New Roman", 9.0f, 0, 1);


            start = wordDoc.Content.End - 1;
            //[3,2]
            InsertContToCell(1, WdParagraphAlignment.wdAlignParagraphLeft, 3, 2, "制造商:常州无线电厂\nManufacturer", "宋体", 10.5f, 0, 0);
            //指定内容
            end   = wordDoc.Content.End - 6;
            start = int.Parse(end.ToString()) - 12;
            SetStyles(WdParagraphAlignment.wdAlignParagraphLeft, "Times New Roman", 9.0f, 0, 1);

            start = wordDoc.Content.End - 1;
            //[4,1]
            InsertContToCell(1, WdParagraphAlignment.wdAlignParagraphLeft, 4, 1, "型号:SSC018A\nType", "宋体", 10.5f, 0, 0);
            //指定内容
            end   = wordDoc.Content.End - 4;
            start = int.Parse(end.ToString()) - 4;
            SetStyles(WdParagraphAlignment.wdAlignParagraphLeft, "Times New Roman", 9.0f, 0, 1);

            start = wordDoc.Content.End - 1;
            //[4,2]
            InsertContToCell(1, WdParagraphAlignment.wdAlignParagraphLeft, 4, 2, "编号:08004\nNo.", "宋体", 10.5f, 0, 0);
            //指定内容
            end   = wordDoc.Content.End - 3;
            start = int.Parse(end.ToString()) - 3;
            SetStyles(WdParagraphAlignment.wdAlignParagraphLeft, "Times New Roman", 9.0f, 0, 1);

            #endregion
            //页首插入行
            wordDoc.ActiveWindow.Selection.TypeParagraph();
            wordDoc.ActiveWindow.Selection.EndKey(ref Unit, ref Extend);
            wordDoc.ActiveWindow.Selection.TypeParagraph();

            start      = wordDoc.Content.End - 1;
            end        = start;
            strcontent = "\r                                    \r\r\r\r";
            InsertContent(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 10.5f, 0, "Times New Roman", 0);//小五

            #region 添加第二个表格

            AddTables(3, 2, "0.8", 10.5f);

            //[1,1]
            InsertContToCell(2, WdParagraphAlignment.wdAlignParagraphLeft, 1, 1, "测试人:\nOperato", "宋体", 10.5f, 0, 0);
            //指定内容
            end   = wordDoc.Content.End - 9;
            start = int.Parse(end.ToString()) - 9;
            SetStyles(WdParagraphAlignment.wdAlignParagraphLeft, "Times New Roman", 9.0f, 0, 1);

            start = wordDoc.Content.End - 1;
            //[1,2]
            InsertContToCell(2, WdParagraphAlignment.wdAlignParagraphLeft, 1, 2, "发证日期:" + DateTime.Now.ToLongDateString() + "\nIssued date", "宋体", 10.5f, 0, 0);
            //指定内容
            end   = wordDoc.Content.End - 8;
            start = int.Parse(end.ToString()) - 12;
            SetStyles(WdParagraphAlignment.wdAlignParagraphLeft, "Times New Roman", 9.0f, 0, 1);

            start = wordDoc.Content.End - 1;
            //[2,1]
            InsertContToCell(2, WdParagraphAlignment.wdAlignParagraphLeft, 2, 1, "审核员:\nInspector", "宋体", 10.5f, 0, 0);
            //指定内容
            end   = wordDoc.Content.End - 7;
            start = int.Parse(end.ToString()) - 10;
            SetStyles(WdParagraphAlignment.wdAlignParagraphLeft, "Times New Roman", 9.0f, 0, 1);

            start = wordDoc.Content.End - 1;
            //[3,1]
            InsertContToCell(2, WdParagraphAlignment.wdAlignParagraphLeft, 3, 1, "签发人:\nDirector", "宋体", 10.5f, 0, 0);
            //指定内容
            end   = wordDoc.Content.End - 4;
            start = int.Parse(end.ToString()) - 8;
            SetStyles(WdParagraphAlignment.wdAlignParagraphLeft, "Times New Roman", 9.0f, 0, 1);

            start = wordDoc.Content.End - 1;
            //[3,2]
            InsertContToCell(2, WdParagraphAlignment.wdAlignParagraphLeft, 3, 2, "发证单位:(专用章)\nIssued By (stamp)", "宋体", 10.5f, 0, 0);
            //指定内容
            end   = wordDoc.Content.End - 3;
            start = int.Parse(end.ToString()) - 17;
            SetStyles(WdParagraphAlignment.wdAlignParagraphLeft, "Times New Roman", 9.0f, 0, 1);//小五

            start      = wordDoc.Content.End - 1;
            end        = start;
            strcontent = "\r\r\r\r";
            InsertContent(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 10.5f, 0, "Times New Roman", 0);


            #endregion

            #region 联系方式
            start      = wordDoc.Content.End - 1;
            end        = start;
            strcontent = "通信地址(Add):北京市5102信箱201号 (5102-201,Beijing)             邮编(Post Code):100094\r";
            InsertContent(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 9.0f, 0, "Times New Roman", 0);

            start = int.Parse(start.ToString()) - 71;
            end   = int.Parse(start.ToString()) + 3;
            SetStyles(WdParagraphAlignment.wdAlignParagraphLeft, "Times New Roman", 9.0f, 0, 1);//小五

            start = wordDoc.Content.End - 19;
            end   = int.Parse(start.ToString()) + 9;
            SetStyles(WdParagraphAlignment.wdAlignParagraphLeft, "Times New Roman", 9.0f, 0, 1);//小五

            start      = wordDoc.Content.End - 1;
            end        = start;
            strcontent = "联系电话(Tel):010-66324147,010-66324148                           传真(Fax):010-66766671\r\n";
            InsertContent(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 9.0f, 0, "Times New Roman", 0);

            start = int.Parse(start.ToString()) - 78;
            end   = int.Parse(start.ToString()) + 3;
            SetStyles(WdParagraphAlignment.wdAlignParagraphLeft, "Times New Roman", 9.0f, 0, 1);//小五

            start = wordDoc.Content.End - 19;
            end   = int.Parse(start.ToString()) + 3;
            SetStyles(WdParagraphAlignment.wdAlignParagraphLeft, "Times New Roman", 9.0f, 0, 1);//小五

            #endregion

            //插入分页符
            InsertBreak();

            #region 第二页
            //首行缩进
            FirstLineIndent(25.1f);
            start = wordDoc.Content.End - 1;
            end   = start;
            longstr.Append("\n本计量站于1992年经原国防科工委考核认可成立(认可证书号:1992国防计认字第152号)");
            longstr.Append(",并于2010年通过中国人民解放军总装备部军用实验室的认可(认可证书号:校/测[2011-05]。\n");
            InsertContent(WdParagraphAlignment.wdAlignParagraphLeft, longstr.ToString(), 10.5f, 0, "宋体", 0);


            //取消首行缩进
            FirstLineIndent(0f);
            start      = wordDoc.Content.End - 1;
            end        = start;
            strcontent = "   ";
            InsertContent(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 10.5f, 0, "Times New Roman", 0);

            start = wordDoc.Content.End - 1;
            end   = start;
            longstr.Remove(0, longstr.Length);
            longstr.Append("This metrology station was accredited by the former Committee of Science and Technology Industry of ");
            longstr.Append("National Defense and established in 1992 (accreditation Certificate No.:1992 guo fang ji ren zi No.152). In ");
            longstr.Append("2010,the station was accredited by the PLA about the laboratory for the army (accreditation Certificate No.: ");
            longstr.Append("Jiao/Ce[ 2011-05].\r\n");
            InsertContent(WdParagraphAlignment.wdAlignParagraphLeft, longstr.ToString(), 9.0f, 0, "Times New Roman", 1);

            start      = wordDoc.Content.End - 1;
            end        = start;
            strcontent = "     \r\r";
            InsertContent(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 10.5f, 0, "Times New Roman", 0);


            start      = wordDoc.Content.End - 1;
            end        = start;
            strcontent = "测试中使用的主要测量设备(Equipments used in the test)";
            InsertContent(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 10.5f, 0, "宋体", 0);

            start = int.Parse(start.ToString()) - 28;
            end   = int.Parse(start.ToString()) + 27;
            SetStyles(WdParagraphAlignment.wdAlignParagraphLeft, "Times New Roman", 9.0f, 0, 1);//小五


            #region 第三个表格
            //添加表格
            AddTables(7, 5, "0.8", 10.5f);
            ///设置单元格剧中
            for (int i = 1; i < 8; i++)
            {
                for (int j = 1; j < 6; j++)
                {
                    wordDoc.Tables[3].Cell(i, j).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                }
            }

            SetColumnsWidth();

            InsertContToCell(3, 1, 1, "名称(Name)", WdParagraphAlignment.wdAlignParagraphCenter, 4, 44, WdColor.wdColorBlack, "Times New Roman", 0, 10.5f, 1);

            InsertContToCell(3, 1, 2, "型号(Type)", WdParagraphAlignment.wdAlignParagraphCenter, 4, 43, WdColor.wdColorBlack, "Times New Roman", 0, 10.5f, 1);

            InsertContToCell(3, 1, 3, "编号(No.)", WdParagraphAlignment.wdAlignParagraphCenter, 3, 42, WdColor.wdColorBlack, "Times New Roman", 0, 10.5f, 1);

            InsertContToCell(3, 1, 4, "证书号\r(Cert. No.)", WdParagraphAlignment.wdAlignParagraphCenter, 9, 41, WdColor.wdColorBlack, "Times New Roman", 0, 10.5f, 1);
            end   = wordDoc.Content.End - 52;
            start = int.Parse(end.ToString()) - 3;
            SetStyles(WdParagraphAlignment.wdAlignParagraphCenter, "宋体", 10.5f, 0, 0);

            InsertContToCell(3, 1, 5, "有效期至\r(Cal Due Date)", WdParagraphAlignment.wdAlignParagraphCenter, 12, 40, WdColor.wdColorBlack, "Times New Roman", 0, 10.5f, 1);
            end   = wordDoc.Content.End - 56;
            start = int.Parse(end.ToString()) - 4;
            SetStyles(WdParagraphAlignment.wdAlignParagraphCenter, "宋体", 10.5f, 0, 0);
            //第二行
            InsertContToCell(3, 2, 1, "信号发生器", WdParagraphAlignment.wdAlignParagraphLeft, 6, 36, WdColor.wdColorRed, "宋体", 0, 10.5f, 0);
            InsertContToCell(3, 2, 2, "8648B", WdParagraphAlignment.wdAlignParagraphLeft, 6, 35, WdColor.wdColorRed, "宋体", 0, 10.5f, 0);
            InsertContToCell(3, 2, 3, "3847U02406", WdParagraphAlignment.wdAlignParagraphCenter, 11, 34, WdColor.wdColorRed, "宋体", 0, 10.5f, 0);
            InsertContToCell(3, 2, 4, "SG12026", WdParagraphAlignment.wdAlignParagraphCenter, 8, 33, WdColor.wdColorRed, "宋体", 0, 10.5f, 0);
            InsertContToCell(3, 2, 5, "2014.06.05", WdParagraphAlignment.wdAlignParagraphCenter, 11, 32, WdColor.wdColorRed, "宋体", 0, 10.5f, 0);

            //第三行
            InsertContToCell(3, 3, 1, "信号发生器", WdParagraphAlignment.wdAlignParagraphLeft, 6, 31, WdColor.wdColorRed, "宋体", 0, 10.5f, 0);
            InsertContToCell(3, 3, 2, "E4432B", WdParagraphAlignment.wdAlignParagraphLeft, 6, 30, WdColor.wdColorRed, "宋体", 0, 10.5f, 0);
            InsertContToCell(3, 3, 3, "GB40050869", WdParagraphAlignment.wdAlignParagraphLeft, 11, 29, WdColor.wdColorRed, "宋体", 0, 10.5f, 0);
            InsertContToCell(3, 3, 4, "SG12024", WdParagraphAlignment.wdAlignParagraphCenter, 8, 28, WdColor.wdColorRed, "宋体", 0, 10.5f, 0);
            InsertContToCell(3, 3, 5, "2013.06.05", WdParagraphAlignment.wdAlignParagraphCenter, 11, 27, WdColor.wdColorRed, "宋体", 0, 10.5f, 0);

            //第四行
            InsertContToCell(3, 4, 1, "频谱分析仪", WdParagraphAlignment.wdAlignParagraphLeft, 6, 25, WdColor.wdColorRed, "宋体", 0, 10.5f, 0);
            InsertContToCell(3, 4, 2, "HP8563E", WdParagraphAlignment.wdAlignParagraphLeft, 7, 24, WdColor.wdColorRed, "宋体", 0, 10.5f, 0);
            InsertContToCell(3, 4, 3, "3751A08296", WdParagraphAlignment.wdAlignParagraphLeft, 11, 23, WdColor.wdColorRed, "宋体", 0, 10.5f, 0);
            InsertContToCell(3, 4, 4, "SA12042", WdParagraphAlignment.wdAlignParagraphCenter, 8, 22, WdColor.wdColorRed, "宋体", 0, 10.5f, 0);
            InsertContToCell(3, 4, 5, "2013.06.05", WdParagraphAlignment.wdAlignParagraphCenter, 11, 21, WdColor.wdColorRed, "宋体", 0, 10.5f, 0);


            #endregion
            strcontent = "标准装置的不确定度:\r";
            InsertContent2(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 10.5f, 0, "宋体", 0, WdColor.wdColorBlack);

            strcontent = "Uncertainty of measurement standard\r";
            InsertContent2(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 9.0f, 0, "Times New Roman", 1, WdColor.wdColorBlack);

            FirstLineIndent(25.1f);
            strcontent = "频率测量准确度:1×10-8\r";
            InsertContent2(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 10.5f, 0, "宋体", 0, WdColor.wdColorRed);

            end   = wordDoc.Content.End - 2;
            start = int.Parse(end.ToString()) - 6;
            SetStyles(WdParagraphAlignment.wdAlignParagraphLeft, "Times New Roman", 10.5f, 0, 0);
            int s = wordDoc.Content.End - 4;
            int e = s + 2;
            SetStyles(s, e);

            strcontent = "电平准确度:±0.5dB\r";
            InsertContent2(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 10.5f, 0, "宋体", 0, WdColor.wdColorRed);
            end   = wordDoc.Content.End - 2;
            start = int.Parse(end.ToString()) - 6;
            SetStyles(WdParagraphAlignment.wdAlignParagraphLeft, "Times New Roman", 10.5f, 0, 0);

            strcontent = "失真测试准确度:±1dB\r\r";
            InsertContent2(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 10.5f, 0, "宋体", 0, WdColor.wdColorRed);
            end   = wordDoc.Content.End - 3;
            start = int.Parse(end.ToString()) - 4;
            SetStyles(WdParagraphAlignment.wdAlignParagraphLeft, "Times New Roman", 10.5f, 0, 0);

            //取消首行缩进
            FirstLineIndent(0f);

            strcontent = "测试所依据的技术文件或者校准方法:\r";
            InsertContent2(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 10.5f, 0, "宋体", 0, WdColor.wdColorBlack);

            strcontent = "Reference document or methods for test\r";
            InsertContent2(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 9.0f, 0, "Times New Roman", 1, WdColor.wdColorBlack);

            strcontent = "\rGB/T6394-1995《短波单边带接收机电性能测量方法》\r";
            InsertContent2(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 10.5f, 0, "宋体", 0, WdColor.wdColorBlack);
            strcontent = "GJB4210.1-2001《军用无线电通用设备通用检验验收规程(超短波电台)》\r";
            InsertContent2(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 10.5f, 0, "宋体", 0, WdColor.wdColorBlack);
            strcontent = "GJB4264-2001《超短波通信侦察系统通用规范》\r\r\r";
            InsertContent2(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 10.5f, 0, "宋体", 0, WdColor.wdColorBlack);

            strcontent = "测试的环境条件\r";
            InsertContent2(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 10.5f, 0, "宋体", 0, WdColor.wdColorBlack);

            strcontent = "Environmental condition in the test";
            InsertContent2(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 9.0f, 0, "Times New Roman", 1, WdColor.wdColorBlack);

            #region 添加第四个表

            strcontent = "\r";
            InsertContent2(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 9.0f, 0, "Times New Roman", 0, WdColor.wdColorBlack);
            AddTables(1, 2, "0.5", 10.5f);

            InsertContToCell(4, 1, 1, "温度:19℃", WdParagraphAlignment.wdAlignParagraphLeft, 6, 4, WdColor.wdColorBlack, "宋体", 0, 10.5f, 0);
            InsertContToCell(4, 1, 2, "相对湿度:22%", WdParagraphAlignment.wdAlignParagraphLeft, 8, 3, WdColor.wdColorBlack, "宋体", 0, 10.5f, 0);

            strcontent = "\r本结果仅对所测试样品有效。证书未经本站批准,不准部分复印。\r";
            InsertContent2(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 9.0f, 0, "宋体", 0, WdColor.wdColorBlack);
            //首行缩进设置
            FirstLineIndent(12.5f);
            strcontent = "These results apply only to the tested sample. The certificates must not be partially duplicated without permission from the Station at which the calibration has been conducted.\n";
            InsertContent2(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 7.5f, 0, "Times New Roman", 1, WdColor.wdColorBlack);
            //FirstLineIndent(0f);

            //插入分页符
            InsertBreak();

            #endregion

            #endregion

            #region 第三页  检测结果
            FirstLineIndent(0f);
            //固定1
            end        = wordDoc.Content.End - 1;
            start      = end;
            strcontent = "1.外观及功能性检查\r";
            InsertContent2(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 12f, 1, "宋体", 0, WdColor.wdColorBlack);

            FirstLineIndent(32.5f);
            end        = wordDoc.Content.End - 1;
            start      = end;
            strcontent = "外观良好、功能正常\r";
            InsertContent2(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 12f, 0, "宋体", 0, WdColor.wdColorBlack);
            FirstLineIndent(0f);

            //固定2
            end        = wordDoc.Content.End - 1;
            start      = end;
            strcontent = "2.频率范围\r";
            InsertContent2(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 12f, 1, "宋体", 0, WdColor.wdColorBlack);

            FirstLineIndent(32.5f);
            end        = wordDoc.Content.End - 1;
            start      = end;
            strcontent = "20.00000MHz~1000.00000MHz\r";
            InsertContent2(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 12f, 0, "宋体", 0, WdColor.wdColorBlack);
            FirstLineIndent(0f);

            //固定3
            end        = wordDoc.Content.End - 1;
            start      = end;
            strcontent = "3.频率分辨率\r";
            InsertContent2(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 12f, 1, "宋体", 0, WdColor.wdColorBlack);

            FirstLineIndent(32.5f);
            end        = wordDoc.Content.End - 1;
            start      = end;
            strcontent = "最小调谐步进或分辨率实测值为 10 Hz   \r";
            InsertContent2(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 12f, 0, "宋体", 0, WdColor.wdColorBlack);
            FirstLineIndent(0f);

            //固定4
            end        = wordDoc.Content.End - 1;
            start      = end;
            strcontent = "4.BFO范围\r";
            InsertContent2(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 12f, 1, "宋体", 0, WdColor.wdColorBlack);

            FirstLineIndent(32.5f);
            end        = wordDoc.Content.End - 1;
            start      = end;
            strcontent = "-5000Hz~+5000Hz\r";
            InsertContent2(WdParagraphAlignment.wdAlignParagraphLeft, strcontent, 12f, 0, "宋体", 0, WdColor.wdColorBlack);
            FirstLineIndent(0f);



            #endregion

            #region 页眉、页脚
            wordApp.ActiveWindow.View.Type     = WdViewType.wdOutlineView;
            wordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;

            wordApp.ActiveWindow.ActivePane.Selection.ParagraphFormat.Borders[WdBorderType.wdBorderBottom].LineStyle = WdLineStyle.wdLineStyleNone;
            wordApp.ActiveWindow.ActivePane.Selection.ParagraphFormat.Borders[WdBorderType.wdBorderBottom].Visible   = false;


            //获取文档的页数
            object oMissing = System.Reflection.Missing.Value;
            int    pages    = wordDoc.ComputeStatistics(WdStatistic.wdStatisticPages, ref oMissing);


            //设置分节符
            //for (int i = 3; i <= pages; i++)
            //{
            //    Range range = GetPages(i);
            //    object oCollapseEnd = WdCollapseDirection.wdCollapseEnd;
            //    object oPageBreak = WdBreakType.wdSectionBreakContinuous;//分页符
            //    range.Collapse(ref oCollapseEnd);
            //    range.InsertBreak(ref oPageBreak);
            //    range.Collapse(ref oCollapseEnd);
            //}

            //取消链接上一节。。
            int secs = wordDoc.Sections.Count;
            for (int p = 1; p <= secs; p++)
            {
                wordDoc.Sections[p].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].LinkToPrevious = false;
                wordDoc.Sections[p].Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].LinkToPrevious = false;
            }

            string firstLine  = "";
            string secondLine = "";

            object down = 0;
            object up   = 0;
            for (int iP = 1; iP <= pages; iP++)
            {
                switch (iP)
                {
                case 1:
                    firstLine  = "证书编号:RX12174                                              " + getPageDes(false, iP, pages);
                    secondLine = "\rCertificate No                                                        " + getPageDes(true, iP, pages);
                    wordApp.ActiveWindow.ActivePane.Selection.InsertAfter(firstLine);
                    wordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;

                    wordApp.ActiveWindow.ActivePane.Selection.InsertAfter(secondLine);
                    wordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                    wordApp.Selection.Font.Size = 10.5f;
                    wordApp.Selection.Font.Name = "Times New Roman";

                    wordApp.ActiveWindow.ActivePane.Selection.GoToNext(WdGoToItem.wdGoToSection);
                    break;

                case 2:
                    wordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekCurrentPageHeader;
                    firstLine  = "证书编号:RX12174                                              " + getPageDes(false, iP, pages);
                    secondLine = "\rCertificate No                                                        " + getPageDes(true, iP, pages);
                    wordApp.ActiveWindow.ActivePane.Selection.InsertAfter(firstLine);
                    wordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;

                    wordApp.ActiveWindow.ActivePane.Selection.InsertAfter(secondLine);
                    wordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                    wordApp.Selection.Font.Size = 10.5f;
                    wordApp.Selection.Font.Name = "Times New Roman";

                    wordApp.ActiveWindow.ActivePane.Selection.GoToNext(WdGoToItem.wdGoToSection);
                    break;

                default:
                    wordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekCurrentPageHeader;
                    firstLine  = "证书编号:RX12174                                              " + getPageDes(false, iP, pages);
                    secondLine = "\rCertificate No                                                       " + getPageDes(true, iP, pages);
                    wordApp.ActiveWindow.ActivePane.Selection.InsertAfter(firstLine);
                    wordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;

                    wordApp.ActiveWindow.ActivePane.Selection.InsertAfter(secondLine + "\r");
                    wordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;

                    wordApp.ActiveWindow.ActivePane.Selection.InsertAfter("测试结果\rTestResult");
                    wordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                    wordApp.Selection.Font.Size = 10.5f;
                    wordApp.Selection.Font.Name = "Times New Roman";

                    //页脚设置
                    wordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekCurrentPageFooter;
                    firstLine  = "测试人(签字):                            审核员(签字):";
                    secondLine = "\rOperator                                   Inspector ";
                    wordApp.ActiveWindow.ActivePane.Selection.InsertAfter(firstLine);
                    wordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;

                    wordApp.ActiveWindow.ActivePane.Selection.InsertAfter(secondLine);
                    wordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                    wordApp.Selection.Font.Italic = 1;
                    wordApp.Selection.Font.Size   = 10.5f;
                    wordApp.Selection.Font.Name   = "Times New Roman";

                    wordApp.ActiveWindow.ActivePane.Selection.GoToNext(WdGoToItem.wdGoToSection);
                    break;
                }
            }



            //关闭文档
            //object saveOption = WdSaveOptions.wdDoNotSaveChanges;
            //wordDoc.Close(ref nothing,ref nothing,ref nothing);
            //wordApp.Application.Quit(ref saveOption, ref nothing, ref nothing);

            //wordDoc = null;
            //wordApp = null;

            //ShellExecute(IntPtr.Zero,"open","c:\\new.doc","","",3);

            #endregion

            /*
             */



            wordApp.Visible = true;
        }
Beispiel #15
0
        private void button2_Click(object sender, EventArgs e)
        {
            if (listBox1.Items.Count <= 1)
            {
                return;
            }
            Object filename              = "test.docx";
            Object filefullname          = @theStrPath[0];
            Object confirmConversions    = Type.Missing;
            Object readOnly              = false;
            Object addToRecentFiles      = Type.Missing;
            Object passwordDocument      = Type.Missing;
            Object passwordTemplate      = Type.Missing;
            Object revert                = Type.Missing;
            Object writePasswordDocument = Type.Missing;
            Object writePasswordTemplate = Type.Missing;
            Object format                = Type.Missing;
            Object encoding              = Type.Missing;
            Object visible               = Type.Missing;
            Object openConflictDocument  = Type.Missing;
            Object openAndRepair         = Type.Missing;
            Object documentDirection     = Type.Missing;
            Object noEncodingDialog      = Type.Missing;

            Microsoft.Office.Interop.Word.Application theAppWord  = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document    theDocument = null;
            MSWord.Document tempDocument = null;
            theDocument = theAppWord.Documents.Open(ref filefullname, ref confirmConversions, ref readOnly, ref addToRecentFiles,
                                                    ref passwordDocument, ref passwordTemplate, ref revert,
                                                    ref writePasswordDocument, ref writePasswordTemplate,
                                                    ref format, ref encoding, ref visible, ref openConflictDocument,
                                                    ref openAndRepair, ref documentDirection, ref noEncodingDialog
                                                    );

            theAppWord.Visible = false;
            //先关闭打开的文档(注意saveChanges选项)
            Object saveChanges    = MSWord.WdSaveOptions.wdSaveChanges;
            Object originalFormat = Type.Missing;
            Object routeDocument  = Type.Missing;

            object docStart = null;
            object docEnd   = null;
            object start    = null;
            object end      = null;

            for (int i = 1; i < theStrPath.Count; i++)
            {
                progressBar1.Value = i * 100 / theStrPath.Count;
                filefullname       = @theStrPath[i];
                readOnly           = true;
                tempDocument       = theAppWord.Documents.Open(ref filefullname, ref confirmConversions, ref readOnly, ref addToRecentFiles,
                                                               ref passwordDocument, ref passwordTemplate, ref revert,
                                                               ref writePasswordDocument, ref writePasswordTemplate,
                                                               ref format, ref encoding, ref visible, ref openConflictDocument,
                                                               ref openAndRepair, ref documentDirection, ref noEncodingDialog
                                                               );


                theDocument.Sections.Add();
                docStart = theDocument.Content.End - 1;
                docEnd   = theDocument.Content.End;

                start = tempDocument.Content.Start;
                end   = tempDocument.Content.End;
                //tempDocument.Range(ref start, ref end).Copy();

                tempDocument.Activate();
                theAppWord.ActiveWindow.View.Type = MSWord.WdViewType.wdNormalView;
                theAppWord.Selection.WholeStory();
                theAppWord.Selection.Copy();

                //计算word文档页数

                MSWord.WdStatistic tempstart = MSWord.WdStatistic.wdStatisticPages;
                int num = tempDocument.ComputeStatistics(tempstart);

                System.Diagnostics.Debug.Print("--------------------" + num);
                theDocument.Activate();
                //theAppWord.Selection.EndKey(MSWord.WdUnits.wdStory);
                if (num > 10)
                {
                    IntPtr p = FindWindowEx(System.IntPtr.Zero, System.IntPtr.Zero, null, theAppWord.Caption);
                    SetFocus(p);
                    keybd_event(Convert.ToByte(System.Windows.Forms.Keys.ControlKey), 0, 0, 0);
                    keybd_event(Convert.ToByte(System.Windows.Forms.Keys.End), 0, 0, 0);
                    keybd_event(Convert.ToByte(System.Windows.Forms.Keys.ControlKey), 0, 0, 0);
                    keybd_event(Convert.ToByte(System.Windows.Forms.Keys.End), 0, 2, 0);

                    keybd_event(Convert.ToByte(System.Windows.Forms.Keys.ControlKey), 0, 0, 0);
                    keybd_event(Convert.ToByte(System.Windows.Forms.Keys.V), 0, 0, 0);
                    keybd_event(Convert.ToByte(System.Windows.Forms.Keys.ControlKey), 0, 2, 0);
                    keybd_event(Convert.ToByte(System.Windows.Forms.Keys.V), 0, 2, 0);
                    System.Threading.Thread.Sleep(500);
                    keybd_event(Convert.ToByte(System.Windows.Forms.Keys.N), 0, 0, 0);
                    keybd_event(Convert.ToByte(System.Windows.Forms.Keys.N), 0, 2, 0);
                    //byte[] ch = (ASCIIEncoding.ASCII.GetBytes());
                    //SendMessage(p, WM_CHAR, Convert.ToByte(System.Windows.Forms.Keys.ControlKey), 0);
                    //SendMessage(p, WM_CHAR, Convert.ToByte(System.Windows.Forms.Keys.V), 0);
                }
                else
                {
                    theAppWord.Selection.PasteAndFormat(MSWord.WdRecoveryType.wdUseDestinationStylesRecovery);
                }


                //theDocument.Range(ref docStart, ref docEnd).PasteAndFormat(MSWord.WdRecoveryType.wdUseDestinationStylesRecovery);

                saveChanges = MSWord.WdSaveOptions.wdDoNotSaveChanges;
                ((MSWord._Document)tempDocument).Close(ref saveChanges, ref originalFormat, ref routeDocument);
            }

            saveChanges = MSWord.WdSaveOptions.wdSaveChanges;
            ((MSWord._Document)theDocument).Close(ref saveChanges, ref originalFormat, ref routeDocument);

            ((MSWord._Application)theAppWord).Quit(Type.Missing, Type.Missing, Type.Missing);

            Kill(theAppWord);
            progressBar1.Value = 100;
            MessageBox.Show("恭喜您,Word文件合标完成!", "合并成功!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        }
Beispiel #16
0
        public static int GetWordPages(string docFile)
        {
            int    pages_t = -1;
            string msg     = "";

            Microsoft.Office.Interop.Word.Document    doc     = null;
            Microsoft.Office.Interop.Word.Application appWord = null;
            try
            {
                if (docFile == null || !(docFile.ToLower().EndsWith("doc") || docFile.ToLower().EndsWith("docx")))
                {
                    msg = "非word文件: " + docFile;
                    return(-999);
                }


                object wordFile = docFile;

                object oMissing = Missing.Value;

                //自定义object类型的布尔值
                object oTrue  = true;
                object oFalse = false;

                object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;

                //定义WORD Application相关
                appWord = new Microsoft.Office.Interop.Word.Application();

                //WORD程序不可见
                appWord.Visible = false;
                //不弹出警告框
                appWord.DisplayAlerts = WdAlertLevel.wdAlertsNone;



                //打开要打印的文件
                doc = appWord.Documents.Open(
                    ref wordFile,
                    ref oMissing,
                    ref oTrue,
                    ref oFalse,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing);


                // 计算Word文档页数 
                WdStatistic stat = WdStatistic.wdStatisticPages;
                pages_t = doc.ComputeStatistics(stat, ref oMissing);//.ComputeStatistics(stat, ref Nothing); 
                //打印完关闭WORD文件
                doc.Close(ref doNotSaveChanges, ref oMissing, ref oMissing);

                //退出WORD程序
                appWord.Quit(ref oMissing, ref oMissing, ref oMissing);

                doc     = null;
                appWord = null;

                return(pages_t);
            }
            catch (System.Exception ex)
            {
                msg = ex.Message;
                LogHelper.WriteLogError(typeof(FilePages), ex.Message);
                pages_t = -997;
            }
            finally {
            }

            //this.textBox1.Text = msg;
            return(pages_t);
        }
Beispiel #17
0
        /// <summary>
        /// Convert a Word file to PDF
        /// </summary>
        /// <param name="inputFile">Full path of the input Word file</param>
        /// <param name="outputFile">Full path of the output PDF</param>
        /// <returns></returns>
        public static new int Convert(String inputFile, String outputFile, Hashtable options)
        {
            Boolean running = (Boolean)options["noquit"];

            Microsoft.Office.Interop.Word.Application word = null;
            object oMissing = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word.Template tmpl;
            String           temporaryStorageDir = null;
            float            wordVersion         = 0;
            List <AppOption> wordOptionList      = new List <AppOption>();

            try
            {
                String  filename           = (String)inputFile;
                Boolean hasSignatures      = WordConverter.hasDigitalSignatures(filename);
                Boolean visible            = !(Boolean)options["hidden"];
                Boolean openAndRepair      = !(Boolean)options["word_no_repair"];
                Boolean nowrite            = (Boolean)options["readonly"];
                Boolean includeProps       = !(Boolean)options["excludeprops"];
                Boolean includeTags        = !(Boolean)options["excludetags"];
                Boolean bitmapMissingFonts = !(Boolean)options["word_ref_fonts"];
                Boolean autosave           = options.ContainsKey("IsTempWord") && (Boolean)options["IsTempWord"];
                bool    pdfa          = (Boolean)options["pdfa"] ? true : false;
                String  writePassword = "";
                String  readPassword  = "";
                int     maxPages      = 0;

                WdExportOptimizeFor     quality    = WdExportOptimizeFor.wdExportOptimizeForPrint;
                WdExportItem            showMarkup = WdExportItem.wdExportDocumentContent;
                WdExportCreateBookmarks bookmarks  = (Boolean)options["bookmarks"] ?
                                                     WdExportCreateBookmarks.wdExportCreateHeadingBookmarks :
                                                     WdExportCreateBookmarks.wdExportCreateNoBookmarks;
                Microsoft.Office.Interop.Word.Options   wdOptions      = null;
                Microsoft.Office.Interop.Word.Documents documents      = null;
                Microsoft.Office.Interop.Word.Template  normalTemplate = null;

                tmpl = null;
                try
                {
                    word = (Microsoft.Office.Interop.Word.Application)Marshal.GetActiveObject("Word.Application");
                }
                catch (System.Exception)
                {
                    int tries = 10;
                    word    = new Microsoft.Office.Interop.Word.Application();
                    running = false;
                    while (tries > 0)
                    {
                        try
                        {
                            // Try to set a property on the object
                            word.ScreenUpdating = false;
                        }
                        catch (COMException)
                        {
                            // Decrement the number of tries and have a bit of a snooze
                            tries--;
                            Thread.Sleep(500);
                            continue;
                        }
                        // Looks ok, so bail out of the loop
                        break;
                    }
                    if (tries == 0)
                    {
                        Converter.releaseCOMObject(word);
                        return((int)ExitCode.ApplicationError);
                    }
                }

                wdOptions          = word.Options;
                word.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                // Issue #48 - we should allow control over whether the history is lost
                if (!(Boolean)options["word_keep_history"])
                {
                    word.DisplayRecentFiles = false;
                }
                word.DisplayDocumentInformationPanel = false;
                word.FeatureInstall = Microsoft.Office.Core.MsoFeatureInstall.msoFeatureInstallNone;
                wordVersion         = (float)System.Convert.ToDecimal(word.Version, new CultureInfo("en-US"));

                // Set the Word options in a way that allows us to reset the options when we finish
                try
                {
                    wordOptionList.Add(new AppOption("AlertIfNotDefault", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("AllowReadingMode", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("PrecisePositioning", true, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateFieldsAtPrint", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateLinksAtPrint", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateLinksAtOpen", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateFieldsWithTrackedChangesAtPrint", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("WarnBeforeSavingPrintingSendingMarkup", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("BackgroundSave", true, ref wdOptions));
                    wordOptionList.Add(new AppOption("SavePropertiesPrompt", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("DoNotPromptForConvert", true, ref wdOptions));
                    wordOptionList.Add(new AppOption("PromptUpdateStyle", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ConfirmConversions", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("CheckGrammarAsYouType", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("CheckGrammarWithSpelling", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("CheckSpellingAsYouType", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("DisplaySmartTagButtons", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("EnableLivePreview", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ShowReadabilityStatistics", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("SuggestSpellingCorrections", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("AllowDragAndDrop", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("EnableMisusedWordsDictionary", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ShowFormatError", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("StoreRSIDOnSave", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("SaveNormalPrompt", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("AllowFastSave", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("BackgroundOpen", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ShowMarkupOpenSave", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("SaveInterval", 0, ref wdOptions));
                }
                catch (SystemException)
                {
                }

                // Set up the PDF output quality
                if ((Boolean)options["print"])
                {
                    quality = WdExportOptimizeFor.wdExportOptimizeForPrint;
                }
                if ((Boolean)options["screen"])
                {
                    quality = WdExportOptimizeFor.wdExportOptimizeForOnScreen;
                }

                if ((Boolean)options["markup"])
                {
                    showMarkup = WdExportItem.wdExportDocumentWithMarkup;
                }

                if (!String.IsNullOrEmpty((String)options["password"]))
                {
                    readPassword = (String)options["password"];
                }

                if (!String.IsNullOrEmpty((String)options["writepassword"]))
                {
                    writePassword = (String)options["writepassword"];
                }

                // Large Word files may simply not print reliably - if the word_max_pages
                // configuration option is set, then we must close up and forget about
                // converting the file.
                maxPages = (int)options[@"word_max_pages"];

                documents      = word.Documents;
                normalTemplate = word.NormalTemplate;

                // Check for password protection and no password
                if (Converter.IsPasswordProtected(inputFile) && String.IsNullOrEmpty(readPassword))
                {
                    normalTemplate.Saved = true;
                    Console.WriteLine("Unable to open password protected file");
                    return((int)ExitCode.PasswordFailure);
                }

                // Having signatures means we should open the document very carefully
                if (hasSignatures)
                {
                    nowrite       = true;
                    autosave      = false;
                    openAndRepair = false;
                }

                Microsoft.Office.Interop.Word.Document doc = null;
                try
                {
                    if ((bool)options["merge"] && !String.IsNullOrEmpty((string)options["template"]) &&
                        File.Exists((string)options["template"]) &&
                        System.Text.RegularExpressions.Regex.IsMatch((string)options["template"], @"^.*\.dot[mx]?$", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                    {
                        // Create a new document based on a template
                        doc = documents.Add((string)options["template"]);
                        Object rStart = 0;
                        Object rEnd   = 0;
                        Range  range  = doc.Range(rStart, rEnd);
                        range.InsertFile(inputFile);
                        Converter.releaseCOMObject(range);
                        // Make sure we save the file with the original filename so
                        // filename fields update correctly
                        temporaryStorageDir = Path.GetTempFileName();
                        File.Delete(temporaryStorageDir);
                        Directory.CreateDirectory(temporaryStorageDir);
                        doc.SaveAs(Path.Combine(temporaryStorageDir, Path.GetFileName(inputFile)));
                    }
                    else
                    {
                        // Open the source document
                        doc = documents.OpenNoRepairDialog(FileName: filename, ReadOnly: nowrite, PasswordDocument: readPassword, WritePasswordDocument: writePassword, Visible: visible, OpenAndRepair: openAndRepair);
                    }
                }
                catch (System.Runtime.InteropServices.COMException)
                {
                    Console.WriteLine("Unable to open file");
                    return((int)ExitCode.FileOpenFailure);
                }

                // Check if there are signatures in the document which changes how we do things
                if (hasSignatures)
                {
                    // Add in a delay to allow signatures to load
                    Thread.Sleep(500);
                }
                else
                {
                    Microsoft.Office.Interop.Word.Window docWin     = null;
                    Microsoft.Office.Interop.Word.View   docWinView = null;

                    doc.Activate();
                    // Check if there are too many pages
                    if (maxPages > 0)
                    {
                        var pageCount = doc.ComputeStatistics(WdStatistic.wdStatisticPages, false);
                        doc.Saved = true;
                        if (pageCount > maxPages)
                        {
                            throw new Exception(String.Format("Too many pages to process ({0}). More than {1}", pageCount, maxPages));
                        }
                    }

                    // Prevent "property not available" errors, see http://blogs.msmvps.com/wordmeister/2013/02/22/word2013bug-not-available-for-reading/
                    docWin     = doc.ActiveWindow;
                    docWinView = docWin.View;
                    if (wordVersion >= 15)
                    {
                        docWinView.ReadingLayout = false;
                    }

                    // Sometimes the print view will not be available (e.g. for a blog post)
                    // Try and switch view
                    try
                    {
                        docWinView.Type = WdViewType.wdPrintPreview;
                    }
                    catch (Exception) { }

                    // Hide comments
                    try
                    {
                        docWinView.RevisionsView            = WdRevisionsView.wdRevisionsViewFinal;
                        docWinView.ShowRevisionsAndComments = false;
                    }
                    catch (SystemException) { }

                    // Try to avoid Word thinking any changes are happening to the document
                    doc.SpellingChecked = true;
                    doc.GrammarChecked  = true;

                    // Changing these properties may be disallowed if the document is protected
                    // and is not signed
                    if (doc.ProtectionType == WdProtectionType.wdNoProtection && !hasSignatures)
                    {
                        if (autosave)
                        {
                            doc.Save(); doc.Saved = true;
                        }
                        doc.TrackMoves      = false;
                        doc.TrackRevisions  = false;
                        doc.TrackFormatting = false;
                    }

                    normalTemplate.Saved = true;

                    // Hide the document window if need be
                    if ((Boolean)options["hidden"])
                    {
                        var activeWin = word.ActiveWindow;
                        activeWin.Visible     = false;
                        activeWin.WindowState = WdWindowState.wdWindowStateMinimize;
                        Converter.releaseCOMObject(activeWin);
                    }

                    // Check if we have a template file to apply to this document
                    // The template must be a file and must end in .dot, .dotx or .dotm
                    if (!String.IsNullOrEmpty((String)options["template"]) && !(bool)options["merge"])
                    {
                        string template = (string)options["template"];
                        if (File.Exists(template) && System.Text.RegularExpressions.Regex.IsMatch(template, @"^.*\.dot[mx]?$"))
                        {
                            doc.set_AttachedTemplate(template);
                            doc.UpdateStyles();
                            tmpl = doc.get_AttachedTemplate();
                        }
                        else
                        {
                            Console.WriteLine("Invalid template '{0}'", template);
                        }
                    }

                    // See if we have to update fields
                    if (!(Boolean)options["word_no_field_update"])
                    {
                        updateDocumentFields(doc, word, inputFile, options);
                    }

                    var pageSetup = doc.PageSetup;
                    if ((float)options["word_header_dist"] >= 0)
                    {
                        pageSetup.HeaderDistance = (float)options["word_header_dist"];
                    }
                    if ((float)options["word_footer_dist"] >= 0)
                    {
                        pageSetup.FooterDistance = (float)options["word_footer_dist"];
                    }
                    Converter.releaseCOMObject(pageSetup);
                    try
                    {
                        // Make sure we are not in a header footer view
                        docWinView.SeekView = WdSeekView.wdSeekPrimaryHeader;
                        docWinView.SeekView = WdSeekView.wdSeekPrimaryFooter;
                        docWinView.SeekView = WdSeekView.wdSeekMainDocument;
                    }
                    catch (Exception)
                    {
                        // We might fail when switching views
                    }

                    normalTemplate.Saved = true;
                    if (autosave)
                    {
                        doc.Save();
                    }
                    doc.Saved = true;
                    Converter.releaseCOMObject(docWinView);
                    Converter.releaseCOMObject(docWin);
                }

                doc.ExportAsFixedFormat(outputFile, WdExportFormat.wdExportFormatPDF, false,
                                        quality, WdExportRange.wdExportAllDocument,
                                        1, 1, showMarkup, includeProps, true, bookmarks, includeTags, bitmapMissingFonts, pdfa);

                if (tmpl != null)
                {
                    tmpl.Saved = true;
                }

                object saveChanges = autosave? WdSaveOptions.wdSaveChanges : WdSaveOptions.wdDoNotSaveChanges;
                if (nowrite)
                {
                    doc.Saved = true;
                }
                normalTemplate.Saved = true;
                ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);

                // Reset options
                foreach (AppOption opt in wordOptionList)
                {
                    opt.resetValue(ref wdOptions);
                }

                Converter.releaseCOMObject(wdOptions);
                Converter.releaseCOMObject(documents);
                Converter.releaseCOMObject(doc);
                Converter.releaseCOMObject(tmpl);
                Converter.releaseCOMObject(normalTemplate);

                return((int)ExitCode.Success);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return((int)ExitCode.UnknownError);
            }
            finally
            {
                if (temporaryStorageDir != null && Directory.Exists(temporaryStorageDir))
                {
                    try
                    {
                        if (File.Exists(Path.Combine(temporaryStorageDir, Path.GetFileName(inputFile))))
                        {
                            File.Delete(Path.Combine(temporaryStorageDir, Path.GetFileName(inputFile)));
                        }
                        Directory.Delete(temporaryStorageDir);
                    }
                    catch (Exception) { }
                }
                if (word != null && !running)
                {
                    closeWordApplication(word);
                }
                Converter.releaseCOMObject(word);
            }
        }
Beispiel #18
0
        public bool Convert(string sourcePath, string targetPath, Word.WdExportFormat exportFormat)
        {
            object _nullobj     = System.Reflection.Missing.Value;
            bool   result       = false;
            int    page         = 0;
            object paramMissing = Type.Missing;
            object Nothing      = System.Reflection.Missing.Value;

            Word.ApplicationClass wordApplication = new Word.ApplicationClass();
            Word.Document         wordDocument    = null;

            try
            {
                //DrawItems.WriteLog("Convert");
                object paramSourceDocPath  = sourcePath;
                string paramExportFilePath = targetPath;

                Word.WdExportFormat paramExportFormat           = exportFormat;
                bool paramOpenAfterExport                       = false;
                Word.WdExportOptimizeFor paramExportOptimizeFor =
                    Word.WdExportOptimizeFor.wdExportOptimizeForPrint;
                Word.WdExportRange paramExportRange = Word.WdExportRange.wdExportFromTo;
                int paramStartPage = 1;
                int paramEndPage   = 0;
                Word.WdExportItem paramExportItem = Word.WdExportItem.wdExportDocumentContent;
                bool paramIncludeDocProps         = true;
                bool paramKeepIRM = true;
                Word.WdExportCreateBookmarks paramCreateBookmarks =
                    Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks;
                bool paramDocStructureTags   = true;
                bool paramBitmapMissingFonts = true;
                bool paramUseISO19005_1      = false;
                wordDocument = wordApplication.Documents.Open(
                    ref paramSourceDocPath, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing);

                if (wordDocument != null)
                {
                    page = wordDocument.ComputeStatistics(Word.WdStatistic.wdStatisticPages, ref _nullobj);
                }

                if (page % 2 != 0)//删除最后一页空白页
                {
                    paramEndPage = page - 1;
                }
                else
                {
                    paramEndPage = page;
                }

                wordDocument.ExportAsFixedFormat(paramExportFilePath,
                                                 paramExportFormat, paramOpenAfterExport,
                                                 paramExportOptimizeFor, paramExportRange, paramStartPage,
                                                 paramEndPage, paramExportItem, paramIncludeDocProps,
                                                 paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                                                 paramBitmapMissingFonts, paramUseISO19005_1,
                                                 ref paramMissing);
                result = true;
            }
            catch (Exception ex)
            {
                DrawItems.WriteLog(ex.ToString());

                if (wordDocument != null)
                {
                    wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordDocument = null;
                }
                if (wordApplication != null)
                {
                    wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordApplication = null;
                }
                throw ex;
            }
            finally
            {
                if (wordDocument != null)
                {
                    wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordDocument = null;
                }
                if (wordApplication != null)
                {
                    wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordApplication = null;
                }

                GC.Collect();
                //GC.WaitForPendingFinalizers();
            }

            return(result);
        }
Beispiel #19
0
        static void Main(string[] args)
        {
            var docx = @"{HOME_SOURCE}\source\repos\ReportParser\ReportParser\bin\Debug\A.docx";

            try
            {
                //建立開啟Word工具
                Word.Application app = new Word.Application();
                //取得文件
                Word.Document dx = app.Documents.Open(docx);

                //Word.WdStatistic是一群列舉常數

                /*
                 * 包含:
                 *  wdStatisticCharacters	3	字元數。
                 *  wdStatisticCharactersWithSpaces	5	含空格的字元數。
                 *  wdStatisticFarEastCharacters	6	亞洲語言的字元數。
                 *  wdStatisticLines	1	行數。
                 *  wdStatisticPages	2	頁數。
                 *  wdStatisticParagraphs	4	段落數。
                 *  wdStatisticWords	0	字數。
                 */
                //取得本文件總頁數
                object           Miss           = System.Reflection.Missing.Value;
                Word.WdStatistic PagesCountStat = Word.WdStatistic.wdStatisticPages;
                int PageCount = dx.ComputeStatistics(PagesCountStat, Miss);
                Console.Out.WriteLine("Word page count : " + PageCount);

                //取得段落總數
                Word.WdStatistic PagesParagraphsStat = Word.WdStatistic.wdStatisticParagraphs;
                int PageParagraphsCount = dx.ComputeStatistics(PagesParagraphsStat, Miss);
                Console.Out.WriteLine("Paragraphs count : " + PageParagraphsCount);

                //取得Table,並檢查Table結束於哪個頁面,以及Row位於哪個頁面
                Console.Out.WriteLine("Tables count : " + dx.Tables.Count);

                foreach (Word.Table tb in dx.Tables)
                {
                    //檢查Table第3個欄位數的Cell總數,如果有合併將顯示合併後數量
                    Console.Out.WriteLine("Column 3 Cells : " + tb.Columns[3].Cells.Count);

                    Console.Out.WriteLine(" OK! ");

                    //Tabel.Uniform 屬性用來判斷是否有合併儲存格,如果有就False否則True
                    if (tb.Uniform)
                    {
                        Console.Out.WriteLine("###該表格沒有合併儲存格,所以尋列讀取!###");
                        int start = tb.Rows[1].Range.Information[Word.WdInformation.wdActiveEndAdjustedPageNumber];
                        int end   = tb.Range.Information[Word.WdInformation.wdActiveEndAdjustedPageNumber];
                        Console.Out.WriteLine("Table Start Page : " + start.ToString() + " - End Page : " + end.ToString());
                        foreach (Word.Row row in tb.Rows)
                        {
                            int endpage = row.Range.Information[Word.WdInformation.wdActiveEndAdjustedPageNumber];
                            Console.Out.WriteLine("Row index : " + row.Index + " At Page : " + endpage.ToString());
                        }
                    }
                    else
                    {
                        Console.Out.WriteLine("###該表格有合併儲存格,所以將Table轉Cell依序讀取!###");
                        //完整頁數
                        int[] fullPages = new int[] { };
                        //計算時暫存用頁數
                        int[] tmPage = new int[] { };
                        //如果Table有合併儲存格讀取方式要將Table轉Cell依序讀取
                        Word.Range ra = tb.Range;
                        for (int i = 1; i <= ra.Cells.Count; i++)
                        {
                            try
                            {
                                Word.Cell cell    = ra.Cells[i];                                                              //取得Cell
                                int       numPage = cell.Range.Information[Word.WdInformation.wdActiveEndAdjustedPageNumber]; //取得頁數
                                int[]     st      = new int[] { numPage };                                                    //頁數準備合併前的暫存陣列物件
                                Console.Out.WriteLine("[ " + cell.RowIndex.ToString() + " - " + cell.ColumnIndex.ToString() + " ] - [ " + numPage + " ]");
                                fullPages = tmPage.Union(st).ToArray <int>();                                                 //合併
                            }
                            catch (Exception inex)
                            {
                                Console.Out.WriteLine(inex.Message);
                            }
                        }
                        Console.Out.WriteLine("Page Num : " + fullPages.Count().ToString());
                    }
                }

                //依序移動頁面,並取得頁面文字陣列
                List <string> Pages = new List <string>();
                object        What  = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToPage;
                object        Which = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToAbsolute;
                object        Start;
                object        End;
                object        CurrentPageNumber;
                object        NextPageNumber;

                for (int Index = 1; Index < PageCount + 1; Index++)
                {
                    CurrentPageNumber = (Convert.ToInt32(Index.ToString()));
                    NextPageNumber    = (Convert.ToInt32((Index + 1).ToString()));

                    // Get start position of current page
                    Start = app.Selection.GoTo(ref What, ref Which, ref CurrentPageNumber, ref Miss).Start;

                    // Get end position of current page
                    End = app.Selection.GoTo(ref What, ref Which, ref NextPageNumber, ref Miss).End;

                    // Get text
                    if (Convert.ToInt32(Start.ToString()) != Convert.ToInt32(End.ToString()))
                    {
                        Pages.Add(dx.Range(ref Start, ref End).Text);
                    }
                    else
                    {
                        Pages.Add(dx.Range(ref Start).Text);
                    }
                }

                //結束關閉檔案
                dx.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
                Console.Out.WriteLine(" OK! ");
            }
            catch (Exception e)
            {
                Console.Out.WriteLine(e.Message);
            }
            finally
            {
                //釋放執行緒
                Process   myProcess   = new Process();
                Process[] wordProcess = Process.GetProcessesByName("winword");
                Console.Out.WriteLine("Word process count : " + wordProcess.Count());
                foreach (Process pro in wordProcess)
                {
                    pro.Kill();
                }
            }

            string x = Console.ReadLine();
        }
Beispiel #20
0
 public int GetPageNumber()
 {
     return(Doc.ComputeStatistics(Word.WdStatistic.wdStatisticPages, System.Reflection.Missing.Value));
 }
        /// <summary>
        /// 模板生成word
        /// </summary>
        /// <param name="templateFile">模板文件</param>
        /// <param name="fileName">新文件</param>
        /// <param name="myDictionary">参数数组</param>
        /// <param name="startPageIndex">word页数</param>
        public static bool ExportWord(string templateFile, string fileName, Dictionary <string, string> myDictionary, int startPageIndex)
        {
            //生成documnet对象
            Word._Document doc = new Word.Document();
            //生成word程序对象
            Word.Application app = new Word.Application();
            //模板文件
            string TemplateFile = templateFile;

            //模板文件拷贝到新文件
            File.Copy(TemplateFile, fileName);

            object Obj_FileName = fileName;
            object Visible      = false;
            object ReadOnly     = false;
            object missing      = System.Reflection.Missing.Value;

            try
            {
                //打开文件
                doc = app.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
                                         ref missing, ref missing, ref missing, ref missing,
                                         ref missing, ref missing, ref missing, ref Visible,
                                         ref missing, ref missing, ref missing,
                                         ref missing);
                doc.Activate();

                #region 声明参数
                if (myDictionary.Count > 0)
                {
                    object what = Word.WdGoToItem.wdGoToBookmark;
                    object WordMarkName;
                    foreach (var item in myDictionary)
                    {
                        WordMarkName = item.Key;
                        //光标转到书签的位置
                        doc.ActiveWindow.Selection.GoTo(ref what, ref missing, ref missing, ref WordMarkName);
                        //插入的内容,插入位置是word模板中书签定位的位置
                        doc.ActiveWindow.Selection.TypeText(item.Value);
                        //设置当前定位书签位置插入内容的格式
                        //doc.ActiveWindow.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    }
                }
                #endregion

                #region  除指定页面
                //获取页数
                int pages = doc.ComputeStatistics(Word.WdStatistic.wdStatisticPages, ref missing);
                //超出3页的部分
                startPageIndex += pages - 3;
                //共3页,少于3页时删除多余页
                if (startPageIndex < pages)
                {
                    object objWhat = Word.WdGoToItem.wdGoToPage;

                    object objWhich = Word.WdGoToDirection.wdGoToAbsolute;
                    //删除startPageIndex页及之后的文档
                    object objPage = startPageIndex + 1;

                    Word.Range rangeStart = doc.GoTo(ref objWhat, ref objWhich, ref objPage, ref missing);

                    object objStart = rangeStart.Start - 1;
                    object objEnd   = doc.Characters.Count;

                    object Unit  = (int)Word.WdUnits.wdCharacter;
                    object Count = 1;
                    doc.Range(ref objStart, ref objEnd).Delete(ref Unit, ref Count);
                }
                #endregion
                return(true);
            }
            catch (Exception ex)
            {
                logger.Error("WordHelper中发生异常:", ex);
                return(false);
            }
            finally
            {
                //输出完毕后关闭doc对象
                object IsSave = true;
                doc.Close(ref IsSave, ref missing, ref missing);
            }
        }
Beispiel #22
0
        private void buttonShowPages_Click(object sender, EventArgs e)
        {
            string msg = "";

            try
            {
                DialogResult ret = this.openFileDialogWord.ShowDialog(this);

                if (ret != DialogResult.OK)
                {
                    return;
                }

                string docFile = this.openFileDialogWord.FileName;

                if (docFile == null || !(docFile.ToLower().EndsWith("doc") || docFile.ToLower().EndsWith("docx")))
                {
                    msg = "非word文件: " + docFile;
                    throw new Exception(msg);
                }

                this.textBox1.Text = msg;

                object wordFile = docFile;

                object oMissing = Missing.Value;

                //自定义object类型的布尔值
                object oTrue  = true;
                object oFalse = false;

                object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;

                //定义WORD Application相关
                Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();

                //WORD程序不可见
                appWord.Visible = false;
                //不弹出警告框
                appWord.DisplayAlerts = WdAlertLevel.wdAlertsNone;

                //打开要打印的文件
                Microsoft.Office.Interop.Word.Document doc = appWord.Documents.Open(
                    ref wordFile,
                    ref oMissing,
                    ref oTrue,
                    ref oFalse,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing,
                    ref oMissing);


                // 计算Word文档页数 
                WdStatistic stat = WdStatistic.wdStatisticPages;
                int         num  = doc.ComputeStatistics(stat, ref oMissing);//.ComputeStatistics(stat, ref Nothing); 
                //打印完关闭WORD文件
                doc.Close(ref doNotSaveChanges, ref oMissing, ref oMissing);

                //退出WORD程序
                appWord.Quit(ref oMissing, ref oMissing, ref oMissing);

                doc     = null;
                appWord = null;

                msg = docFile + " : All Pages:" + num;
            }
            catch (System.Exception ex)
            {
                msg = ex.Message;
            }

            this.textBox1.Text = msg;
        }
        public static bool MergeDataWithWordTemplate(string sourceTemplatePath, string outputDocPath, DataSet sourceData, bool isDoubleSidedPrinting, string[] extraPages, out string errorString)
        {
            #region Declares
            errorString = string.Empty;
            Object oMissing        = System.Reflection.Missing.Value; //null value
            Object oTrue           = true;
            Object oFalse          = false;
            Object oPageBreak      = Word.WdBreakType.wdPageBreak;
            Object oTemplatePath   = sourceTemplatePath;
            Object oOutputPath     = outputDocPath;
            Object oOutputPathTemp = outputDocPath.Substring(0, outputDocPath.IndexOf(".doc")) + "_temp.doc";
            Object sectionStart    = (Object)Microsoft.Office.Interop.Word.WdSectionStart.wdSectionNewPage;

            Word.Application oWord         = null;
            Word.Document    oWordDoc      = null; //the document to load into word application
            Word.Document    oFinalWordDoc = null; //the document to load into word application
            #endregion

            try
            {
                Logger.LogMailMerge(false, "");
                Logger.LogMailMerge(false, "MailMergeWebApp:MailMerge() merging document: " + sourceTemplatePath);

                oWord         = new Word.Application(); //starts an instance of word
                oWord.Visible = false;                  //don't show the UI

                //create an empty document that we will insert all the merge docs into
                oFinalWordDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                //for each record in the dataset
                int count = 1;
                foreach (DataRow dr in sourceData.Tables[0].Rows)
                {
                    Logger.LogMailMerge(false, "MailMergeWebApp:MailMerge() adding a document for this record");

                    //insert a document for each record
                    oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
                    if (oWordDoc.Fields.Count == 0)
                    {
                        Logger.LogMailMerge(false, "MailMergeWebApp:MailMerge() No template fields found in document:" + sourceTemplatePath);
                        return(false);
                    }

                    foreach (Word.Field myMergeField in oWordDoc.Fields)
                    {
                        Word.Range rngFieldCode = myMergeField.Code;
                        String     fieldText    = rngFieldCode.Text;
                    }

                    oWordDoc.Activate(); //make current

                    // Perform mail merge field
                    foreach (Word.Field myMergeField in oWordDoc.Fields)
                    {
                        Word.Range rngFieldCode = myMergeField.Code;
                        String     fieldText    = rngFieldCode.Text;

                        // ONLY GET THE MAILMERGE FIELDS
                        if (fieldText.StartsWith(" MERGEFIELD") && fieldText.IndexOf("\\") != -1)
                        {
                            // THE TEXT COMES IN THE FORMAT OF
                            // MERGEFIELD MyFieldName \\* MERGEFORMAT
                            // THIS HAS TO BE EDITED TO GET ONLY THE FIELDNAME "MyFieldName"
                            Int32  endMerge        = fieldText.IndexOf("\\");
                            Int32  fieldNameLength = fieldText.Length - endMerge;
                            String fieldName       = fieldText.Substring(11, endMerge - 11);
                            //Logger.LogMailMerge("fieldName:" + fieldName);

                            // GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dot FILE
                            // field names with spaces in them have quotes on either end, so strip those
                            fieldName = fieldName.Trim().Replace("\"", "");
                            Logger.LogMailMerge(false, "MailMergeWebApp:MailMerge() found word template field: " + fieldName);

                            //find a matching dataset column
                            foreach (DataColumn col in sourceData.Tables[0].Columns)
                            {
                                // google:   c# word document merge table

                                if (col.ColumnName.StartsWith("tbl_"))
                                {
                                    // Fill the table with data.
                                    Word.Table    tbl = oWordDoc.Tables[1];
                                    DirectoryInfo di  = new DirectoryInfo("C:\\");

                                    // Start with row 2.
                                    int i = 2;

                                    Object beforeRow = Type.Missing;
                                    foreach (FileInfo fi in di.GetFiles())
                                    {
                                        tbl.Rows.Add(ref beforeRow);
                                        tbl.Cell(i, 1).Range.Text = fi.Name;
                                        tbl.Cell(i, 2).Range.Text =
                                            string.Format("{0:N0}", fi.Length);
                                        tbl.Cell(i, 3).Range.Text =
                                            string.Format("{0:g}", fi.LastWriteTime);
                                        i++;
                                    }

                                    continue;
                                }


                                string key   = col.ColumnName;
                                string value = dr[key].ToString();

                                // **** FIELD REPLACEMENT IMPLEMENTATION GOES HERE ****//
                                // THE PROGRAMMER CAN HAVE HIS OWN IMPLEMENTATIONS HERE
                                if (fieldName == key)
                                {
                                    Logger.LogMailMerge(false, "MailMergeWebApp:MailMerge() setting value: " + value);

                                    myMergeField.Select();
                                    oWord.Selection.TypeText(value);
                                }
                            }
                        }
                    }


                    if (isDoubleSidedPrinting) // make sure so far, even nbr of pages
                    {
                        int nPages = oWordDoc.ComputeStatistics(Word.WdStatistic.wdStatisticPages, ref oMissing);
                        if (nPages % 2 == 1)
                        {
                            Word.Paragraph paragraph = oWordDoc.Content.Paragraphs.Add(ref oMissing);
                            paragraph.Range.InsertParagraphBefore();
                            paragraph.Range.Text = string.Empty;
                            paragraph.Range.InsertBreak(ref oPageBreak);
                            paragraph.Range.InsertParagraphAfter();
                        }
                    }



                    Logger.LogMailMerge(false, "MailMergeWebApp:MailMerge() adding pages");

                    if (extraPages != null)
                    {
                        foreach (string text in extraPages)
                        {
                            Word.Paragraph paragraph;

                            paragraph = oWordDoc.Content.Paragraphs.Add(ref oMissing);
                            paragraph.Range.InsertParagraphBefore();
                            paragraph.Range.Text = string.Empty;
                            paragraph.Range.InsertBreak(ref oPageBreak);
                            paragraph.Range.InsertParagraphAfter();

                            paragraph = oWordDoc.Content.Paragraphs.Add(ref oMissing);
                            paragraph.Range.InsertParagraphBefore();
                            paragraph.Range.Text = text;
                            paragraph.Range.InsertParagraphAfter();


                            if (isDoubleSidedPrinting) // make sure so far, even nbr of pages
                            {
                                int nPages = oWordDoc.ComputeStatistics(Word.WdStatistic.wdStatisticPages, ref oMissing);
                                if (nPages % 2 == 1)
                                {
                                    paragraph = oWordDoc.Content.Paragraphs.Add(ref oMissing);
                                    paragraph.Range.InsertParagraphBefore();
                                    paragraph.Range.Text = string.Empty;
                                    paragraph.Range.InsertBreak(ref oPageBreak);
                                    paragraph.Range.InsertParagraphAfter();
                                }
                            }
                        }
                    }


                    Logger.LogMailMerge(false, "MailMergeWebApp:MailMerge() saving the doc");

                    //SAVE THE DOCUMENT as temp
                    oWordDoc.SaveAs(ref oOutputPathTemp, ref oMissing, ref oMissing, ref oMissing
                                    , ref oMissing, ref oMissing, ref oMissing, ref oMissing
                                    , ref oMissing, ref oMissing, ref oMissing, ref oMissing
                                    , ref oMissing, ref oMissing, ref oMissing, ref oMissing);



                    Logger.LogMailMerge(false, "MailMergeWebApp:MailMerge() closing the doc");

                    //CLOSE THE DOCUMENT
                    oWordDoc.Close(ref oFalse, ref oMissing, ref oMissing);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oWordDoc);
                    oWordDoc = null;

                    //NOW ADD THE NEW DOC TO THE MAIN DOC
                    oFinalWordDoc.Activate(); //make current
                    oWord.Selection.InsertFile(oOutputPathTemp.ToString(), ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                    if (count < sourceData.Tables[0].Rows.Count)
                    {
                        oWord.Selection.InsertBreak(ref sectionStart);
                    }

                    count++;
                }

                //SAVE THE FINAL DOC
                oFinalWordDoc.SaveAs(ref oOutputPath, ref oMissing, ref oMissing, ref oMissing
                                     , ref oMissing, ref oMissing, ref oMissing, ref oMissing
                                     , ref oMissing, ref oMissing, ref oMissing, ref oMissing
                                     , ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                //CLOSE THE FINAL DOC
                oFinalWordDoc.Close(ref oFalse, ref oMissing, ref oMissing);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oFinalWordDoc);
                oFinalWordDoc = null;

                //now delete the temp file
                File.Delete(oOutputPathTemp.ToString());

                Logger.LogMailMerge(false, "MailMergeWebApp:MailMerge() Merge complete, printing document");

                return(true);
            }
            catch (System.Exception ex)
            {
                errorString = ex.Message;
                Logger.LogMailMerge(false, "MailMergeWebApp:MailMerge() Error: " + Environment.NewLine + Environment.NewLine + ex.Message);
            }
            finally
            {
                //RELEASE WORD ITSELF
                oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord);
                oWord = null;

                GC.Collect();
            }

            return(false);
        }
        public void countpage(string printPCLFile)
        {
            string docFile = printPCLFile;
            string msg     = "";

            try
            {
                if (docFile.ToLower().EndsWith("pdf"))
                {
                    iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(docFile);
                    int num = reader.NumberOfPages;

                    msg  = num + "页";
                    mnum = num;
                }
                if (docFile.ToLower().EndsWith("jpg"))
                {
                    mnum = 1;
                }
                if (docFile.ToLower().EndsWith("xlsx") || docFile.ToLower().EndsWith("xlsm"))
                {
                    string path  = System.IO.Directory.GetCurrentDirectory();
                    string sPath = path + "\\temp\\xlsx";

                    // MessageBox.Show(docFile+"\n"+ sPath, "sPath");
                    if (XLSConvertToPDF(docFile, sPath))
                    {
                        string pdffile = sPath + ".pdf";
                        // MessageBox.Show(pdffile,"pdffile");
                        iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(pdffile);
                        int num = reader.NumberOfPages;
                        msg  = num + "页";
                        mnum = num;
                    }
                }
                if (docFile.ToLower().EndsWith("doc") || docFile.ToLower().EndsWith("docx"))
                {
                    //this.textFilename.Text = msg;
                    object wordFile = docFile;
                    object oMissing = Missing.Value;
                    //自定义object类型的布尔值
                    object oTrue  = true;
                    object oFalse = false;

                    object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
                    //定义WORD Application相关
                    Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
                    //WORD程序不可见
                    appWord.Visible = false;
                    //不弹出警告框
                    appWord.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                    //打开要打印的文件
                    Microsoft.Office.Interop.Word.Document doc = appWord.Documents.Open(
                        ref wordFile,
                        ref oMissing,
                        ref oTrue,
                        ref oFalse,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing,
                        ref oMissing);
                    // 计算Word文档页数 
                    WdStatistic stat = WdStatistic.wdStatisticPages;
                    num = doc.ComputeStatistics(stat, ref oMissing);//.ComputeStatistics(stat, ref Nothing); 
                    //打印完关闭WORD文件
                    doc.Close(ref doNotSaveChanges, ref oMissing, ref oMissing);
                    //退出WORD程序
                    appWord.Quit(ref oMissing, ref oMissing, ref oMissing);
                    doc     = null;
                    appWord = null;
                    msg     = num + "页";
                    mnum    = num;
                }
            }
            catch (System.Exception ex)
            {
                msg = ex.Message;
            }
        }