我试图生成一个DocX文档,在文档的中心有一个图像,但我已经尝试了几件事,但没有任何工作。图像显示在左上角。函数addImageToBody来自MS网站(http://msdn.microsoft.com/en-us/library/office/bb497430(v=office.15).aspx)。我尝试使用HorizontalPosition类(http://msdn.microsoft.com/en-us/library/documentformat.openxml.drawing.wordprocessing.horizontalposition(v=office.14).aspx),但它对我不起作用。
添加图像和调用函数:
MainDocumentPart mainPart = document.MainDocumentPart;
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Png);
using (FileStream stream = new FileStream(@"C:...\Logo.png", FileMode.Open))
{
imagePart.FeedData(stream);
}
AddImageToBody(document, mainPart.GetIdOfPart(imagePart));
和功能:
private static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId)
{
int defX = 854;
int defY = 350;
int size = 3000;
// Define the reference of the image.
var element =
new DocumentFormat.OpenXml.Wordprocessing.Drawing(
new DW.Inline(
new DW.Extent() { Cx = defX * size, Cy = defY * size },
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 = "New Bitmap Image.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 = 1000L, Y = 500L, },
new A.Extents() { Cx = defX * size, Cy = defY * size }),
new A.PresetGeometry(
new A.AdjustValueList()
) { Preset = A.ShapeTypeValues.Rectangle }))
) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
)
{
DistanceFromTop = (UInt32Value)999999,
DistanceFromBottom = (UInt32Value)10000,
DistanceFromLeft = (UInt32Value)10000,
DistanceFromRight = (UInt32Value)10000,
EditId = "50D07946"
});
// Append the reference to body, the element should be in a Run.
wordDoc.MainDocumentPart.Document.Body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(element)));
}
1条答案
按热度按时间c9x0cxw01#
您需要将包含图像的段落居中。你可以使用段落属性(代码的最后一行)来实现: