问题描述
publicstaticvoidInsertAPicture(stringdocument,stringfileName){using(WordprocessingDocumentwordprocessingDocument=WordprocessingDocument.Open(document,true)){MainDocumentPartmainPart=wordprocessingDocument.MainDocumentPart;ImagePartimagePart=mainPart.AddImagePart(ImagePartType.Jpeg);using(FileStreamstream=newFileStream(fileName,FileMode.Open)){imagePart.FeedData(stream);}AddImageToBody(wordprocessingDocument,mainPart.GetIdOfPart(imagePart));}}privatestaticvoidAddImageToBody(WordprocessingDocumentwordDoc,stringrelationshipId){//Definethereferenceoftheimage.varelement=newdrawing(newDW.Inline(newDW.Extent(){Cx=990000L,Cy=792000L},newDW.EffectExtent(){LeftEdge=0L,TopEdge=0L,RightEdge=0L,BottomEdge=0L},newDW.DocProperties(){Id=(UInt32Value)1U,Name="Picture1"},newDW.NonVisualGraphicFrameDrawingProperties(newA.GraphicFrameLocks(){NoChangeAspect=true}),newA.Graphic(newA.GraphicData(newPIC.Picture(newPIC.NonVisualPictureProperties(newPIC.NonVisualDrawingProperties(){Id=(UInt32Value)0U,Name="NewBitmapImage.jpg"},newPIC.NonVisualPictureDrawingProperties()),newPIC.BlipFill(newA.Blip(newA.BlipExtensionList(newA.BlipExtension(){Uri="{28A0092B-C50C-407E-A947-70E740481C1C}"})){Embed=relationshipId,CompressionState=A.BlipCompressionValues.Print},newA.Stretch(newA.FillRectangle())),newPIC.ShapeProperties(newA.Transform2D(newA.Offset(){X=0L,Y=0L},newA.Extents(){Cx=990000L,Cy=792000L}),newA.PresetGeometry(newA.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"});//Appendthereferencetobody,theelementshouldbeinaRun.wordDoc.MainDocumentPart.Document.Body.AppendChild(newParagraph(newRun(element)));}privatevoidbutton1_Click(objectsender,EventArgse){stringdocument=@"f:实验.docx";stringfilename=@"f:实验.jpg";InsertAPicture(document,filename);MessageBox.Show("运行完毕");}以上代码基本是照抄msdn上的帮助的,为什么我通过此方式向word插入图片后,word打开出现错误呢?请高手们赐教!
解决方案
解决方案二:
代码太多没仔细看,是不是对word版本或文字编码格式有要求?或者是图片格式有限制?你抄代码时有现成的demo吗,先跑一遍