如何在Word首个页脚插入图片并设置显示范围与位置?
C# OpenXML SDK Word页脚问题解决方案
已通过C# OpenXML SDK实现Word页脚文本插入,现有代码如下:
static void Main(string[] args) { CreateFooter(@"D:\1.docx"); } static void CreateFooter(String documentPath) { using (WordprocessingDocument document = WordprocessingDocument.Open(documentPath, true)) { MainDocumentPart mainDocumentPart = document.MainDocumentPart; mainDocumentPart.DeleteParts(mainDocumentPart.FooterParts); FooterPart footerPart = mainDocumentPart.AddNewPart<FooterPart>(); string footerPartId = mainDocumentPart.GetIdOfPart(footerPart); GenerateFooter(footerPart); var sections = mainDocumentPart.Document.Body.Elements<SectionProperties>().FirstOrDefault(); sections.RemoveAllChildren<FooterReference>(); sections.PrependChild<FooterReference>(new FooterReference() { Id = footerPartId }); } } static void GenerateFooter(FooterPart part) { Footer footer1 = new Footer() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "w14 wp14" } }; footer1.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas"); footer1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006"); footer1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office"); footer1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"); footer1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math"); footer1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml"); footer1.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing"); footer1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"); footer1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word"); footer1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"); footer1.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml"); footer1.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"); footer1.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk"); footer1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml"); footer1.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape"); Paragraph paragraph1 = new Paragraph() { RsidParagraphAddition = "00164C17", RsidRunAdditionDefault = "00164C17" }; ParagraphProperties paragraphProperties1 = new ParagraphProperties(); ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "Footers" }; using (FileStream stream = File.OpenRead(@"C:\Users\Амир\Downloads\Подпись.png")) { var img = Bitmap.FromStream(stream); paragraphProperties1.Append(paragraphStyleId1); Run run1 = new Run(); Text text1 = new Text(); text1.Text = "Footessr"; run1.Append(text1); paragraph1.Append(paragraphProperties1); paragraph1.Append(run1); footer1.Append(paragraph1); part.Footer = footer1; } }
但存在三个待解决问题:
- 在页脚中插入图片
- 设置页脚仅显示在第一页
- 将页脚内容定位到右下角
1. 页脚插入图片
需先向FooterPart添加ImagePart并写入图片流,再构建Drawing元素嵌入段落。修改GenerateFooter方法如下:
// 需添加以下命名空间引用: // using DocumentFormat.OpenXml.Drawing; // using DocumentFormat.OpenXml.Drawing.Wordprocessing; // using DocumentFormat.OpenXml.Drawing.Pictures; static void GenerateFooter(FooterPart part) { Footer footer1 = new Footer() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "w14 wp14" } }; // 保留所有命名空间声明... Paragraph paragraph1 = new Paragraph() { RsidParagraphAddition = "00164C17", RsidRunAdditionDefault = "00164C17" }; ParagraphProperties paragraphProperties1 = new ParagraphProperties(); ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "Footers" }; // 添加右对齐,同步解决第三个定位问题 Justification justification1 = new Justification() { Val = JustificationValues.Right }; paragraphProperties1.Append(paragraphStyleId1); paragraphProperties1.Append(justification1); using (FileStream stream = File.OpenRead(@"C:\Users\Амир\Downloads\Подпись.png")) { // 1. 添加ImagePart并写入图片数据 ImagePart imagePart = part.AddImagePart(ImagePartType.Png); imagePart.FeedData(stream); string imageRelId = part.GetIdOfPart(imagePart); // 2. 构建图片对应的Drawing元素 Drawing drawing = new Drawing( new Inline( new Extent() { Cx = 990000, Cy = 792000 }, // 图片尺寸,可按需调整 new EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L }, new DocProperties() { Id = (UInt32Value)1U, Name = "Footer Image" }, new NonVisualGraphicFrameDrawingProperties( new GraphicFrameLocks() { NoChangeAspect = true }), new Graphic( new GraphicData( new Picture( new NonVisualPictureProperties( new NonVisualDrawingProperties() { Id = (UInt32Value)0U, Name = "Подпись.png" }, new NonVisualPictureDrawingProperties()), new BlipFill( new Blip( new BlipExtensionList( new BlipExtension() { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" }) ) { Embed = imageRelId, CompressionState = BlipCompressionValues.Print }, new Stretch( new FillRectangle())), new ShapeProperties( new Transform2D( new Offset() { X = 0L, Y = 0L }, new Extents() { Cx = 990000, Cy = 792000 }), new PresetGeometry( new AdjustValueList()) { Preset = ShapeTypeValues.Rectangle })) ) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" }) ) { DistanceFromTop = (UInt32Value)0U, DistanceFromBottom = (UInt32Value)0U, DistanceFromLeft = (UInt32Value)0U, DistanceFromRight = (UInt32Value)0U, EditId = "50D07946" }); // 3. 创建包含图片的Run Run imageRun = new Run(); imageRun.Append(drawing); // 4. 保留文本Run(可选) Run textRun = new Run(); Text text1 = new Text(); text1.Text = "Footessr"; textRun.Append(text1); paragraph1.Append(paragraphProperties1); paragraph1.Append(textRun); paragraph1.Append(imageRun); footer1.Append(paragraph1); part.Footer = footer1; } }
2. 设置页脚仅显示在第一页
修改CreateFooter方法中的SectionProperties处理逻辑,启用首页不同并指定Footer类型为First:
static void CreateFooter(String documentPath) { using (WordprocessingDocument document = WordprocessingDocument.Open(documentPath, true)) { MainDocumentPart mainDocumentPart = document.MainDocumentPart; mainDocumentPart.DeleteParts(mainDocumentPart.FooterParts); FooterPart footerPart = mainDocumentPart.AddNewPart<FooterPart>(); string footerPartId = mainDocumentPart.GetIdOfPart(footerPart); GenerateFooter(footerPart); var sections = mainDocumentPart.Document.Body.Elements<SectionProperties>().FirstOrDefault(); if (sections == null) { // 文档无SectionProperties时,创建新的并添加到Body末尾 sections = new SectionProperties(); mainDocumentPart.Document.Body.Append(sections); } sections.RemoveAllChildren<FooterReference>(); // 启用首页不同设置 if (sections.Elements<DifferentFirstPage>().FirstOrDefault() == null) { sections.PrependChild<DifferentFirstPage>(new DifferentFirstPage()); } // 指定当前Footer为首页专属 sections.PrependChild<FooterReference>(new FooterReference() { Id = footerPartId, Type = HeaderFooterValues.First }); } }
3. 页脚内容定位到右下角
核心是设置段落右对齐,已包含在上述GenerateFooter方法的paragraphProperties1.Append(justification1);代码中,对应代码:
Justification justification1 = new Justification() { Val = JustificationValues.Right }; paragraphProperties1.Append(justification1);
若需要更精确的偏移定位,可添加TabStop设置:
// 添加右侧Tab位(对应页面宽度914400缇,可按需调整) TabStop tabStop = new TabStop() { Val = TabStopValues.Right, Position = "914400" }; paragraphProperties1.Append(new TabStops(tabStop));
然后在文本前添加Tab字符:
Text text1 = new Text(); text1.Text = "\tFootessr";
整合后的完整代码可直接运行,同时解决三个问题。
内容的提问来源于stack exchange,提问作者Student
相关产品推荐
相关产品推荐

