Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions .github/workflows/publish_nuget.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,17 @@
runs-on: ubuntu-latest

steps:
# validate the input.version as Github do not yet support regex validation
- name: Validate version input
run: |
REGEXP="^[1-9]{1,2}.[0-9]+.[0-9]+(-beta\d+)?$"
if [[ ! "$UNTRUSTED_INPUT" =~ $REGEXP ]]; then
echo "::error:: Invalid version format"
exit 1
fi
env:
UNTRUSTED_INPUT: ${{ github.event.inputs.version }}

- uses: actions/checkout@v6

# Only validate tag is on master for auto-triggered runs
Expand All @@ -57,14 +68,16 @@
- name: Build
run: |
dotnet build src/Html2OpenXml/HtmlToOpenXml.csproj \
--configuration Release /p:SourceRevisionId=${{ github.sha }}
--configuration Release /p:SourceRevisionId=${{ github.sha }} \
/p:ContinuousIntegrationBuild=true /p:Deterministic=true \

- name: Pack NuGet Package
run: |
dotnet pack src/Html2OpenXml/HtmlToOpenXml.csproj \
--configuration Release \
--output ./nupkg \
-- /p:PackageVersion=${{ inputs.version }}
/p:PackageVersion=${{ inputs.version }}

Check failure on line 79 in .github/workflows/publish_nuget.yml

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

inputs.version is vulnerable to script injection: values of inputs are provided by whoever triggers the workflow. Change this workflow to not use user-controlled data directly in a run block, for example by assigning this expression to an environment variable.

See more on https://sonarcloud.io/project/issues?id=onizet_html2openxml&issues=AZ-BdJ7qPDIr-DRZvh6z&open=AZ-BdJ7qPDIr-DRZvh6z&pullRequest=236

- name: Verify Package Created
run: |
if [ ! -f ./nupkg/*.nupkg ]; then
Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Changelog

## 3.5.0

- Support css margin/padding inline/block
- Bump AngleSharp to 1.5 due to CVE

## 3.4.0

- Numbering list now support `list-style-type: dash`
Expand Down
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Version>3.4.1</Version>
<Version>3.5.0</Version>
</PropertyGroup>

<PropertyGroup>
Expand Down
18 changes: 16 additions & 2 deletions src/Html2OpenXml/Collections/HtmlAttributeCollection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -171,24 +171,38 @@
/// If a side has been specified individually, it will override the grouped definition.
/// </summary>
/// <returns>If the attribute is misformed, the <see cref="Margin.IsValid"/> property is set to false.</returns>
public Margin GetMargin(string name)

Check failure on line 174 in src/Html2OpenXml/Collections/HtmlAttributeCollection.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this method to reduce its Cognitive Complexity from 16 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=onizet_html2openxml&issues=AZ-BdJ1zPDIr-DRZvh6y&open=AZ-BdJ1zPDIr-DRZvh6y&pullRequest=236
{
Margin margin = Margin.Empty;
// shortcut to avoid resolving each individual side when we know this collection is empty
if (IsEmpty) return margin;

Unit u;

if (attributes.TryGetValue(name, out var range))
margin = Margin.Parse(rawValue.AsSpan().Slice(range));

Unit u;
if (attributes.TryGetValue(name + "-inline", out range))
{
u = Unit.Parse(rawValue.AsSpan().Slice(range));
if (u.IsValid) margin.Left = margin.Right = u;
}
if (attributes.TryGetValue(name + "-block", out range))
{
u = Unit.Parse(rawValue.AsSpan().Slice(range));
if (u.IsValid) margin.Top = margin.Bottom = u;
}

u = GetUnit(name + "-top", UnitMetric.Pixel);
if (!u.IsValid) u = GetUnit(name + "-block-start");
if (u.IsValid) margin.Top = u;
u = GetUnit(name + "-right", UnitMetric.Pixel);
if (!u.IsValid) u = GetUnit(name + "-inline-end");
if (u.IsValid) margin.Right = u;
u = GetUnit(name + "-bottom", UnitMetric.Pixel);
if (!u.IsValid) u = GetUnit(name + "-block-end");
if (u.IsValid) margin.Bottom = u;
u = GetUnit(name + "-left", UnitMetric.Pixel);
if (!u.IsValid) u = GetUnit(name + "-inline-start");
if (u.IsValid) margin.Left = u;

return margin;
Expand Down
2 changes: 1 addition & 1 deletion src/Html2OpenXml/Expressions/BlockElementExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ internal static IEnumerable<OpenXmlElement> ComposeChildren(ParsingContext conte
foreach (var element in expression.Interpret(context))
{
context.CascadeStyles(element);
if (element is Run r || element is Hyperlink)
if (element is Run || element is Hyperlink)
{
runs.Add(element);
continue;
Expand Down
7 changes: 2 additions & 5 deletions src/Html2OpenXml/Expressions/BodyExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ sealed class BodyExpression(IHtmlElement node, ParagraphStyleId? defaultStyle)
private const uint PortraitPageWidth = 11906U;
private const uint PortraitPageHeight = 16838U;
private bool shouldRegisterTopBookmark;
private ParsingContext? overridenContext;


public override IEnumerable<OpenXmlElement> Interpret(ParsingContext context)
{
MarkAllBookmarks();
Expand Down Expand Up @@ -89,9 +89,6 @@ protected override void ComposeStyles(ParsingContext context)
SectionProperties validSectionProp = ChangePageOrientation(orientation);
pageSize?.Remove();
sectionProperties.PrependChild(validSectionProp.GetFirstChild<PageSize>()!.CloneNode(true));

overridenContext = context.CreateChild(this);
overridenContext.IsLandscape = orientation == PageOrientationValues.Landscape;
}
}
}
Expand Down
4 changes: 1 addition & 3 deletions src/Html2OpenXml/Expressions/HtmlDomExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ private static Dictionary<string, Func<IElement, HtmlDomExpression>> InitKnownTa
{
// A complete list of HTML tags can be found here: http://www.w3schools.com/tags/default.asp

var knownTags = new Dictionary<string, Func<IElement, HtmlDomExpression>>(StringComparer.InvariantCultureIgnoreCase) {
return new Dictionary<string, Func<IElement, HtmlDomExpression>>(StringComparer.InvariantCultureIgnoreCase) {
{ TagNames.A, el => new HyperlinkExpression((IHtmlAnchorElement) el) },
{ TagNames.Abbr, el => new AbbreviationExpression((IHtmlElement) el) },
{ "acronym", el => new AbbreviationExpression((IHtmlElement) el) },
Expand Down Expand Up @@ -82,8 +82,6 @@ private static Dictionary<string, Func<IElement, HtmlDomExpression>> InitKnownTa
{ TagNames.Ul, el => new ListExpression((IHtmlElement) el) },
{ TagNames.Var, el => new PhrasingElementExpression((IHtmlElement) el) }
};

return knownTags;
}

/// <summary>
Expand Down
40 changes: 21 additions & 19 deletions src/Html2OpenXml/Expressions/Image/ImageExpressionBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,32 +106,34 @@ internal static (uint imageObjId, uint drawingObjId) IncrementDrawingObjId(Parsi
imageObjId ??= 1;

var mainPart = context.MainPart;
foreach (var part in new[] {
foreach (var part in new[] {
mainPart.Document!.Body!.Descendants<Drawing>(),
mainPart.HeaderParts.Where(f => f.Header != null).SelectMany(f => f.Header!.Descendants<Drawing>()),
mainPart.FooterParts.Where(f => f.Footer != null).SelectMany(f => f.Footer!.Descendants<Drawing>())
})
foreach (Drawing d in part)
{
wp.DocProperties? docProperties = null;
pic.NonVisualPictureProperties? nvPr = null;

if (d.Anchor != null)
{
docProperties = d.Anchor.GetFirstChild<wp.DocProperties>();
nvPr = d.Anchor.GetFirstChild<a.Graphic>()?.GraphicData?.GetFirstChild<pic.Picture>()?.GetFirstChild<pic.NonVisualPictureProperties>();
}
else if (d.Inline != null)
foreach (Drawing d in part)
{
docProperties = d.Inline!.DocProperties;
nvPr = d.Inline!.Graphic?.GraphicData?.GetFirstChild<pic.NonVisualPictureProperties>();
wp.DocProperties? docProperties = null;
pic.NonVisualPictureProperties? nvPr = null;

if (d.Anchor != null)
{
docProperties = d.Anchor.GetFirstChild<wp.DocProperties>();
nvPr = d.Anchor.GetFirstChild<a.Graphic>()?.GraphicData?.GetFirstChild<pic.Picture>()?.GetFirstChild<pic.NonVisualPictureProperties>();
}
else if (d.Inline != null)
{
docProperties = d.Inline!.DocProperties;
nvPr = d.Inline!.Graphic?.GraphicData?.GetFirstChild<pic.NonVisualPictureProperties>();
}

if (docProperties?.Id != null && docProperties.Id.Value > drawingObjId)
drawingObjId = docProperties.Id.Value;

if (nvPr != null && nvPr.NonVisualDrawingProperties?.Id?.Value > imageObjId)
imageObjId = nvPr.NonVisualDrawingProperties.Id;
}

if (docProperties?.Id != null && docProperties.Id.Value > drawingObjId)
drawingObjId = docProperties.Id.Value;

if (nvPr != null && nvPr.NonVisualDrawingProperties?.Id?.Value > imageObjId)
imageObjId = nvPr.NonVisualDrawingProperties.Id;
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/Html2OpenXml/Expressions/Numbering/ListExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ private ListContext ConcretiseInstance(ParsingContext context, int abstractNumId
overrideLevelIndex = currentLevel;
listContext = new ListContext(listStyle, abstractNumId, instanceId.Value, currentLevel + 1, dir);
}
else if (!instanceId.HasValue || context.Converter.ContinueNumbering == false)
else if (!instanceId.HasValue || !context.Converter.ContinueNumbering)
{
// create a new instance of that list template
instanceId = IncrementInstanceId(context, abstractNumId, isReusable: context.Converter.ContinueNumbering);
Expand Down
17 changes: 3 additions & 14 deletions src/Html2OpenXml/Expressions/Numbering/NumberingExpressionBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,6 @@ private void InitNumberingIds(ParsingContext context)

knownAbsNumIds = [];
knownInstanceIds = [];
int absNumIdRef = 0;
NumberingDefinitionsPart numberingPart = context.MainPart.NumberingDefinitionsPart
?? context.MainPart.AddNewPart<NumberingDefinitionsPart>();

Expand All @@ -201,21 +200,11 @@ private void InitNumberingIds(ParsingContext context)
}

var numbering = numberingPart.Numbering!;

// The absNumIdRef Id is a required field and should be unique. We will loop through the existing Numbering definition
// to retrieve the highest Id and reconstruct our own list definition template.
foreach (var abs in numbering.Elements<AbstractNum>())
{
if (abs.AbstractNumberId != null && abs.AbstractNumberId > absNumIdRef)
absNumIdRef = abs.AbstractNumberId;
}
absNumIdRef++;

IEnumerable<AbstractNum> existingAbstractNums = numbering.ChildElements
.Where(e => e != null && e is AbstractNum).Cast<AbstractNum>();
.OfType<AbstractNum>();

knownAbsNumIds = existingAbstractNums
.Where(a => a.AbstractNumDefinitionName != null && a.AbstractNumDefinitionName.Val != null)
.Where(a => a.AbstractNumDefinitionName?.Val != null)
.ToDictionary(a => a.AbstractNumDefinitionName!.Val!.Value!, a => a.AbstractNumberId!.Value);

foreach (NumberingInstance inst in numbering.Elements<NumberingInstance>())
Expand All @@ -239,7 +228,7 @@ private AbstractNum CreateCustomBulletAbstractNum(string customSymbol)
AbstractNumDefinitionName = new() { Val = customSymbol },
MultiLevelType = new() { Val = MultiLevelValues.HybridMultilevel }
};

for (var lvlIndex = 0; lvlIndex <= MaxLevel; lvlIndex++)
{
abstractNum.Append(new Level {
Expand Down
2 changes: 1 addition & 1 deletion src/Html2OpenXml/Expressions/Table/TableExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ private static int GuessColumnsCount(IHtmlTableElement tableNode)

for(int i = 0; i < rows.Length; i++)
{
foreach (var cell in rowNodes.ElementAt(i).Cells)
foreach (var cell in rowNodes[i].Cells)
{
var colSpan = Math.Max(1, cell.ColumnSpan);
for (int r = i; r < i + cell.RowSpan; r++)
Expand Down
9 changes: 0 additions & 9 deletions src/Html2OpenXml/HtmlConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,6 @@ public partial class HtmlConverter
private readonly IWebRequest webRequester;


/// <summary>
/// Constructor.
/// </summary>
/// <param name="mainPart">The mainDocumentPart of a document where to write the conversion to.</param>
/// <remarks>We preload some configuration from inside the document such as style, bookmarks,...</remarks>
public HtmlConverter(MainDocumentPart mainPart) : this(mainPart, null)
{
}

/// <summary>
/// Constructor.
/// </summary>
Expand Down
13 changes: 3 additions & 10 deletions src/Html2OpenXml/HtmlToOpenXml.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@
<Description>A library to convert simple or advanced html to plain OpenXml document</Description>
<Authors>Olivier Nizet</Authors>
<RepositoryType>GIT</RepositoryType>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<DebugType>embedded</DebugType>
<NoWarn>$(NoWarn);CS8981</NoWarn>
</PropertyGroup>
<Import Project="..\..\build\SignAssembly.props" />
Expand All @@ -41,7 +39,7 @@
<ItemGroup>
<PackageReference Include="AngleSharp" Version="1.5.0" />
<PackageReference Include="DocumentFormat.OpenXml" Version="$(DocumentFormatOpenXmlPackageVersion)" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="10.0.300" PrivateAssets="all" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.0" />
</ItemGroup>

Expand All @@ -50,14 +48,9 @@
<Optimize>false</Optimize>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<DebugType>portable</DebugType>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<Deterministic>true</Deterministic>
</PropertyGroup>

<PropertyGroup Condition="'$(GITHUB_ACTIONS)' == 'true'">
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
</PropertyGroup>

</Project>
4 changes: 2 additions & 2 deletions src/Html2OpenXml/IO/ImageHeader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ private static FileType DetectFileType (SequentialBinaryReader reader)

private static Size DecodeBitmap(SequentialBinaryReader reader)
{
var magicNumber = reader.ReadUInt16();
var _ = reader.ReadUInt16();

// skip past the rest of the file header
reader.Skip(4 + 2 + 2 + 4);
Expand Down Expand Up @@ -200,7 +200,7 @@ private static Size DecodeGif(SequentialBinaryReader reader)
private static Size DecodeJfif(SequentialBinaryReader reader)
{
reader.IsBigEndian = true;
var magicNumber = reader.ReadUInt16(); // first two bytes should be JPEG magic number
var _ = reader.ReadUInt16(); // first two bytes should be JPEG magic number

do
{
Expand Down
Loading
Loading