我在創建圖像時遇到了一些OPEN XML問題。Word Open XML:插入超過3張圖像時文件損壞
我用一些圖像替換文檔中的某些文本。 如果我替換1到3張圖像,保存的文件是完美的:圖像顯示,一切看起來不錯。
如果我替換3個以上的圖像,文件結果損壞,並且在Microsoft Word「恢復」之後它也是完美的。
我試圖移動圖像,改變順序,改變圖像等,但是當我插入3插入的圖像時,文檔似乎被破壞。
這裏是我稱之爲:
private static void ReplaceTextWithImage(string find, string filepath, Bitmap bitmap, int incremental)
{
using (WordprocessingDocument doc = WordprocessingDocument.Open(filepath, true))
{
MainDocumentPart mainPart = doc.MainDocumentPart;
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
using (var ms = new MemoryStream())
{
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
ms.Position = 0;
imagePart.FeedData(ms);
}
var relID = mainPart.GetIdOfPart(imagePart);
var element =
new Drawing(
new DW.Inline(
new DW.Extent() { Cx = 990000L * (long)(7.13/1.08), Cy = 792000L * (long)(8.51/0.87) },
new DW.EffectExtent()
{
LeftEdge = 0L,
TopEdge = 0L,
RightEdge = 0L,
BottomEdge = 0L
},
new DW.DocProperties()
{
Id = (UInt32Value)1U,
Name = "img" + incremental
},
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 = "img" + incremental + ".jpg"
},
new PIC.NonVisualPictureDrawingProperties()),
new PIC.BlipFill(
new A.Blip(
new A.BlipExtensionList(
new A.BlipExtension()
{
Uri = Guid.NewGuid().ToString()
})
)
{
Embed = relID,
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 * (long)(7.13/1.08), Cy = 792000L * (long)(8.51/0.87) }),
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"
});
var paragraphs = doc.MainDocumentPart.Document.Body.ChildElements.First(x => x.OuterXml.Contains(find));
doc.MainDocumentPart.Document.Body.InsertAfter(new Paragraph(new Run(element)), paragraphs);
doc.MainDocumentPart.Document.Body.RemoveChild(paragraphs);
doc.Close();
}
}
正如你可以看到它是非常tipical方法,我已經試圖改變一些ID等,但都沒有成功!