dotnet / Open-XML-SDK

Open XML SDK by Microsoft
https://www.nuget.org/packages/DocumentFormat.OpenXml/
MIT License
3.99k stars 544 forks source link

AddImagePart adds Media folder and images to Root instead of the Word sub folder within the document package #1730

Open oaktechnology opened 3 months ago

oaktechnology commented 3 months ago

Describe the bug We have been trying to work out why when some 3rd party systems convert a Word document that we have generated using the Open XML SDK that images are not visible and came across other people with the same issue.

We have done quite a bit of investigation and research and it appears to be down to the SDK putting the images and relationships in a media folder in the root of the package, rather than in the word sub folder.

If one of these documents is editing in Word then it detects that this is wrong and moves the images and then the document is fine again. Someone posted on the internet about this 3.5 years ago and have a work-around which was to insert the images manually and avoid the AddImagePart function but his sample code no longer works in the new versions and it seems to make more sense to resolve the issue at source rather than trying to fudge a way round it.

sample code that shows the behaviour: ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Png);
imagePart.FeedData(imageStream);

I also tried using an embedded object to see if I could make that work in the meantime and although it didn't do what I wanted it does put the EmbeddedObjects in the correct WORD sub folder so the functionality appears to be inconsistent: var imagePart = mainPart.AddEmbeddedObjectPart(ImagePartType.Png); imagePart.FeedData(imageStream);

Screenshots Word generated document has created the media folder under the word folder: StandardWord

OpenXMLSDK generated document has created the media folder in root: OpenXMLGenerated

To Reproduce Steps to reproduce the behavior: ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Png);
imagePart.FeedData(imageStream);

Observed behavior The image uploads to the \media folder within the package.

Expected behavior The image should upload to the \word\media folder within the package.

Additional context If the AddImagePart function could be changed to upload media files into the word sub folder then that would be ideal but if that proposes a problem then having an additional parameter would be a good alternative solution to get the desired result.

Desktop (please complete the following information) OS: Docker mcr.microsoft.com/dotnet/aspnet:8.0 Office version [e.g. 16.0.15427.20178] .NET Target: .net8 DocumentFormat.OpenXml Version: 3.0.2