为有中文需求的客户提供多渠道中文技术支持.

Sat Nov 19, 2022 9:22 am

第一个问题:请问如何设置页眉的段落中字体的自定义样式?
在word文档中的设置方式:选中文字,点击右键,选择样式,选择创建样式,再点击修改,左下角点击格式,再选择边框。在弹出的对话框中设置边框样式后点击确定,此时即可以应用自定义样式。但不知如何使用C#设置这样的自定义样式
第二个问题:如何隐藏节中的页眉
1.使用C#创建一个Doc,doc中添加了多个Section,在第一个section中设置了doc的HeaderFooter,此时整个doc都会显示页眉和页脚。
2.设置某一个section的pageSection.PageSetup.DifferentFirstPageHeaderFooter = true;属性,会将真个section的页眉和页脚影藏掉
3.此时如果我想某一个节只隐藏页眉,显示页脚,并且该section的设置不能影响其它section,我应该如何设置
谢谢回复。

doctorfeng
 
Posts: 2
Joined: Sat Sep 10, 2022 2:09 pm

Mon Nov 21, 2022 7:19 am

您好,

感谢您的留言。
第一个问题:请问如何设置页眉的段落中字体的自定义样式?
请参考下面的代码:

Code: Select all
//加载文档
            Document doc = new Document();
            doc.LoadFromFile(@"../../data/testHeader.docx");
         
            //获取section 1的页眉
            HeaderFooter header = doc.Sections[0].HeadersFooters.Header;

            //创建名为“style1”的自定义段落格式
            ParagraphStyle paragraphStyle = doc.AddParagraphStyle("style1");
     
            //设置字体
            paragraphStyle.CharacterFormat.FontName = "微软雅黑";
       
            //设置字体大小
            paragraphStyle.CharacterFormat.FontSize = 20f;

            //设置字体为斜体显示
            paragraphStyle.CharacterFormat.Italic = true;

            //设置字体加粗显示
            paragraphStyle.CharacterFormat.Bold = true;

            //为页眉的第一个段落应用名为“style1”的自定义样式
            header.Paragraphs[0].ApplyStyle("style1");

            //保存结果文档
            doc.SaveToFile(@"../../output/result_no_link.docx",FileFormat.Docx);


第二个问题:如何隐藏节中的页眉
请参考下面的代码:

Code: Select all
  //加载文档
            Document doc = new Document();
            doc.LoadFromFile(@"../../data/testHeader.docx");

            //设置每一节的页眉不受其他节的页眉影响
            foreach (Section section in doc.Sections)
            {
                section.HeadersFooters.Header.LinkToPrevious = false;
            }

            //获取section 2的页眉
            HeaderFooter header = doc.Sections[1].HeadersFooters.Header;

            //隐藏section 2的页眉
            foreach(Paragraph paragraph in header.Paragraphs)
            {
                foreach(DocumentObject obj in paragraph.ChildObjects)
                {
                    if(obj.DocumentObjectType == DocumentObjectType.TextRange)
                    {
                        TextRange textRange = (TextRange)obj;
                        textRange.CharacterFormat.Hidden = true;
                    }
                }
            }

            //保存结果文档
            doc.SaveToFile(@"../../output/result_hidden.docx", FileFormat.Docx);

我将我用于测试的文档放在附件中供你测试参考,如果您还有任何问题,欢迎随时留言。

Sincerely
Abel
E-iceblue support team
User avatar

Abel.He
 
Posts: 951
Joined: Tue Mar 08, 2022 2:02 am

Return to 中文技术支持