Reputation: 1
I'm basically trying to horizontally center image relative to the page and vertically bottom align it again relative to the page. The image is in the footer. It appears, the width, height, etc... are all okay. Thanks in advance!
private static void AddImageToFooter(FooterPart footerPart, string imagePath)
{
ImagePart imagePart = footerPart.AddImagePart(ImagePartType.Png);
using (FileStream stream = new FileStream(imagePath, FileMode.Open))
{
imagePart.FeedData(stream);
}
string relationshipId = footerPart.GetIdOfPart(imagePart);
int imageWidthPx = 795;
int imageHeightPx = 137;
long imageWidthEmus = imageWidthPx * 9525;
long imageHeightEmus = imageHeightPx * 9525;
Drawing imageElement = new Drawing(
new DW.Inline(
new DW.Extent() { Cx = imageWidthEmus, Cy = imageHeightEmus },
new DW.EffectExtent() { LeftEdge = 0, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L },
new DW.HorizontalAlignment() { },
new DW.VerticalAlignment() { },
new DW.DocProperties() { Id = (UInt32Value)1U, Name = "Picture" },
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 Image" },
new PIC.NonVisualPictureDrawingProperties()),
new PIC.BlipFill(
new A.Blip() { Embed = relationshipId },
new A.Stretch(new A.FillRectangle())),
new PIC.ShapeProperties(
new A.Transform2D(
new A.Offset() { X = 0L, Y = 0L },
new A.Extents() { Cx = imageWidthEmus, Cy = imageHeightEmus }),
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" }
);
Paragraph paragraph = new Paragraph(new Run(imageElement));
footerPart.Footer.Append(paragraph);
footerPart.Footer.Save();
}
I've tried several things like Anchor(), but this for some reason makes it so my Word document will not open, I'm assuming due to it not being supported or I'm just doing it wrong, I'll provide a snippet of what I tried previously:
long horizontalPositionEmus = (totalPageWidthEmus - imageWidthEmus) / 2; // Center horizontally
long verticalPositionEmus = totalPageHeightEmus - imageHeightEmus;
Drawing imageElement = new Drawing(
new DW.Anchor(
new DW.SimplePosition() { X = horizontalPositionEmus, Y = verticalPositionEmus },
new DW.HorizontalPosition() { RelativeFrom = DW.HorizontalRelativePositionValues.Page },
new DW.VerticalPosition() { RelativeFrom = DW.VerticalRelativePositionValues.Page },
new DW.Extent() { Cx = imageWidthEmus, Cy = imageHeightEmus },
// Other properties for wrapping, effects, etc.
// ...
Drawing imageElement = new Drawing(
new DW.Anchor(
new DW.SimplePosition() { X = 0L, Y = 0L },
new DW.HorizontalPosition() { RelativeFrom = DW.HorizontalRelativePositionValues.Page },
new DW.VerticalPosition() { RelativeFrom = DW.VerticalRelativePositionValues.Page },
new DW.Extent() { Cx = imageWidthEmus, Cy = imageHeightEmus },
new DW.EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L },
new DW.WrapSquare(),
// ...
And this simply doesn't work or I'm just missing something:
Drawing imageElement = new Drawing(
new DW.Inline(
new DW.Extent() { Cx = imageWidthEmus, Cy = imageHeightEmus },
new DW.EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L },
new DW.DocProperties() { Id = (UInt32Value)1U, Name = "Picture" },
new DW.NonVisualGraphicFrameDrawingProperties(new A.GraphicFrameLocks() { NoChangeAspect = true }),
Upvotes: 0
Views: 87
Reputation: 11104
If you're willing to give OfficeIMO a go, playing with images is quite simple. It takes away the pain of dealing with direct openxml.
internal static void Example_AddingImagesInline(string folderPath, bool openWord)
{
Console.WriteLine("[*] Creating standard document with inline images");
string filePath = System.IO.Path.Combine(folderPath, "DocumentWithInlineImages2.docx");
string imagePaths = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Images");
using (WordDocument document = WordDocument.Create(filePath))
{
var file = System.IO.Path.Combine(imagePaths, "PrzemyslawKlysAndKulkozaurr.jpg");
var paragraph = document.AddParagraph();
var pargraphWithImage = paragraph.AddImage(file, 100, 100, WrapTextImage.InLineWithText, "Przemek and Kulek on an image");
// Console.WriteLine("Image is inline: " + pargraphWithImage.Image.Rotation);
//pargraphWithImage.Image.VerticalFlip = false;
//pargraphWithImage.Image.HorizontalFlip = false;
//pargraphWithImage.Image.Rotation = 190;
//pargraphWithImage.Image.Shape = ShapeTypeValues.Cloud;
//pargraphWithImage.Image.Description = "Other description";
var pargraphWithImage1 = paragraph.AddImage(file, 100, 100, WrapTextImage.BehindText, "Przemek and Kulek on an image");
//pargraphWithImage1.Image.WrapImage = WrapImageText.BehindText;
//Console.WriteLine("Image is inline: " + pargraphWithImage.Image.Rotation);
document.Save(openWord);
}
}
or
internal static void Example_AddingFixedImages(string folderPath, bool openWord)
{
Console.WriteLine("[*] Creating standard document with an Image in a fixed position.");
var filePath = System.IO.Path.Combine(folderPath, "BasicDocumentWithImages.docx");
var imagePaths = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Images");
using var document = WordDocument.Create(filePath);
document.BuiltinDocumentProperties.Title = "Fixed image example";
document.BuiltinDocumentProperties.Creator = "example";
var paragraph1 = document.AddParagraph("First Paragraph");
const string fileNameImage = "Kulek.jpg";
var filePathImage = System.IO.Path.Combine(imagePaths, fileNameImage);
// Add an image with a fixed position to paragraph. First we add the image, then we will
// edit the position properties.
//
// Note: The image MUST be constructed with a WrapTextImage property that is NOT inline. Assigning
// the WrapTextImage property later was not available at the time of making this example.
paragraph1.AddImage(filePathImage, 100, 100, WrapTextImage.Square);
Console.WriteLine("PRE position edit.");
// Before editing, we can assess the RelativeFrom and PositionOffset properties of the image.
DocumentFormat.OpenXml.EnumValue<HorizontalRelativePositionValues> hRelativeFrom;
string hOffset, vOffset;
DocumentFormat.OpenXml.EnumValue<VerticalRelativePositionValues> vRelativeFrom;
checkImageProps(paragraph1);
// Begin editing the fixed position properties of the image. You may edit both, however it
// is not necessary.
// Note that the units for the PositionOffset are taken in EMU's. This is a conversion
// for an offset of 1/4 inch.
const double emusPerInch = 914400.0;
double offsetInches = 0.25;
// Non integer values will cause the document properties to be corrupted, cast
// to an int for avoiding this.
int offsetEmus = (int)(offsetInches * emusPerInch);
// Edit the horizontal relative from property of the image. Both
// the RelativeFrom property and PositionOffset are required.
HorizontalPosition horizontalPosition1 = new HorizontalPosition()
{
RelativeFrom = HorizontalRelativePositionValues.Page,
PositionOffset = new PositionOffset { Text = $"{offsetEmus}" }
};
paragraph1.Image.horizontalPosition = horizontalPosition1;
// Edit the vertical relative from property of the image. Both
// the RelativeFrom property and PositionOffset are required.
VerticalPosition verticalPosition1 = new VerticalPosition()
{
RelativeFrom = VerticalRelativePositionValues.Page,
PositionOffset = new PositionOffset { Text = $"{offsetEmus}" }
};
paragraph1.Image.verticalPosition = verticalPosition1;
Console.WriteLine("POST position edit.");
// After editing, lets reassess the properties.
checkImageProps(paragraph1);
// This will put the image in the upper top left corner of the document.
document.Save(openWord);
static void checkImageProps(WordParagraph paragraph1)
{
var hRelativeFrom = paragraph1.Image.horizontalPosition.RelativeFrom;
var hOffset = paragraph1.Image.horizontalPosition.PositionOffset.Text;
var vRelativeFrom = paragraph1.Image.verticalPosition.RelativeFrom;
var vOffset = paragraph1.Image.verticalPosition.PositionOffset.Text;
Console.WriteLine($"Horizontal RelativeFrom type: {hRelativeFrom.ToString()}");
Console.WriteLine($"Horizontal PositionOffset value: {hOffset.ToString()}");
Console.WriteLine($"Vertical RelativeFrom type: {vRelativeFrom.ToString()}");
Console.WriteLine($"Vertical PositionOffset value: {vOffset.ToString()}");
}
}
There are multiple examples:
It's still work in progress so optimizations can be made so the dealing with some images is even simpler.
Upvotes: 0