狂自私

导航

C#-根据word页面内容打印每一页为PDF

写的很一般,我没有学习过C#,就是拼拼凑凑来的。

using Word = Microsoft.Office.Interop.Word;
using System.Windows.Forms;
using Microsoft.Office.Interop.Word;
using System.Collections;
using System;
using System.Text.RegularExpressions;

namespace print_page
{
    public partial class ThisAddIn
    {
        string file_path = "";
        string file_directory = "";
        string file_baseName = "";
        Word.Document myword;           //word文档对象
        ArrayList start=new ArrayList();    //page起始index列表
        ArrayList end=new ArrayList();      //page结束index列表
        ArrayList PDF_fileName = new ArrayList();      //PDF文件名列表,防止文件名重复导致打印失败

        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            //选择文件
            System.Windows.Forms.OpenFileDialog fileDialog = new System.Windows.Forms.OpenFileDialog
            {
                InitialDirectory = System.AppDomain.CurrentDomain.BaseDirectory,          //初始化路径
                Filter = "word文档(*.docx)|*.docx",                                      //过滤word文档
                Title = "选择word文档"                                                   //窗口标题
            };
            if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                file_path = fileDialog.FileName;
                this.file_directory = System.IO.Path.GetDirectoryName(file_path);
                this.file_baseName= System.IO.Path.GetFileNameWithoutExtension(file_path);
            }
            else 
            {
                //结束程序
                //System.Environment.Exit(0);
                this.Application.Quit();
            }

            this.myword = this.Application.Documents.Open(file_path, ReadOnly: true);
            int pages = myword.ComputeStatistics(Word.WdStatistic.wdStatisticPages);    //文档页数
            get_pageIndex();        //获取页码的起始index
            for (int i = 1; i <= pages; ++i)
            {
                //获取省份名称
                string provinceName = get_ProvinceName(i);
                //确定文件名
                this.GenerateFilename(this.file_directory + "\\" + this.file_baseName + "-" + provinceName + "-1.pdf");
            }
            for (int i = 1; i <= pages; ++i)
            {
                //打印
                print_page(page_number: i, file_name: this.PDF_fileName[i - 1].ToString());
            }
            //关闭文档
            Word.Document document = this.Application.ActiveDocument;
            document.Close(Word.WdSaveOptions.wdDoNotSaveChanges,OriginalFormat:Word.WdOriginalFormat.wdOriginalDocumentFormat);

            //结束程序
            this.Application.Quit();
        }
        
        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {

        }
        void Application_DocumentBeforeSave(Word.Document Doc, ref bool SaveAsUI, ref bool Cancel)
        {
            Doc.Paragraphs[1].Range.InsertParagraphBefore();
            Doc.Paragraphs[1].Range.Text = "This text was added by using code.";
        }
        //确定唯一的文件名
        string GenerateFilename(string fileName)
        {
            bool flag = false;
            string fileName_new="";    //新文件名
            for (int i = 0; i < this.PDF_fileName.Count; ++i)
            {
                if (PDF_fileName[i].ToString() == fileName)
                {
                    flag = true;
                    //重名了
                    fileName_new = fileName.Substring(0, fileName.Length - 6);
                    if(i+1 == this.PDF_fileName.Count)
                    {
                        //说明本文件名是-2
                        fileName_new += "-2.pdf";
                        this.PDF_fileName.Add(fileName_new);
                    }
                    else
                    {
                        //说明文件名可能是-3,-4等
                        fileName_new += "-" + (this.PDF_fileName.Count - i + 1).ToString() + ".pdf";
                        this.PDF_fileName.Add(fileName_new);
                    }
                    break;
                }
                else
                {
                    flag = false;
                }
            }
            if (!flag)
            {
                this.PDF_fileName.Add(fileName);
                fileName_new = fileName;
            }
            return fileName_new;

        }
        //打印指定的页码
        void print_page(int page_number,string file_name)
        {
            object copies = "1";
            object pages = page_number.ToString();
            object range = Word.WdPrintOutRange.wdPrintRangeOfPages;
            object items = Word.WdPrintOutItem.wdPrintDocumentContent;
            object pageType = Word.WdPrintOutPages.wdPrintAllPages;
            object oTrue = true;
            object oFalse = false;
            object fileName = file_name;

            this.Application.ActiveDocument.PrintOut(
                Background: ref oTrue,
                Append: ref oFalse,
                Range: ref range,
                OutputFileName: ref fileName,
                From: ref missing,
                To: ref missing,
                Item: ref items,
                Copies: ref copies,
                Pages: ref pages,
                PageType: ref pageType,
                PrintToFile: ref oTrue,
                Collate: ref oTrue,
                ActivePrinterMacGX: ref missing,
                ManualDuplexPrint: ref oFalse,
                PrintZoomColumn: ref missing,
                PrintZoomRow: ref missing,
                PrintZoomPaperWidth: ref missing,
                PrintZoomPaperHeight: ref missing);
        }
        //获取省份
        string get_ProvinceName(int page_number){
            ArrayList names = new ArrayList();
            //选中当前页
            Word.Range page_range = Application.ActiveDocument.Range(this.start[page_number - 1], this.end[page_number - 1]);
            //将搜索字符串分配给变量。
            object findText = "^13";       //表达式,用来匹配段落标记
            //清除之前的搜索的格式。
            Application.Selection.Find.ClearFormatting();
            //新建一个文档
            Word.Document temp = Application.Documents.Add(Visible: false);
            //复制页面内容
            page_range.Select();
            Word.Selection page_range_Selection = Application.Selection;
            page_range_Selection.Copy();
            temp.Activate();        //激活
            page_range_Selection = Application.Selection;
            page_range_Selection.Paste();   //粘贴到新文档中
            page_range = temp.Content;      

            //替换换行字符,原本文档里面的段落标记要替换为换行符
            page_range.Find.Execute(FindText: ref findText,      //要搜索的文本
                    MatchCase: ref missing,          //True 指定查找文本是区分大小写
                    MatchWholeWord: ref missing,     //如果该属性值为 True ,则查找操作仅查找整个单词,而不是较长单词的一部分的文本。 对应于“查找和替换”对话框中的“全字匹配”复选框。
                    MatchWildcards: true,            //要查找的文字是特殊搜索操作符。 对应于“查找和替换”对话框中的“使用通配符”复选框。
                    MatchSoundsLike: ref missing,    //类似于查找的文字发音单词 
                    MatchAllWordForms: ref missing,  //查找操作定位查找文字的所有形式  
                    Forward: ref missing,            //向前搜索
                    Wrap: ref missing,               //如果从文档开头之外的某个位置开始搜索,并到达文档结尾处(反之亦然,如果 Forward 设置为False),则控制所发生的操作。 此参数还控制在选定内容或区域中找不到搜索文本时,将会发生什么情况。
                    Format: ref missing,             //如果该属性值为 True ,则查找操作定位于格式,而不是查找文本。
                    ReplaceWith: "^p",               //替换的文字。
                    Replace: Word.WdReplace.wdReplaceAll,//指定要执行替换的个数:一个、全部或者不替换。此处是替换所有项
                    MatchKashida: ref missing,       //如果查找操作用 kashida 阿拉伯语文档中匹配的文本。
                    MatchDiacritics: ref missing,    //如果查找操作用匹配从右到左语言的文档中的音调符号来匹配文字。
                    MatchAlefHamza: ref missing,     //如果查找操作用匹配 alef hamza 适用于阿拉伯语文档中的匹配的文本
                    MatchControl: ref missing);      //如果查找操作用匹配的从右到左语言的文档中的双向控制字符来匹配文字。

            //使用正则查询
            string content_text = page_range.Text.Replace("\r","\n");
            string pattern = @"\n\w{2,8}\t";
            foreach (Match match in Regex.Matches(content_text, pattern))
            {
                string text_ = match.Value.Trim();
                //标志,false表示不重复
                bool flag = false;
                //检查是否重复
                foreach (string name in names)
                {
                    if (text_ == name)
                    {
                        flag = true;
                        break;
                    }
                    else
                    {
                        flag = false;
                    }
                }
                //若是不重复
                if (!flag)
                {
                    names.Add(text_);
                }
            }



            string result_text = "";
            foreach (string name in names)
            {
                result_text += name + "&";
            }
            if (result_text.Length > 0)
            {
                result_text = result_text.Substring(0, result_text.Length - 1);
            }

            //关闭tmep文档
            temp.Close(SaveChanges:Word.WdSaveOptions.wdDoNotSaveChanges);      //关闭而不保存
            myword.Activate();      //激活源文档
            return result_text;
        }

        //粗略获取一页的起始位置
        void get_pageIndex()
        {
            Word.Range rng = myword.Content;

            rng.Find.ClearFormatting();
            rng.Find.Forward = true;
            rng.Find.Text = "红章盖章区域";
            Word.Selection currentSelection;
            int num = 0;
            do
            {
                rng.Find.Execute(
                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);
                if (rng.Find.Found)
                {
                    rng.Select();
                    currentSelection = Application.Selection;
                    if (num == 0)
                    {
                        this.start.Add(num);
                    }
                    else
                    {
                        this.start.Add(this.end[num - 1]);
                    }
                    this.end.Add(currentSelection.End);
                }
                num = num + 1;
            } while (rng.Find.Found);
        }


        #region VSTO 生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }

        #endregion
    }
}
View Code

 

posted on 2022-10-31 21:03  狂自私  阅读(62)  评论(0编辑  收藏  举报