Open XML SDK - 在Sharepoint文档中插入图片

时间:2013-12-12 12:14:43

标签: c# image sharepoint openxml-sdk

我在Sharepoint解决方案中使用open xml sdk 2.0时遇到了这个问题。我的目标是使用图像的网址为我的用户插入列表中的模板文档添加图像,文档末尾的附件准确但总是文件结束损坏,当恢复时,图片就是没有显示。

我将发布我正在使用的代码:

        public static String teste()
    {
        //Url image for test
        string fileName = @"http://upload.wikimedia.org/wikipedia/commons/2/2a/Junonia_lemonias_DSF_upper_by_Kadavoor.JPG";
        return InsertAPicture(fileName);
    }

public static String InsertAPicture(string fileName)
    {

        SPWeb web = SPContext.Current.Web;
        web.AllowUnsafeUpdates = true;
        SPList list = web.Lists["Documentos Compartilhados"]; //I'm using Portuguese Sharepoint
        SPListItem item = list.GetItemById(5); //For test only
        byte[] byteArray = item.File.OpenBinary();
        using (MemoryStream memStr = new MemoryStream())
        {
            memStr.Write(byteArray, 0, byteArray.Length);


            using (WordprocessingDocument doc = WordprocessingDocument.Open(memStr, true))
            {
                MainDocumentPart mainPart = doc.MainDocumentPart;

                ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);

                WebClient myWebClient = new WebClient();
                byte[] myDataBuffer = myWebClient.DownloadData(fileName);

                using (MemoryStream image = new MemoryStream())
                {
                    image.Write(myDataBuffer, 0, myDataBuffer.Length);

                    imagePart.FeedData(image);
                }

                AddImageToBody(doc, mainPart.GetIdOfPart(imagePart));

                OpenXmlValidator validator = new OpenXmlValidator();
                var errors = validator.Validate(doc);
                Boolean valido = true;
                String s = "";
                foreach (ValidationErrorInfo error in errors)
                {
                    s += error.Description + "    ";
                    valido = false;
                } //Just checking for erros, the code it's not returing any

                if (valido)
                {
                    doc.MainDocumentPart.Document.Save();

                    string linkFileName = item.File.Item["LinkFilename"] as string;
                    item.File.ParentFolder.Files.Add(linkFileName, memStr, true);

                    return "";
                }
                else {
                    return s;
                }
            }
        }
    }

private static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId)
    {
        var element =
                    new Drawing(
                        new DW.Inline(
                            new DW.Extent() { Cx = 990000L, Cy = 792000L },
                            new DW.EffectExtent()
                            {
                                LeftEdge = 0L,
                                TopEdge = 0L,
                                RightEdge = 0L,
                                BottomEdge = 0L
                            },
                            new DW.DocProperties()
                            {
                                Id = (UInt32Value)1U,
                                Name = "Picture 1"
                            },
                            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 = "Pic.jpg"
                                            },
                                            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 = 990000L, Cy = 792000L }),
                                            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
                        });

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

有人对我做错了吗?

2 个答案:

答案 0 :(得分:0)

创建图像流后,它的数据指针显示在流的末尾,导致不向imagePart提供任何数据。将数据指针移动到流的开头

using (MemoryStream image = new MemoryStream())
{
    image.Write(myDataBuffer, 0, myDataBuffer.Length);
    image.Position = 0;  //<----
    imagePart.FeedData(image);
}

答案 1 :(得分:0)

首先,考虑到您想从文档库中获取图像,可以将列表项文件作为流打开

protected ClientResult<Stream> OpenFileFromListItemAsStream(ClientContext context, string libraryTitle, string filename)
    {
        //source list and list item
        var sourceList = context.Web.Lists.GetByTitle(libraryTitle);
        var sourceListItems = sourceList.GetItems(new CamlQuery
        {
            ViewXml = "<View><Query><Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='Text'>" + filename + "</Value></Eq></Where></Query></</View>"
        });
        context.Load(sourceListItems);
        context.ExecuteQuery();

        ListItem sourceListItem = null;
        if (sourceListItems != null && sourceListItems.Count() > 0)
            sourceListItem = sourceListItems.FirstOrDefault();

        var fileStream = sourceListItem.File.OpenBinaryStream();
        context.Load(sourceListItem);
        context.Load(sourceListItem.File);
        context.ExecuteQuery();

        return fileStream;
    }

然后创建一个内存流并将位置设置为0

var imageStream = OpenFileFromListItemAsStream(imageContext, imageEntity.LibraryTitle, imageEntity.Filename);
                                    using (MemoryStream memStream = new MemoryStream())
                                    {
                                        imageStream.Value.CopyTo(memStream);
                                        memStream.Position = 0;
                                        imagePart.FeedData(memStream);
                                    }

最后...

AddImageToBody(doc, mainPart.GetIdOfPart(imagePart));