You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Open XML SDK导出Word时添加页眉Logo失败求助

解决Open XML SDK添加页眉图片不显示的问题

问题描述

我使用Open XML SDK,通过using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(memStream, WordprocessingDocumentType.Document))创建Word文档,尝试添加图片到页面页眉,但页眉显示空白;文档正文的其他文本内容均正常显示。原代码如下:

HeaderPart headerPart = mainPart.AddNewPart<HeaderPart>();
string logoRld = "rId" + Guid.NewGuid().ToString("N");
GenerateHeaderPart1Content(headerPart, ImagePath, logoRld);
HeaderReference headerReference = new HeaderReference() { Type = HeaderFooterValues.Default, Id = "rId1" }; // mainPart.GetIdOfPart(headerPart) };
SectionProperties sectionProperties = new SectionProperties(headerReference);
mainPart.Document.Body.Append(sectionProperties);

static void GenerateHeaderPart1Content(HeaderPart headerPart, string imagepath, string logoRld)
{
    ImagePart imagePart = headerPart.AddImagePart(ImagePartType.Jpeg, "rId1");
    SetImagePartContent(imagePart, imagepath);

    Drawing drawing = new Drawing();
    Inline inline = new Inline(
        new Extent() { Cx = 990000L, Cy = 792000L },
        new DocProperties(),
        new DocumentFormat.OpenXml.Drawing.Graphic(
            new DocumentFormat.OpenXml.Drawing.GraphicData(
                new DocumentFormat.OpenXml.Drawing.Pictures.Picture(
                        new DocumentFormat.OpenXml.Drawing.BlipFill(
                        new DocumentFormat.OpenXml.Drawing.Blip() { Embed = "rId2" },
                        new DocumentFormat.OpenXml.Drawing.Stretch(new DocumentFormat.OpenXml.Drawing.FillRectangle())),
                    new DocumentFormat.OpenXml.Drawing.ShapeProperties(
                        new DocumentFormat.OpenXml.Drawing.NoFill()
                        )))));
  
    drawing.Append(inline);
    Paragraph paragraph = new Paragraph(drawing);
    headerPart.Header = new Header(paragraph);
}

static void SetImagePartContent(ImagePart imagePart, string imagepath)
{
    using (FileStream inFile = new FileStream(imagepath, FileMode.Open, FileAccess.Read))
    {
        byte[] byteArray = new byte[inFile.Length];
        inFile.Read(byteArray, 0, (int)inFile.Length);
        imagePart.FeedData(new MemoryStream(byteArray));
    }
}

错误原因分析

  1. HeaderReference关联ID错误:硬编码Id = "rId1",但实际页眉部件的ID需要通过mainPart.GetIdOfPart(headerPart)获取,否则文档无法正确关联页眉。
  2. 图片Embed ID不匹配:添加ImagePart时指定的ID是"rId1",但Blip的Embed属性写的是"rId2",导致无法找到图片资源。
  3. 缺少Run元素:Paragraph直接包含Drawing不符合Open XML结构,需要将Drawing放入Run中再添加到Paragraph。
  4. ShapeProperties不完整:仅设置NoFill会导致图片的轮廓和位置信息缺失,需要补充Outline和Transform。

修正后的代码

// 添加页眉部件并获取关联ID
HeaderPart headerPart = mainPart.AddNewPart<HeaderPart>();
string headerId = mainPart.GetIdOfPart(headerPart);
GenerateHeaderPart1Content(headerPart, ImagePath);

// 创建正确的页眉引用和节属性
HeaderReference headerReference = new HeaderReference() 
{ 
    Type = HeaderFooterValues.Default, 
    Id = headerId 
};
SectionProperties sectionProperties = new SectionProperties(headerReference);
mainPart.Document.Body.Append(sectionProperties);

static void GenerateHeaderPart1Content(HeaderPart headerPart, string imagepath)
{
    // 添加图片部件,自动生成ID
    ImagePart imagePart = headerPart.AddImagePart(ImagePartType.Jpeg);
    string imageId = headerPart.GetIdOfPart(imagePart);
    SetImagePartContent(imagePart, imagepath);

    // 构建完整的Drawing元素
    Drawing drawing = new Drawing(
        new Inline(
            new Extent() { Cx = 990000L, Cy = 792000L },
            new DocProperties() { Id = 1U, Name = "Header Image" },
            new Graphic(
                new GraphicData(
                    new Picture(
                        new BlipFill(
                            new Blip() { Embed = imageId },
                            new Stretch(new FillRectangle())
                        ),
                        new ShapeProperties(
                            new Transform2D(
                                new Offset() { X = 0L, Y = 0L },
                                new Extents() { Cx = 990000L, Cy = 792000L }
                            ),
                            new Outline(
                                new NoFill()
                            )
                        )
                    )
                ) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" }
            )
        ) { DistanceFromTop = 0U, DistanceFromBottom = 0U, DistanceFromLeft = 0U, DistanceFromRight = 0U }
    );

    // 构建正确的段落结构:Paragraph -> Run -> Drawing
    Run run = new Run(drawing);
    Paragraph paragraph = new Paragraph(run);
    headerPart.Header = new Header(paragraph);
}

static void SetImagePartContent(ImagePart imagePart, string imagepath)
{
    using (FileStream inFile = new FileStream(imagepath, FileMode.Open, FileAccess.Read))
    {
        // 直接传入文件流,无需转字节数组
        imagePart.FeedData(inFile);
    }
}

关键修正点说明

  • 使用mainPart.GetIdOfPart(headerPart)获取页眉部件的实际关联ID,确保文档能正确识别页眉。
  • 通过headerPart.GetIdOfPart(imagePart)获取图片部件的ID,保证Blip的Embed属性与图片ID一致。
  • 按照Paragraph -> Run -> Drawing的正确层级构建内容,符合Open XML的文档结构规范。
  • 补充Transform2D和Outline到ShapeProperties中,确保图片的位置和显示样式正确。
  • 优化图片流的写入方式,直接传入FileStream,避免不必要的字节数组转换。

内容的提问来源于stack exchange,提问作者siri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 20:25:16