9

我的 OpenXML Word 文档生成项目需要文本、表格和图像。但首先,我需要一个带有徽标(图像)的文档标题。

我在 使用 Open XML SDK 2.0 for Microsoft Office 生成带有页眉和页脚的文档在 Word 2007 中使用Microsoft 示例创建页眉和页脚,文本页眉工作得很好,但图像显示在页眉中损坏的图像图标、大小正确的边框和消息“此图像当前无法显示”。另外,我可以将所选图像加载到文档正文中。以下是我创建 ImagePart 的方法:

// Create AG logo part.
_agLogoPart = mainDocumentPart.AddImagePart(ImagePartType.Jpeg);
using (FileStream stream = new FileStream(_agLogoFilename, FileMode.Open))
{
    _agLogoPart.FeedData(stream);
}
_agLogoRel = mainDocumentPart.GetIdOfPart(_agLogoPart);

图像使用 LoadImage 方法加载,该方法源自 Microsoft 示例,但添加了宽度和高度参数,并返回一个绘图对象:

private static Drawing LoadImage(string relationshipId,
                             string filename,
                             string picturename,
                             double inWidth,
                             double inHeight)
{
double emuWidth = Konsts.EmusPerInch * inWidth;
double emuHeight = Konsts.EmusPerInch * inHeight;

var element = new Drawing(
    new DW.Inline(
    new DW.Extent { Cx = (Int64Value)emuWidth, Cy = (Int64Value)emuHeight },
    new DW.EffectExtent { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L },
    new DW.DocProperties { Id = (UInt32Value)1U, Name = picturename },
    new DW.NonVisualGraphicFrameDrawingProperties(
    new A.GraphicFrameLocks { NoChangeAspect = true }),
    new A.Graphic(
    new A.GraphicData(
    new PIC.Picture(
    new PIC.NonVisualPictureProperties(
    new PIC.NonVisualDrawingProperties { Id = (UInt32Value)0U, Name = filename },
    new PIC.NonVisualPictureDrawingProperties()),
    new PIC.BlipFill(
    new A.Blip(
    new A.BlipExtensionList(
    new A.BlipExtension { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" }))
    {
    Embed = relationshipId,
    CompressionState = A.BlipCompressionValues.Print },
    new A.Stretch(
    new A.FillRectangle())),
    new PIC.ShapeProperties(
    new A.Transform2D(
    new A.Offset { X = 0L, Y = 0L },
    new A.Extents { Cx = (Int64Value)emuWidth, Cy = (Int64Value)emuHeight }),
    new A.PresetGeometry(
    new A.AdjustValueList()) { Preset = A.ShapeTypeValues.Rectangle })))
    {
        Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"
    }))
    {
        DistanceFromTop = (UInt32Value)0U,
        DistanceFromBottom = (UInt32Value)0U,
        DistanceFromLeft = (UInt32Value)0U,
        DistanceFromRight = (UInt32Value)0U,
        EditId = "50D07946"
    });
return element;
}

使用它,以下代码可以工作,将图像加载到我想要的正文中的任何位置:

Paragraph paraImage = new Paragraph(new Run(LoadImage(_genomeImageRel, _genomeImageFilename, "name" + _genomeImageRel, 7.5, 2.925)));
body.AppendChild(paraImage);

以下代码无法将徽标图像放在标题中:

private static Header GeneratePageHeaderPart(string headerText)
{
    Header hdr = new Header(new Paragraph(new Run(LoadImage(_agLogoRel, _agLogoFilename, "name" + _agLogoRel, 2.57, 0.73))));
    return hdr;
}

我怀疑我做错了一些非常微妙的事情,因为我可以在除标题之外的任何地方加载图像。任何人都可以建议吗?

4

3 回答 3

10

我怀疑我做错了一些非常微妙的事情,因为我可以在除标题之外的任何地方加载图像。

如果您能够在主文档中插入图像,您还可以使用此代码 ( private static Drawing LoadImage) 在页眉或页脚中插入图像。

唯一的区别是您添加的位置ImagePart

  • 要在文档正文中插入图像,请ImagePartMainDocumentPart:

    _agLogoPart = mainDocumentPart.AddImagePart(ImagePartType.Jpeg);
    ...
     _agLogoRel = mainDocumentPart.GetIdOfPart(_agLogoPart);
    
  • 要在标题中插入图像,您需要添加一个ImagePart用于HeaderPart创建标题的

    _agLogoPart = headerPart.AddImagePart(ImagePartType.Jpeg);
    ...
    _agLogoRel = headerPart.GetIdOfPart(_agLogoPart);
    
  • 要在页脚中插入图像,您需要在ImagePart用于FooterPart创建页脚的 中添加一个:

    _agLogoPart = footerPart.AddImagePart(ImagePartType.Jpeg);
    ...
    _agLogoRel = footerPart.GetIdOfPart(_agLogoPart);
    

有关的:

于 2013-08-02T15:28:26.720 回答
0

请尝试以下代码:

Bitmap image = new Bitmap(imagePath);
SdtElement controlBlock = doc.MainDocumentPart.HeaderParts.First().Header.Descendants<SdtElement>().Where
                                (r => r.SdtProperties.GetFirstChild<Tag>().Val == tagName).SingleOrDefault();
 //find the Blip element of the content control
 Blip blip = controlBlock.Descendants<Blip>().FirstOrDefault();

 //add image and change embeded id
 ImagePart imagePart = doc.MainDocumentPart.AddImagePart(ImagePartType.Jpeg);
 using (MemoryStream stream = new MemoryStream())
 {
      image.Save(stream, ImageFormat.Jpeg);
      stream.Position = 0;
      imagePart.FeedData(stream);
 }
 blip.Embed = doc.MainDocumentPart.GetIdOfPart(imagePart);
于 2013-07-19T15:04:43.400 回答
0
private static MainDocumentPart AddHeader(MainDocumentPart mainDocPart)
        {
            string LogoFilename = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/Images/TemplateLogo.png");     
            mainDocPart.DeleteParts(mainDocPart.HeaderParts);
            var FirstHeaderPart = mainDocPart.AddNewPart<HeaderPart>();
            var DefaultHeaderPart = mainDocPart.AddNewPart<HeaderPart>();
            var imgPartFirst = FirstHeaderPart.AddImagePart(ImagePartType.Jpeg);           
            var imagePartFirstID = FirstHeaderPart.GetIdOfPart(imgPartFirst);
            var imgPartDefault = FirstHeaderPart.AddImagePart(ImagePartType.Jpeg);
            var imagePartDefaultID = FirstHeaderPart.GetIdOfPart(imgPartDefault);
            using (FileStream fs = new FileStream(LogoFilename, FileMode.Open))
            {
                imgPartFirst.FeedData(fs);                
            }
            using (FileStream fsD = new FileStream(LogoFilename, FileMode.Open))
            {
                imgPartDefault.FeedData(fsD);
            }
            var rIdFirst = mainDocPart.GetIdOfPart(FirstHeaderPart);
            var FirstHeaderRef = new HeaderReference { Id = rIdFirst, Type = HeaderFooterValues.First };
            var rIdDefault = mainDocPart.GetIdOfPart(DefaultHeaderPart);
            var DefaultHeaderRef = new HeaderReference { Id = rIdDefault };

            var sectionProps = mainDocPart.Document.Body.Elements<SectionProperties>().LastOrDefault();
            if (sectionProps == null)
            {
                sectionProps = new SectionProperties();
                mainDocPart.Document.Body.Append(sectionProps);
            }
            sectionProps.RemoveAllChildren<HeaderReference>();        
            FirstHeaderPart.Header = GenerateFirstPicHeader(imagePartFirstID);
            DefaultHeaderPart.Header = GeneratePicHeader(imagePartDefaultID);
            FirstHeaderPart.Header.Save();
            DefaultHeaderPart.Header.Save();
            sectionProps.PrependChild(new TitlePage());

            sectionProps.AppendChild(DefaultHeaderRef);
            sectionProps.AppendChild(FirstHeaderRef);

            return mainDocPart;
        }
于 2018-09-16T16:40:24.723 回答