OpenXml多图像损坏Word文档

问题描述

我正在尝试使用OpenXml C#SDK将多个图像插入到Word文档中。我遇到一个问题,即使我尝试插入1张图片,它也损坏了word文档,但我真的无法弄清楚为什么。我很确定DocPropertiesNonVisualDrawingProperties都有唯一的ID。

这是我要建立一些表的地方,然后针对这些部分中的每一个,在表之后插入与该部分相关的所有图片。我在此之前插入图表,因此为什么我要以超过部分的数目开始计数(因为图表使用该部分的ID作为其docproperties等的ID)。

private void GenerateSectionTables(WordprocessingDocument doc,ParentModel parent,bool 
                                   isReport = false,IEnumerable<Section> sections= null)
{
    var newSections = isReport ? reportSections : parents.Sections;
    var imageCounter = parent.Sections.Count() + 2;
    foreach (Section section in newSections)
    {
        ...
        *building up section table*
        ...
        sectionTable.Append(observationRow);

        doc.MainDocumentPart.Document.Body.Append(sectionTable);


        doc.MainDocumentPart.Document.Body.Append(new Paragraph(new Run(new Break())));

        if (isReport)
        {
            var filteredFiles = parent.Files.Where(file => file.SectionId == subitem.Id);
            AttachImages(doc,filteredFiles,imageCounter);
            imageCounter += filteredFiles.Count() + 1;
        }
    }

这是我生成ImagePart并将文件数据馈送给它的地方。文件数据存储为字节数组,因此我首先将其拉入流中。

private void AttachImages(WordprocessingDocument doc,IEnumerable<CustomFile> files,int counterStart) 
{
    var counter = counterStart;
    foreach (CustomFile file in files)
    {
       var imagePartType = MapToImagePartType(file);
       if (imagePartType == ImagePartType.Pcx)
           continue;
                
       ImagePart newImage = doc.MainDocumentPart.AddImagePart(imagePartType);

       Stream data = new MemoryStream(file.Content);
       newImage.FeedData(data);
       data.Close();

       AddImagetoBody(doc,doc.MainDocumentPart.GetIdOfPart(newImage),counter,file.FileName);
       counter++;
   }
}

private ImagePartType MapToImagePartType(AttachmentInfo file)
{
    var lowerName = file.FileName.ToLower();
    if (lowerName.Contains("jpeg") || lowerName.Contains("jpg"))
    {
        return ImagePartType.Jpeg;
    } else if (lowerName.Contains("png"))
    {
       return ImagePartType.Png;
    }  else
    {
       return ImagePartType.Pcx;
    }
}

然后在这里为图像部分生成内容

private static void AddImagetoBody(WordprocessingDocument wordDoc,string relationshipId,int imageIndex,string fileName)
{
    // Define the reference of the image.
    var element =
         new Drawing(
             new D.Wordprocessing.Inline(
                 new D.Wordprocessing.Extent() { Cx = 500000L,Cy = 502000L },new D.Wordprocessing.EffectExtent()
                 {
                     LeftEdge = 0L,TopEdge = 0L,RightEdge = 0L,BottomEdge = 0L
                 },new D.Wordprocessing.DocProperties()
                 {
                     Id = UInt32Value.FromUInt32((uint)(imageIndex * 50)),Name = $"{imageIndex}-{fileName}"
                 },new D.Wordprocessing.NonVisualGraphicFrameDrawingProperties(
                    new D.GraphicFrameLocks() { NoChangeAspect = true }),new D.Graphic(
                     new D.GraphicData(
                        new D.Pictures.Picture(
                            new D.Pictures.NonVisualPictureProperties(
                                new D.Pictures.NonVisualDrawingProperties()
                                {
                                    Id = UInt32Value.FromUInt32((uint)(imageIndex * 100)),Name = fileName
                                 },new D.Pictures.NonVisualPictureDrawingProperties()),new D.Pictures.BlipFill(
                                new D.Blip(
                                    new D.BlipExtensionList(
                                         new D.BlipExtension()
                                            {
                                                Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}"
                                             }
                                     )
                                 )
                                 {
                                    Embed = relationshipId,CompressionState =
                                    D.BlipCompressionValues.Print
                                 },new D.Stretch(
                                    new D.FillRectangle())),new D.Pictures.ShapeProperties(
                                new D.Transform2D(
                                    new D.Offset() { X = 0L,Y = 0L },new D.Extents() { Cx = 500000L,Cy = 502000L }),new D.PresetGeometry(
                                    new D.AdjustValueList()
                                 )
                                 { Preset = D.ShapeTypeValues.Rectangle }))
                    )
                    { Uri = "https://schemas.openxmlformats.org/drawingml/2006/picture" })
            )
            {
                distanceFromTop = (UInt32Value)0U,distanceFromBottom = (UInt32Value)0U,distanceFromLeft = (UInt32Value)0U,distanceFromright = (UInt32Value)0U,EditId = "50D07946"
            });

    // Append the reference to body,the element should be in a Run.
    wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element)));
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...