C#修改word页眉页脚的文字和图片

**

方法一:Spire.Doc修改word页眉页脚的文字和图片

**

		Spire.Doc有付费和免费版。文档关于接口的描述很详细,免费版有个问题,会在第一页生成
Evaluation Warning: The document was created with Spire.Doc for .NET.
虽然后面有办法将这行字符串给去掉,但是显得不够直接。
		Spire.Docm目前支持的开发语言有Java,VB和C#,因为对C++比较熟悉,所以选择C#开发
private void modifyPage(string fileName)
        {
            Document document = new Document();
            document.LoadFromFile(fileName);
            Section section = document.Sections[0];
            section.PageSetup.DifferentFirstPageHeaderFooter = false;

            //Handle header
            HeaderFooter header = document.Sections[0].HeadersFooters.Header;
            int count = header.Paragraphs.Count;
            for (int i = 0; i < count; i++)
            {
                int child_count = header.Paragraphs[i].ChildObjects.Count;
                for (int c = 0; c < child_count; c++)
                {
                    DocumentObject child = header.Paragraphs[i].ChildObjects[c];
                    if (child.DocumentObjectType == DocumentObjectType.Picture)
                    {
                        DocPicture pic = (DocPicture)child;
                        pic.LoadImage(Image.FromFile("logo.png"));
                        pic.Width = 60;
                        pic.Height = 20;
                    }
                    else if (child.DocumentObjectType == DocumentObjectType.TextRange)
                    {
                        TextRange text = (TextRange)child;
                        String sn = text.Text;
                        if (sn.Contains("oldstr"))
                        {
                            sn = sn.Replace("oldstr", "newstr");
                            text.Text = sn;
                        }
                    }
                }
            }

            // Handle footer
            HeaderFooter footer = document.Sections[0].HeadersFooters.Footer;
            if (footer.Paragraphs.Count > 0)
            {
                String old_str = footer.Paragraphs[0].Text;
                String new_str = old_str.Replace("oldstr", "newstr");
                footer.Paragraphs[0].Text = new_str;
                Console.WriteLine(footer.Paragraphs[0].Text);
            }          

            //Save doc file.
            String[] paths=fileName.Split('\\');
            int path_num = paths.Length;
            String exe_path = System.Environment.CurrentDirectory + "\\output\\";
            for (int i = 2; i < path_num - 1; i++)
                exe_path += paths[i]+"\\";

            if (!Directory.Exists((exe_path)))
                    Directory.CreateDirectory(exe_path);

            String file_name = exe_path+System.IO.Path.GetFileName(fileName);
            document.SaveToFile(file_name);
        }

    

你可能感兴趣的:(C#修改word页眉页脚的文字和图片)