コード例 #1
0
        private void readInfo()
        {
            wordDoc = wordApp.Documents.Open((object)docName, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS);
            wordApp.ActiveWindow.View.ShowFieldCodes = false;
            //wordApp.Visible = true;
            MSWord.Paragraphs pgs = wordDoc.TablesOfContents[1].Range.Paragraphs;

            int start = wordDoc.GoTo(MSWord.WdGoToItem.wdGoToPage, MSWord.WdGoToDirection.wdGoToAbsolute, QS, 1).Start;
            int end   = wordDoc.GoTo(MSWord.WdGoToItem.wdGoToPage, MSWord.WdGoToDirection.wdGoToAbsolute, QS, 2).Start;
            //richTextBoxEx1.Text = wordDoc.Range(start, end).Text;
            //richTextBoxEx1.AppendText("\n"+pgs[1].Next().Range.Hyperlinks[1]);
        }
コード例 #2
0
ファイル: WordDocument.cs プロジェクト: schifflee/Rubin
		/// <summary>
		/// Вставляет содержимое файла *.doc/*.docx в текущий документ с новой страницы 
		/// </summary>
		/// <param name="fileName">Полное имя вставляемого файла</param>
		public void InsertFromFile(string fileName)
		{
			if (_document == null || _application == null)
			{
				return;
			}

			object missingObj = Missing.Value;
			object whatObj = Word.WdGoToItem.wdGoToLine;
			object whichObj = Word.WdGoToDirection.wdGoToLast;	 
			
			var range = _document.GoTo(ref whatObj, ref whichObj, ref missingObj, ref missingObj);	
			range.InsertFile(fileName);
		}
コード例 #3
0
ファイル: DocSettings.cs プロジェクト: goffer14/WordAddin
 public Word.Range GetPageRange(int PageNubmer)
 {
     CurrentPageNumber = (Convert.ToInt32(PageNubmer.ToString()));
     NextPageNumber    = (Convert.ToInt32((PageNubmer + 1).ToString()));
     // Get start position of current page
     Start = Doc.GoTo(ref What, ref Which, ref CurrentPageNumber, ref Miss).Start;
     End   = Doc.GoTo(ref What, ref Which, ref NextPageNumber, ref Miss).End;
     // Get text
     if (Convert.ToInt32(Start.ToString()) != Convert.ToInt32(End.ToString()))
     {
         return(Doc.Range(ref Start, ref End));
     }
     else
     {
         return(Doc.Range(ref Start));
     }
 }
コード例 #4
0
 private void createList()
 {
     MSWord.Range range = wordDoc.GoTo(MSWord.WdGoToItem.wdGoToPage, MSWord.WdGoToDirection.wdGoToAbsolute, QS, 1);
     range.InsertAfter("\r\n");
     range = wordDoc.GoTo(MSWord.WdGoToItem.wdGoToPage, MSWord.WdGoToDirection.wdGoToAbsolute, QS, 1);
     wordDoc.TablesOfContents.Add(range, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, true, ref QS, ref QS);
     wordDoc.TablesOfContents[1].Range.Font.Name = list_font_style;
     wordDoc.TablesOfContents[1].Range.Font.Size = list_font_size;
     wordDoc.TablesOfContents[1].Range.ParagraphFormat.LineSpacingRule = MSWord.WdLineSpacing.wdLineSpaceExactly;
     wordDoc.TablesOfContents[1].Range.ParagraphFormat.LineSpacing     = 22F;
     range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
     range.Text      = "\n目  录\n\n";
     range.Font.Name = mulu_font_style;
     range.Font.Size = mulu_font_size;
     range.ParagraphFormat.LineSpacingRule = MSWord.WdLineSpacing.wdLineSpaceExactly;
     range.ParagraphFormat.LineSpacing     = 22F;
 }
コード例 #5
0
        private static Range getRangeByPageID(Word.Document myDoc, int iPage)
        {
            object missing  = System.Reflection.Missing.Value;
            object objWhat  = Word.WdGoToItem.wdGoToPage;
            object objWhich = Word.WdGoToDirection.wdGoToAbsolute;
            object objPage  = iPage;

            Word.Range rangePage = myDoc.GoTo(ref objWhat, ref objWhich, ref objPage, ref missing);
            return(rangePage);
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: cc29sf3/FileMatch
        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();
        }
コード例 #7
0
        private void hideText(Word.Document myDoc, object iPage, object iEnd)
        {
            object missing  = System.Reflection.Missing.Value;
            object objWhat  = Word.WdGoToItem.wdGoToPage;
            object objWhich = Word.WdGoToDirection.wdGoToAbsolute;
            object objPage  = iPage;

            Word.Range rangePage = myDoc.GoTo(ref objWhat, ref objWhich, ref objPage, ref missing);
            rangeText            = rangePage;
            wdTextColor          = rangePage.Font.Color;
            rangePage.End        = (int)iEnd;
            rangePage.Font.Color = WdColor.wdColorWhite;
        }
コード例 #8
0
ファイル: TestReport.cs プロジェクト: wwwK/2016
        /// <summary>
        /// 获取指定页的 Range。。。
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public Range GetPages(int pageIndex)
        {
            object objWhat  = WdGoToItem.wdGoToPage;
            object objWhich = WdGoToDirection.wdGoToAbsolute;
            object oMissing = System.Reflection.Missing.Value;
            object objPage  = pageIndex;
            Range  range1   = wordDoc.GoTo(ref objWhat, ref objWhich, ref objPage, ref oMissing);
            Range  range2   = range1.GoToNext(WdGoToItem.wdGoToPage);
            object objStart = range1.Start;
            object objEnd   = range2.Start;

            if (range1.Start == range2.Start)
            {
                objEnd = wordDoc.Content.End;
            }
            else
            {
                objEnd = range2.Start - 1;
            }

            return(wordDoc.Range(ref objStart, ref objEnd));
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: 15831944/Code-4
    //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);
    }
コード例 #10
0
ファイル: City.cs プロジェクト: cykb518hu/Scraper
        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);
        }
コード例 #11
0
        /// <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);
            }
        }