Skip to content

Commit 71ff822

Browse files
campersaukblok
andauthored
Use object for Top / Left / Bottom / Right in MarginOptions (#2788)
* Use object for Top / Left / Bottom / Right in MarginOptions This is similar to the object Width / Height in PdfOptions and all of them already got converted by ConvertPrintParameterToInches * Add back PdfOptionsShouldWorkWithMarginWithNoUnits test * Expand comment for PrimitiveTypeConverter * Turn test into unit test * bump System.Text.Json * chrome 129.0.6668.100 --------- Co-authored-by: Darío Kondratiuk <[email protected]>
1 parent 1b2dcca commit 71ff822

File tree

8 files changed

+134
-149
lines changed

8 files changed

+134
-149
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ await page.GoToAsync("http://www.google.com"); // In case of fonts being loaded
9090
await page.EvaluateExpressionHandleAsync("document.fonts.ready"); // Wait for fonts to be loaded. Omitting this might result in no text rendered in pdf.
9191
await page.PdfAsync(outputFile);
9292
```
93-
<sup><a href='https://github.com/hardkoded/puppeteer-sharp/blob/master/lib/PuppeteerSharp.Tests/PageTests/PdfTests.cs#L23-L33' title='Snippet source file'>snippet source</a> | <a href='#snippet-pdfasync_example' title='Start of snippet'>anchor</a></sup>
93+
<sup><a href='https://github.com/hardkoded/puppeteer-sharp/blob/master/lib/PuppeteerSharp.Tests/PageTests/PdfTests.cs#L24-L34' title='Snippet source file'>snippet source</a> | <a href='#snippet-pdfasync_example' title='Start of snippet'>anchor</a></sup>
9494
<!-- endSnippet -->
9595

9696
### Inject HTML

lib/PuppeteerSharp.Tests/PageTests/PdfTests.cs

+9-18
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using System.Text.Json;
44
using System.Threading.Tasks;
55
using NUnit.Framework;
6+
using PuppeteerSharp.Cdp;
67
using PuppeteerSharp.Media;
78
using PuppeteerSharp.Nunit;
89

@@ -127,6 +128,8 @@ public void PdfOptionsShouldBeSerializable()
127128
{
128129
var pdfOptions = new PdfOptions
129130
{
131+
Width = 100,
132+
Height = 100,
130133
Format = PaperFormat.A4,
131134
DisplayHeaderFooter = true,
132135
MarginOptions = new MarginOptions
@@ -145,25 +148,13 @@ public void PdfOptionsShouldBeSerializable()
145148
}
146149

147150
[Test]
148-
public void PdfOptionsShouldWorkWithMarginWithNoUnits()
151+
public void ConvertPrintParameterToInchesTests()
149152
{
150-
var pdfOptions = new PdfOptions
151-
{
152-
Format = PaperFormat.A4,
153-
DisplayHeaderFooter = true,
154-
MarginOptions = new MarginOptions
155-
{
156-
Top = "0",
157-
Right = "0",
158-
Bottom = "0",
159-
Left = "0"
160-
},
161-
FooterTemplate = "<div id=\"footer-template\" style=\"font-size:10px !important; color:#808080; padding-left:10px\">- <span class=\"pageNumber\"></span> - </div>"
162-
};
163-
164-
var serialized = JsonSerializer.Serialize(pdfOptions);
165-
var newPdfOptions = JsonSerializer.Deserialize<PdfOptions>(serialized);
166-
Assert.That(newPdfOptions, Is.EqualTo(pdfOptions));
153+
Assert.That(CdpPage.ConvertPrintParameterToInches("10"), Is.EqualTo(10m / 96));
154+
Assert.That(CdpPage.ConvertPrintParameterToInches("10px"), Is.EqualTo(10m / 96));
155+
Assert.That(CdpPage.ConvertPrintParameterToInches("0"), Is.EqualTo(0));
156+
Assert.That(CdpPage.ConvertPrintParameterToInches("0px"), Is.EqualTo(0));
157+
Assert.That(CdpPage.ConvertPrintParameterToInches("10in"), Is.EqualTo(10));
167158
}
168159
}
169160
}

lib/PuppeteerSharp/BrowserData/Chrome.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ public static class Chrome
1313
/// <summary>
1414
/// Default chrome build.
1515
/// </summary>
16-
public static string DefaultBuildId => "128.0.6613.119";
16+
public static string DefaultBuildId => "129.0.6668.100";
1717

1818
internal static async Task<string> ResolveBuildIdAsync(ChromeReleaseChannel channel)
1919
=> (await GetLastKnownGoodReleaseForChannel(channel).ConfigureAwait(false)).Version;

lib/PuppeteerSharp/Cdp/CdpPage.cs

+42-42
Original file line numberDiff line numberDiff line change
@@ -731,6 +731,48 @@ internal static async Task<Page> CreateAsync(
731731
}
732732
}
733733

734+
internal static decimal ConvertPrintParameterToInches(object parameter)
735+
{
736+
if (parameter == null)
737+
{
738+
return 0;
739+
}
740+
741+
decimal pixels;
742+
if (parameter is decimal or int)
743+
{
744+
pixels = Convert.ToDecimal(parameter, CultureInfo.CurrentCulture);
745+
}
746+
else
747+
{
748+
var text = parameter.ToString();
749+
var unit = text.Length > 2 ? text.Substring(text.Length - 2).ToLower(CultureInfo.CurrentCulture) : string.Empty;
750+
string valueText;
751+
if (GetPixels(unit) is { })
752+
{
753+
valueText = text.Substring(0, text.Length - 2);
754+
}
755+
else
756+
{
757+
// In case of unknown unit try to parse the whole parameter as number of pixels.
758+
// This is consistent with phantom's paperSize behavior.
759+
unit = "px";
760+
valueText = text;
761+
}
762+
763+
if (decimal.TryParse(valueText, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var number))
764+
{
765+
pixels = number * GetPixels(unit).Value;
766+
}
767+
else
768+
{
769+
throw new ArgumentException($"Failed to parse parameter value: '{text}'", nameof(parameter));
770+
}
771+
}
772+
773+
return pixels / 96;
774+
}
775+
734776
/// <inheritdoc />
735777
protected override async Task ExposeFunctionAsync(string name, Delegate puppeteerFunction)
736778
{
@@ -1214,48 +1256,6 @@ await PrimaryTargetClient.SendAsync(
12141256
}
12151257
}
12161258

1217-
private decimal ConvertPrintParameterToInches(object parameter)
1218-
{
1219-
if (parameter == null)
1220-
{
1221-
return 0;
1222-
}
1223-
1224-
decimal pixels;
1225-
if (parameter is decimal or int)
1226-
{
1227-
pixels = Convert.ToDecimal(parameter, CultureInfo.CurrentCulture);
1228-
}
1229-
else
1230-
{
1231-
var text = parameter.ToString();
1232-
var unit = text.Length > 2 ? text.Substring(text.Length - 2).ToLower(CultureInfo.CurrentCulture) : string.Empty;
1233-
string valueText;
1234-
if (GetPixels(unit) is { })
1235-
{
1236-
valueText = text.Substring(0, text.Length - 2);
1237-
}
1238-
else
1239-
{
1240-
// In case of unknown unit try to parse the whole parameter as number of pixels.
1241-
// This is consistent with phantom's paperSize behavior.
1242-
unit = "px";
1243-
valueText = text;
1244-
}
1245-
1246-
if (decimal.TryParse(valueText, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var number))
1247-
{
1248-
pixels = number * GetPixels(unit).Value;
1249-
}
1250-
else
1251-
{
1252-
throw new ArgumentException($"Failed to parse parameter value: '{text}'", nameof(parameter));
1253-
}
1254-
}
1255-
1256-
return pixels / 96;
1257-
}
1258-
12591259
private Clip GetIntersectionRect(Clip clip, BoundingBox viewport)
12601260
{
12611261
var x = Math.Max(clip.X, viewport.X);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
#nullable enable
2+
3+
using System;
4+
using System.Text.Json;
5+
using System.Text.Json.Serialization;
6+
7+
namespace PuppeteerSharp.Helpers.Json
8+
{
9+
/// <summary>
10+
/// Support types (<see cref="decimal"/>, <see cref="int"/> and <see cref="string"/>)
11+
/// used by <see cref="PdfOptions"/> and <see cref="Media.MarginOptions"/> for serialization / deserialization.
12+
/// For usecases like <see href="https://github.com/hardkoded/puppeteer-sharp/issues/1001"/>.
13+
/// </summary>
14+
internal sealed class PrimitiveTypeConverter : JsonConverter<object>
15+
{
16+
public override object? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
17+
{
18+
if (reader.TokenType == JsonTokenType.Null)
19+
{
20+
return null;
21+
}
22+
else if (reader.TokenType == JsonTokenType.String)
23+
{
24+
return reader.GetString();
25+
}
26+
else if (reader.TokenType == JsonTokenType.Number)
27+
{
28+
if (reader.TryGetInt32(out var i))
29+
{
30+
return i;
31+
}
32+
else if (reader.TryGetDecimal(out var dec))
33+
{
34+
return dec;
35+
}
36+
}
37+
38+
return JsonSerializer.Deserialize(ref reader, typeToConvert, options);
39+
}
40+
41+
public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
42+
{
43+
if (value is null)
44+
{
45+
writer.WriteNullValue();
46+
}
47+
else if (value is string str)
48+
{
49+
writer.WriteStringValue(str);
50+
}
51+
else if (value is decimal dec)
52+
{
53+
writer.WriteNumberValue(dec);
54+
}
55+
else if (value is int i)
56+
{
57+
writer.WriteNumberValue(i);
58+
}
59+
else
60+
{
61+
JsonSerializer.Serialize(writer, value, options);
62+
}
63+
}
64+
}
65+
}
+11-47
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
using System;
2-
using System.Collections.Generic;
1+
using System.Text.Json.Serialization;
2+
using PuppeteerSharp.Helpers.Json;
33

44
namespace PuppeteerSharp.Media
55
{
66
/// <summary>
77
/// margin options used in <see cref="PdfOptions"/>.
88
/// </summary>
9-
public class MarginOptions : IEquatable<MarginOptions>
9+
public record MarginOptions
1010
{
1111
/// <summary>
1212
/// Initializes a new instance of the <see cref="PuppeteerSharp.Media.MarginOptions"/> class.
@@ -18,61 +18,25 @@ public MarginOptions()
1818
/// <summary>
1919
/// Top margin, accepts values labeled with units.
2020
/// </summary>
21-
public string Top { get; set; }
21+
[JsonConverter(typeof(PrimitiveTypeConverter))]
22+
public object Top { get; set; }
2223

2324
/// <summary>
2425
/// Left margin, accepts values labeled with units.
2526
/// </summary>
26-
public string Left { get; set; }
27+
[JsonConverter(typeof(PrimitiveTypeConverter))]
28+
public object Left { get; set; }
2729

2830
/// <summary>
2931
/// Bottom margin, accepts values labeled with units.
3032
/// </summary>
31-
public string Bottom { get; set; }
33+
[JsonConverter(typeof(PrimitiveTypeConverter))]
34+
public object Bottom { get; set; }
3235

3336
/// <summary>
3437
/// Right margin, accepts values labeled with units.
3538
/// </summary>
36-
public string Right { get; set; }
37-
38-
/// <summary>Overriding == operator for <see cref="MarginOptions"/>.</summary>
39-
/// <param name="left">the value to compare against <paramref name="right" />.</param>
40-
/// <param name="right">the value to compare against <paramref name="left" />.</param>
41-
/// <returns><c>true</c> if the two instances are equal to the same value.</returns>
42-
public static bool operator ==(MarginOptions left, MarginOptions right)
43-
=> EqualityComparer<MarginOptions>.Default.Equals(left, right);
44-
45-
/// <summary>Overriding != operator for <see cref="MarginOptions"/>.</summary>
46-
/// <param name="left">the value to compare against <paramref name="right" />.</param>
47-
/// <param name="right">the value to compare against <paramref name="left" />.</param>
48-
/// <returns><c>true</c> if the two instances are not equal to the same value.</returns>
49-
public static bool operator !=(MarginOptions left, MarginOptions right) => !(left == right);
50-
51-
/// <inheritdoc/>
52-
public override bool Equals(object obj)
53-
{
54-
if (obj == null || GetType() != obj.GetType())
55-
{
56-
return false;
57-
}
58-
59-
return Equals((MarginOptions)obj);
60-
}
61-
62-
/// <inheritdoc/>
63-
public bool Equals(MarginOptions options)
64-
=> options != null &&
65-
Top == options.Top &&
66-
Left == options.Left &&
67-
Bottom == options.Bottom &&
68-
Right == options.Right;
69-
70-
/// <inheritdoc/>
71-
public override int GetHashCode()
72-
=> -481391125
73-
^ EqualityComparer<string>.Default.GetHashCode(Top)
74-
^ EqualityComparer<string>.Default.GetHashCode(Left)
75-
^ EqualityComparer<string>.Default.GetHashCode(Bottom)
76-
^ EqualityComparer<string>.Default.GetHashCode(Right);
39+
[JsonConverter(typeof(PrimitiveTypeConverter))]
40+
public object Right { get; set; }
7741
}
7842
}

lib/PuppeteerSharp/Media/PaperFormat.cs

+1-40
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,10 @@
1-
using System;
2-
using System.Collections.Generic;
3-
41
namespace PuppeteerSharp.Media
52
{
63
/// <summary>
74
/// Paper format.
85
/// </summary>
96
/// <seealso cref="PdfOptions.Format"/>
10-
public class PaperFormat : IEquatable<PaperFormat>
7+
public record PaperFormat
118
{
129
/// <summary>
1310
/// Initializes a new instance of the <see cref="PaperFormat"/> class.
@@ -87,41 +84,5 @@ public PaperFormat(decimal width, decimal height)
8784
/// </summary>
8885
/// <value>The Height.</value>
8986
public decimal Height { get; set; }
90-
91-
/// <summary>Overriding == operator for <see cref="PaperFormat"/>. </summary>
92-
/// <param name="left">the value to compare against <paramref name="right" />.</param>
93-
/// <param name="right">the value to compare against <paramref name="left" />.</param>
94-
/// <returns><c>true</c> if the two instances are equal to the same value.</returns>
95-
public static bool operator ==(PaperFormat left, PaperFormat right)
96-
=> EqualityComparer<PaperFormat>.Default.Equals(left, right);
97-
98-
/// <summary>Overriding != operator for <see cref="PaperFormat"/>. </summary>
99-
/// <param name="left">the value to compare against <paramref name="right" />.</param>
100-
/// <param name="right">the value to compare against <paramref name="left" />.</param>
101-
/// <returns><c>true</c> if the two instances are not equal to the same value.</returns>
102-
public static bool operator !=(PaperFormat left, PaperFormat right) => !(left == right);
103-
104-
/// <inheritdoc/>
105-
public override bool Equals(object obj)
106-
{
107-
if (obj == null || GetType() != obj.GetType())
108-
{
109-
return false;
110-
}
111-
112-
return Equals((PaperFormat)obj);
113-
}
114-
115-
/// <inheritdoc/>
116-
public bool Equals(PaperFormat format)
117-
=> format != null &&
118-
Width == format.Width &&
119-
Height == format.Height;
120-
121-
/// <inheritdoc/>
122-
public override int GetHashCode()
123-
=> 859600377
124-
^ Width.GetHashCode()
125-
^ Height.GetHashCode();
12687
}
12788
}

lib/PuppeteerSharp/PdfOptions.cs

+4
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
using System.Text.Json.Serialization;
2+
using PuppeteerSharp.Helpers.Json;
13
using PuppeteerSharp.Media;
24

35
namespace PuppeteerSharp
@@ -67,11 +69,13 @@ public PdfOptions()
6769
/// <summary>
6870
/// Paper width, accepts values labeled with units.
6971
/// </summary>
72+
[JsonConverter(typeof(PrimitiveTypeConverter))]
7073
public object Width { get; set; }
7174

7275
/// <summary>
7376
/// Paper height, accepts values labeled with units.
7477
/// </summary>
78+
[JsonConverter(typeof(PrimitiveTypeConverter))]
7579
public object Height { get; set; }
7680

7781
/// <summary>

0 commit comments

Comments
 (0)