Skip to content

Commit a290371

Browse files
committed
Prevent crash when header/footer is incomplete and parsing image #159
1 parent 438d34d commit a290371

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

src/Html2OpenXml/Expressions/Image/ImageExpressionBase.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,8 @@ internal static (uint imageObjId, uint drawingObjId) IncrementDrawingObjId(Parsi
8787

8888
foreach (var part in new[] {
8989
context.MainPart.Document.Body!.Descendants<Drawing>(),
90-
context.MainPart.HeaderParts.SelectMany(f => f.Header.Descendants<Drawing>()),
91-
context.MainPart.FooterParts.SelectMany(f => f.Footer.Descendants<Drawing>())
90+
context.MainPart.HeaderParts.Where(f => f.Header != null).SelectMany(f => f.Header.Descendants<Drawing>()),
91+
context.MainPart.FooterParts.Where(f => f.Footer != null).SelectMany(f => f.Footer.Descendants<Drawing>())
9292
})
9393
foreach (Drawing d in part)
9494
{

test/HtmlToOpenXml.Tests/ImgTests.cs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,24 @@ public async Task ImageIds_IsUniqueAcrossPackagingParts()
133133
"New image id is incremented considering existing images in header, body and footer");
134134
}
135135

136+
[GenericTestCase(typeof(HeaderPart), Description = "Incomplete header or footer definition must be skipped #159")]
137+
[GenericTestCase(typeof(FooterPart))]
138+
public void WithIncompleteHeader_ShouldNotThrow<T>() where T : OpenXmlPart, IFixedContentTypePart
139+
{
140+
using var generatedDocument = new MemoryStream();
141+
using (var buffer = ResourceHelper.GetStream("Resources.DocWithImgHeaderFooter.docx"))
142+
buffer.CopyTo(generatedDocument);
143+
144+
generatedDocument.Position = 0L;
145+
using WordprocessingDocument package = WordprocessingDocument.Open(generatedDocument, true);
146+
MainDocumentPart mainPart = package.MainDocumentPart!;
147+
mainPart.AddNewPart<T>(); // this code is incomplete as it's missing the header content
148+
149+
HtmlConverter converter = new(mainPart);
150+
Assert.DoesNotThrowAsync(async () =>
151+
await converter.ParseHtml("<img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==' width='42' height='42'>"));
152+
}
153+
136154
private Drawing AssertIsImg (OpenXmlCompositeElement element)
137155
{
138156
var run = element.GetFirstChild<Run>();

0 commit comments

Comments
 (0)