简体   繁体   English

使用OpenXML SDK C#以编程方式将FootNotes添加到Word文档

[英]Add FootNotes to Word Document Programatically using OpenXML SDK C#

I need to create a Word Document using Open XML SDK. 我需要使用Open XML SDK创建Word文档。 I have the document text and the Footnotes . 我有文档文本和脚注。 I am using the below Snippets to Create the Word Document. 我正在使用下面的代码片段创建Word文档。 I am able to create the document with the text ,But I am not able to add Footnotes to it. 我可以使用文本创建文档,但是无法在其中添加脚注。 Can you please let us know how to add FootNotes programmatically using Open Xml 您能否让我们知道如何使用Open Xml以编程方式添加FootNotes

   public void CreateWordDocument()
   {

       using (MemoryStream DocxMemory = new MemoryStream())
       {
           using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(DocxMemory, WordprocessingDocumentType.Document, true))
           {
               // Add a main document part. 
               MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
               // Create the document structure and add some text.
               this.AddSettingsToMainDocumentPart(mainPart);

               StyleDefinitionsPart part = mainPart.StyleDefinitionsPart;
               // If the Styles part does not exist, add it.  
               if (part == null)
               {
                   this.AddStylesPartToPackage(mainPart);
               }

               mainPart.Document = new Document();
               Body body = mainPart.Document.AppendChild(new Body());
               Paragraph Para = body.AppendChild(new Paragraph());
               Run run = Para.AppendChild(new Run());
               run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text("This is main text of the document"));

               var footnotesPart = mainPart.AddNewPart<FootnotesPart>("rId1");

               this.GenerateFooterPartContent(mainPart.FootnotesPart);
               mainPart.Document.Save();
               wordDocument.Close();

               MemoryStream Result = new MemoryStream();
               DocxMemory.Seek(0, SeekOrigin.Begin);
               DocxMemory.CopyTo(Result);
               Result.Position = 0;

               ////Citation processing
               byte[] BufferFileData = new byte[Result.Length];
               Result.Read(BufferFileData, 0, (int)Result.Length);
               File.WriteAllBytes("Output1.docx", BufferFileData);

           }
       }
   }

   private void AddSettingsToMainDocumentPart(MainDocumentPart part)
   {
       DocumentSettingsPart settingsPart = part.DocumentSettingsPart;
       if (settingsPart == null)
           settingsPart = part.AddNewPart<DocumentSettingsPart>();
       settingsPart.Settings = new Settings(
         new Compatibility(
           new CompatibilitySetting()
           {
               Name = new EnumValue<CompatSettingNameValues>
                       (CompatSettingNameValues.CompatibilityMode),
               Val = new StringValue("14"),
               Uri = new StringValue
                       ("http://schemas.microsoft.com/office/word")
           }
      )
   );
       settingsPart.Settings.Save();
   }
   private StyleDefinitionsPart AddStylesPartToPackage(MainDocumentPart mainPart)
   {
       StyleDefinitionsPart part;
       part = mainPart.AddNewPart<StyleDefinitionsPart>();
       Styles root = new Styles();
       root.Save(part);
       return part;
   }

   // Generates content of part.
   private void GenerateFooterPartContent(FootnotesPart part)
   {
       Footnotes footnotes1 = new Footnotes() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "w14 wp14" } };
       footnotes1.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
       footnotes1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
       footnotes1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
       footnotes1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
       footnotes1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
       footnotes1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
       footnotes1.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
       footnotes1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
       footnotes1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
       footnotes1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
       footnotes1.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
       footnotes1.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
       footnotes1.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
       footnotes1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
       footnotes1.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");

       Footnote footnote1 = new Footnote() { Type = FootnoteEndnoteValues.Separator, Id = -1 };

       Paragraph paragraph1 = new Paragraph() { RsidParagraphAddition = "003F1A60", RsidParagraphProperties = "00626544", RsidRunAdditionDefault = "003F1A60" };

       Run run1 = new Run();
       SeparatorMark separatorMark1 = new SeparatorMark();

       run1.Append(separatorMark1);

       paragraph1.Append(run1);

       footnote1.Append(paragraph1);

       Footnote footnote2 = new Footnote() { Type = FootnoteEndnoteValues.ContinuationSeparator, Id = 0 };

       Paragraph paragraph2 = new Paragraph() { RsidParagraphAddition = "003F1A60", RsidParagraphProperties = "00626544", RsidRunAdditionDefault = "003F1A60" };

       Run run2 = new Run();
       ContinuationSeparatorMark continuationSeparatorMark1 = new ContinuationSeparatorMark();

       run2.Append(continuationSeparatorMark1);

       paragraph2.Append(run2);

       footnote2.Append(paragraph2);

       Footnote footnote3 = new Footnote() { Id = 1 };

       Paragraph paragraph3 = new Paragraph() { RsidParagraphMarkRevision = "009774CC", RsidParagraphAddition = "00626544", RsidParagraphProperties = "00626544", RsidRunAdditionDefault = "00626544" };

       ParagraphProperties paragraphProperties1 = new ParagraphProperties();


       ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties();
       RunFonts runFonts1 = new RunFonts() { AsciiTheme = ThemeFontValues.MinorHighAnsi, HighAnsiTheme = ThemeFontValues.MinorHighAnsi, ComplexScriptTheme = ThemeFontValues.MinorHighAnsi };
       FontSize fontSize1 = new FontSize() { Val = "24" };
       FontSizeComplexScript fontSizeComplexScript1 = new FontSizeComplexScript() { Val = "24" };

       paragraphMarkRunProperties1.Append(runFonts1);
       paragraphMarkRunProperties1.Append(fontSize1);
       paragraphMarkRunProperties1.Append(fontSizeComplexScript1);
       paragraphProperties1.Append(paragraphMarkRunProperties1);

       Run run3 = new Run() { RsidRunProperties = "009774CC" };

       RunProperties runProperties1 = new RunProperties();
       RunFonts runFonts2 = new RunFonts() { AsciiTheme = ThemeFontValues.MinorHighAnsi, HighAnsiTheme = ThemeFontValues.MinorHighAnsi, ComplexScriptTheme = ThemeFontValues.MinorHighAnsi };
       FontSize fontSize2 = new FontSize() { Val = "24" };
       FontSizeComplexScript fontSizeComplexScript2 = new FontSizeComplexScript() { Val = "24" };
       VerticalTextAlignment verticalTextAlignment1 = new VerticalTextAlignment() { Val = VerticalPositionValues.Superscript };

       runProperties1.Append(runFonts2);
       runProperties1.Append(fontSize2);
       runProperties1.Append(fontSizeComplexScript2);
       runProperties1.Append(verticalTextAlignment1);
       Text text1 = new Text();
       text1.Text = "1";

       run3.Append(runProperties1);
       run3.Append(text1);

      Run run4 = new Run() { RsidRunProperties = "009774CC" };

       RunProperties runProperties2 = new RunProperties();
       RunFonts runFonts3 = new RunFonts() { AsciiTheme = ThemeFontValues.MinorHighAnsi, HighAnsiTheme = ThemeFontValues.MinorHighAnsi, ComplexScriptTheme = ThemeFontValues.MinorHighAnsi };

       runProperties2.Append(runFonts3);
       Text text2 = new Text() { Space = SpaceProcessingModeValues.Preserve };
       text2.Text = " ";

       run4.Append(runProperties2);
       run4.Append(text2);

      Run run5 = new Run() { RsidRunProperties = "009774CC", RsidRunAddition = "009774CC" };

       RunProperties runProperties3 = new RunProperties();
       RunFonts runFonts4 = new RunFonts() { AsciiTheme = ThemeFontValues.MinorHighAnsi, HighAnsiTheme = ThemeFontValues.MinorHighAnsi, ComplexScriptTheme = ThemeFontValues.MinorHighAnsi };
       FontSize fontSize3 = new FontSize() { Val = "21" };
       FontSizeComplexScript fontSizeComplexScript3 = new FontSizeComplexScript() { Val = "21" };

       runProperties3.Append(runFonts4);
       runProperties3.Append(fontSize3);
       runProperties3.Append(fontSizeComplexScript3);
       Text text3 = new Text();
       text3.Text = "This is the foot note text";

       run5.Append(runProperties3);
       run5.Append(text3);

       paragraph3.Append(paragraphProperties1);
       paragraph3.Append(run3);
       paragraph3.Append(run4);
       paragraph3.Append(run5);

       footnote3.Append(paragraph3);

       footnotes1.Append(footnote1);
       footnotes1.Append(footnote2);
       footnotes1.Append(footnote3);
       part.Footnotes = footnotes1;
   }

I managed to add footnotes using the following code. 我设法使用以下代码添加了脚注。 I hope this helps. 我希望这有帮助。

        var ms = new MemoryStream();
        using (WordprocessingDocument myDoc = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document))
        {
            MainDocumentPart mainPart = myDoc.AddMainDocumentPart();
            var footPart = mainPart.AddNewPart<FootnotesPart>();
            footPart.Footnotes = new Footnotes();

            mainPart.Document = new Document();
            Body body = new Body();
            var p = new Paragraph();
            var r = new Run();
            var t = new Text("123");
            r.Append(t);
            p.Append(r);

            // ADD THE FOOTNOTE
            var footnote = new Footnote();
            footnote.Id = 1;
            var p2 = new Paragraph();
            var r2 = new Run();
            var t2 = new Text();
            t2.Text = "My FootNote Content";
            r2.Append(t2);
            p2.Append(r2);
            footnote.Append(p2);
            footPart.Footnotes.Append(footnote);

            // ADD THE FOOTNOTE REFERENCE
            var fref = new FootnoteReference();
            fref.Id = 1;
            var r3 = new Run();
            r3.RunProperties = new RunProperties();
            var s3 = new VerticalTextAlignment();
            s3.Val = VerticalPositionValues.Superscript;
            r3.RunProperties.Append(s3);
            r3.Append(fref);
            p.Append(r3);

            body.Append(p);
            mainPart.Document.Append(body);
            mainPart.Document.Save();
            ms.Flush();
        }
        return ms.ToArray();

I'm not an expert on OpenXML but I think you're missing adding an actual reference to the footnote in the body text, I tweaked your code like this and I now get the footnote in the document. 我不是OpenXML专家,但是我认为您没有在正文中添加对脚注的实际引用,我像这样调整了代码,现在在文档中得到了脚注。 Hope it helps or at least gets you started. 希望它能帮助或至少让您入门。

Run run = Para.AppendChild(new Run());
run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text("This is main text of the document"));
var footnoteref = new FootnoteReference() { Id = 1 };
run.Append(footnoteref);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM