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
7 changes: 0 additions & 7 deletions HtmlPdfPlus.sln
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HtmlPdfPlus.Server", "src\H
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HtmlPdfPlus.Shared", "src\HtmlPdfPlus.Shared\HtmlPdfPlus.Shared.csproj", "{305A8FB5-2E0A-4771-9CC5-5D0D9B3ABB72}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Workflows", "Workflows", "{5ABE1DDA-E964-40F4-BF56-4B52E0605666}"
ProjectSection(SolutionItems) = preProject
.github\workflows\build.yml = .github\workflows\build.yml
.github\workflows\codeql.yml = .github\workflows\codeql.yml
.github\workflows\publish.yml = .github\workflows\publish.yml
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down
32 changes: 21 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,22 @@ The current version (V.1.50.0) of **Playwright** supports **only the Chromium br
- AfterPDF : Save file, Send to cloud, etc
- Disable features to improve/ balance performance (minify, compress and log)

#### What's new in the latest version

- Initial version
#### What's new in the latest version

- v0.3.0-beta (latest version)
- Added FromUrl(Uri value) command to client-side mode
- Fixed bug in server mode for multi thread safe when there is parameter customization and/or no client mode sending.
- Moved the BeforePDF(Func<string, TIn?, CancellationToken, Task<string>> inputParam) command to the execution context.
- Moved the AfterPDF(Func<byte[]?, TIn?, CancellationToken, Task<TOut>> outputParam) command to the execution context.
- Added command Source(TIn? inputparam = default) to transfer input parameter for server execution context and custom actions and html source.
- Added Request(string request Client) command to pass the request client data to the server execution context for custom actions and HTML source.
- Simplified execution commands for server side with execution context with fluid interface comands :
- Removed static class RequestHtmlPdf
- Added command FromHtml(string html, int converttimeout = 30000, bool minify = true)
- Added command FromUrl(Uri value, int converttimeout = 30000)
- Added command FromRazor\<T\>(string template, T model, int converttimeout = 30000, bool minify = true)
- v0.2.0-beta
- Initial version

## Prerequisites
[**Top**](#table-of-contents)
Expand Down Expand Up @@ -242,8 +255,6 @@ Host.CreateDefaultBuilder(args)
{
services.AddHtmlPdfService((cfg) =>
{
//when run in the same context, not Compress is fast because it is not required to transfer data over the network
cfg.DisableFeatures(DisableOptionsHtmlToPdf.DisableCompress);
.Logger(LogLevel.Debug, "MyPDFServer")
.DefaultConfig((page) =>
{
Expand All @@ -257,12 +268,11 @@ Host.CreateDefaultBuilder(args)
//instance of Html to Pdf Engine and Warmup HtmlPdfServerPlus
var PDFserver = HostApp!.Services.GetHtmlPdfService();

//create a request with default configuration and without compression to the server
//when run in the same context, not Compress is fast because it is not required to transfer data over the network
var request = RequestHtmlPdf.Create(HtmlSample(), compress: false);

//Performs conversion on the server
var pdfresult = await PDFserver.Run(request, applifetime.ApplicationStopping);
//Performs conversion and custom operations on the server
var pdfresult = await PDFserver
.Source()
.FromHtml(HtmlSample(),5000)
.Run(applifetime.ApplicationStopping);

//performs writing to file after performing conversion
if (pdfresult.IsSuccess)
Expand Down
27 changes: 27 additions & 0 deletions samples/ConsoleHtmlToPdfPlus.ClientSendHttp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,33 @@ public static async Task Main(string[] args)
Console.WriteLine($"HtmlPdfClient error: {pdfresult.Error!}");
}

Console.WriteLine("Press any key to next");
Console.ReadKey();

//create client instance and send to server
Console.WriteLine($"HtmlPdfClient send Url to PDF Server via http post");

pdfresult = await HtmlPdfClient.Create("HtmlPdfPlusClient")
.PageConfig((cfg) => cfg.Margins(10))
.Logger(HostApp.Services.GetService<ILogger<Program>>())
.FromUrl(new Uri("https://github.com/FRACerqueira/HtmlPdfPlus"))
.Timeout(15000)
.Run(clienthttp, applifetime.ApplicationStopping);

Console.WriteLine($"HtmlPdfClient IsSuccess {pdfresult.IsSuccess} after {pdfresult.ElapsedTime}");

//performs writing to file after performing conversion
if (pdfresult.IsSuccess)
{
var fullpath = Path.Combine(PathToSamples, "HtmlPdfPlus.pdf");
await File.WriteAllBytesAsync(fullpath, pdfresult.OutputData!);
Console.WriteLine($"File PDF generate at {fullpath}");
}
else
{
Console.WriteLine($"HtmlPdfClient error: {pdfresult.Error!}");
}


Console.WriteLine("Press any key to end");
Console.ReadKey();
Expand Down
4 changes: 1 addition & 3 deletions samples/ConsoleHtmlToPdfPlus.ClientSendTcp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,6 @@ public static async Task Main(string[] args)
//create client instance and to HtmlPdfPlus server endpoint
Console.WriteLine($"HtmlPdfClient send Html to PDF Server via http post");

TimeoutWaitResponse = 50000;

var pdfresult = await HtmlPdfClient.Create("HtmlPdfPlusClient")
.PageConfig((cfg) =>
{
Expand All @@ -64,7 +62,7 @@ public static async Task Main(string[] args)
})
.Logger(HostApp.Services.GetService<ILogger<Program>>())
.FromHtml(HtmlSample())
.Timeout(TimeoutWaitResponse)
.Timeout(5000)
.Run(SendToTcpServer, applifetime.ApplicationStopping);

Console.WriteLine($"HtmlPdfClient IsSuccess {pdfresult.IsSuccess} after {pdfresult.ElapsedTime}");
Expand Down
11 changes: 3 additions & 8 deletions samples/ConsoleHtmlToPdfPlus.OnlyAtServer/v1/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,10 @@ public static async Task Main(string[] args)
//instance of Html to Pdf Engine
var PDFserver = HostApp!.Services.GetHtmlPdfService<string, string>();

//create a request with custom type param , default config page and without compression to save file at server.
//When run in the same context, not Compress is fast because it is not required to transfer data over the network
var request = RequestHtmlPdf.Create(
HtmlSample(),
5000,
param: Path.Combine(PathToSamples, "html2pdfHtml.pdf"));

//Performs conversion and custom operations on the server
var pdfresult = await PDFserver
.Source(Path.Combine(PathToSamples, "html2pdfHtml.pdf"))
.FromHtml(HtmlSample(), 5000)
.BeforePDF((html, _, _) =>
{
//performs replacement token substitution in the HTML source before performing the conversion
Expand All @@ -56,7 +51,7 @@ public static async Task Main(string[] args)
Console.WriteLine($"File PDF generate at {filepath}");
return filepath!;
})
.Run(request, applifetime.ApplicationStopping);
.Run(applifetime.ApplicationStopping);

Console.WriteLine($"HtmlPdfServer IsSuccess {pdfresult.IsSuccess} after {pdfresult.ElapsedTime}");

Expand Down
39 changes: 26 additions & 13 deletions samples/ConsoleHtmlToPdfPlus.OnlyAtServer/v2/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
// https://github.com/FRACerqueira/HtmlPdfPlus
// ***************************************************************************************

using HtmlPdfPlus;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -32,28 +31,46 @@ public static async Task Main(string[] args)

Console.WriteLine($"HtmlPdfServerPlus ready");

//create a request with default configuration and without compression to the server
//when run in the same context, not Compress is fast because it is not required to transfer data over the network
//change compress to false to uncompression (recommended)
//if you want to disable compression, uncomment the line 80!
var request = RequestHtmlPdf.Create(HtmlSample(), compress: true);

//Performs conversion on the server
var pdfresult = await PDFserver.Run(request, applifetime.ApplicationStopping);
var pdfresult = await PDFserver
.Source()
.FromHtml(HtmlSample(),5000)
.Run(applifetime.ApplicationStopping);

Console.WriteLine($"HtmlPdfServer IsSuccess {pdfresult.IsSuccess} after {pdfresult.ElapsedTime}");

//performs writing to file after performing conversion
if (pdfresult.IsSuccess)
{
var fullpath = Path.Combine(PathToSamples, "html2pdfHtml.pdf");
await File.WriteAllBytesAsync(fullpath, pdfresult.DecompressBytes()!);
await File.WriteAllBytesAsync(fullpath, pdfresult.OutputData!);
Console.WriteLine($"File PDF generate at {fullpath}");
}
else
{
Console.WriteLine($"HtmlPdfServer error: {pdfresult.Error}");
}

//Performs conversion on the server
pdfresult = await PDFserver
.Source()
.FromUrl(new Uri("https://github.com/FRACerqueira/HtmlPdfPlus"), 5000)
.Run(applifetime.ApplicationStopping);

Console.WriteLine($"HtmlPdfServer IsSuccess {pdfresult.IsSuccess} after {pdfresult.ElapsedTime}");

//performs writing to file after performing conversion
if (pdfresult.IsSuccess)
{
var fullpath = Path.Combine(PathToSamples, "HtmlPdfPlus.pdf");
await File.WriteAllBytesAsync(fullpath, pdfresult.OutputData!);
Console.WriteLine($"File PDF generate at {fullpath}");
}
else
{
Console.WriteLine($"HtmlPdfServer error: {pdfresult.Error}");
}

Console.WriteLine("Press any key");
Console.ReadKey();

Expand All @@ -72,10 +89,6 @@ private static IHostBuilder CreateHostBuilder(string[] args) =>
{
services.AddHtmlPdfService((cfg) =>
{
//when run in the same context, not Compress is fast because it is not required to transfer data over the network
//Remove the comment to disable compression (recommended)
//if you want to disable compression,change compress to false at line 41
//cfg.DisableFeatures(DisableOptionsHtmlToPdf.DisableCompress);
cfg.Logger(LogLevel.Debug, "MyPDFServer")
.DefaultConfig((page) =>
{
Expand Down
5 changes: 4 additions & 1 deletion samples/TcpServerHtmlToPdf.GenericServer/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Text;
using System.Text.Json;
using HtmlPdfPlus;
using HtmlPdfPlus.Shared.Core;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -112,7 +113,9 @@ private static void DataReceived(object sender, DataReceivedEventArgs e)

var request = Encoding.UTF8.GetString(e.Data.Array!, 0, e.Data.Count);

var aux = PDFserver.Run(request, CancellationToken.None).Result;
var aux = PDFserver
.Request(request)
.Run(CancellationToken.None).Result;

var sendata = JsonSerializer.Serialize<HtmlPdfResult<byte[]>>(aux);

Expand Down
3 changes: 2 additions & 1 deletion samples/WebHtmlToPdf.CustomSaveFileServer/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
app.MapPost("/SavePdf", async ([FromServices] IHtmlPdfServer<DataSavePDF,string> PDFserver, [FromBody] string requestclienthtmltopdf, CancellationToken token) =>
{
return await PDFserver
.Request(requestclienthtmltopdf)
.BeforePDF( (html,inputparam, _) =>
{
if (inputparam is null)
Expand All @@ -52,7 +53,7 @@
//TODO : performs writing to file after performing conversion
return Task.FromResult(inputparam.Filename);
})
.Run(requestclienthtmltopdf, token);
.Run(token);
}).Produces<HtmlPdfResult<string>>(200);

app.Run();
3 changes: 2 additions & 1 deletion samples/WebHtmlToPdf.GenericServer/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@

app.MapPost("/GeneratePdf", async ([FromServices] IHtmlPdfServer<object, byte[]> PDFserver, [FromBody] string requestclienthtmltopdf, CancellationToken token) =>
{
return await PDFserver.Run(requestclienthtmltopdf, token);
return await PDFserver
.Run(requestclienthtmltopdf,token);
}).Produces<HtmlPdfResult<byte[]>>(200);

app.Run();
11 changes: 9 additions & 2 deletions src/HtmlPdfPlus.Client/Commands/IHtmlPdfClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,20 @@ public interface IHtmlPdfClient
IHtmlPdfClient Logger(ILogger? logger, LogLevel logLevel = LogLevel.Debug);

/// <summary>
/// Register HTML template to be executed by the server.
/// Register HTML to be executed by the server.
/// </summary>
/// <param name="html">The HTML content.</param>
/// <returns><see cref="IHtmlPdfClient"/> instance.</returns>
/// <exception cref="ArgumentNullException">Thrown when the HTML content is null.</exception>
IHtmlPdfClient FromHtml(string html);

/// <summary>
/// ;Register Page Url to be executed by the server.
/// </summary>
/// <param name="value">The url</param>
/// <returns><see cref="IHtmlPdfClient"/> instance.</returns>
IHtmlPdfClient FromUrl(Uri value);

/// <summary>
/// Execute the Razor HTML template with the data and register the HTML.
/// </summary>
Expand All @@ -62,7 +69,7 @@ public interface IHtmlPdfClient
/// Execute parse validation of the HTML before sending it to the server.
/// </summary>
/// <param name="validate">Execute validation.Default <c>false</c></param>
/// <param name="whenhaserror">Action when has errror. The action input is VisualStudio format error message file(startline[-endline]?,startcol[-endcol]?):[subcategory] category [errorcode]: message</param>
/// <param name="whenhaserror">Action when has errror. The action input is VisualStudio string format error message </param>
/// <returns><see cref="IHtmlPdfClient"/> instance.</returns>
IHtmlPdfClient HtmlParser(bool validate, Action<string> whenhaserror);

Expand Down
17 changes: 12 additions & 5 deletions src/HtmlPdfPlus.Client/Core/HtmlPdfClientInstance.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ internal sealed class HtmlPdfClientInstance(string sourcealias, DisableOptionsHt
private bool _htmlparse = false;
private string? _errorparse = null;
private Action<string>? _parseError = null;
private static readonly JsonSerializerOptions jsonoptions = new() { PropertyNameCaseInsensitive = true };

/// <inheritdoc />
public IHtmlPdfClient PageConfig(Action<IPdfPageConfig> config)
Expand Down Expand Up @@ -77,6 +76,14 @@ public IHtmlPdfClient FromHtml(string value)
return this;
}

/// <inheritdoc />
public IHtmlPdfClient FromUrl(Uri value)
{
_html = value.ToString();
_errorparse = null;
return this;
}

/// <inheritdoc />
public IHtmlPdfClient FromRazor<T>(string template, T razordata)
{
Expand Down Expand Up @@ -310,7 +317,7 @@ private StringContent CreateHttpContent<T>(T? customdata)
private string CreateRequestSend<T>(T? inputparam)
{
return disableOptions.HasFlag(DisableOptionsHtmlToPdf.DisableCompress)
? JsonSerializer.Serialize(new RequestHtmlPdf<T>(_html, sourcealias, _pdfPageConfig, _timeout, inputparam), jsonoptions)
? JsonSerializer.Serialize(new RequestHtmlPdf<T>(_html, sourcealias, _pdfPageConfig, _timeout, inputparam), GZipHelper.JsonOptions)
: GZipHelper.CompressRequest(sourcealias, _pdfPageConfig, _html, _timeout, inputparam);
}

Expand Down Expand Up @@ -357,11 +364,11 @@ private async Task<HtmlPdfResult<Tout>> HandleHttpResponse<Tout>(HttpResponseMes
{
if (disableOptions.HasFlag(DisableOptionsHtmlToPdf.DisableCompress))
{
return JsonSerializer.Deserialize<HtmlPdfResult<Tout>>(resultconvert, jsonoptions)!;
return JsonSerializer.Deserialize<HtmlPdfResult<Tout>>(resultconvert, GZipHelper.JsonOptions)!;
}
else
{
var auxresult = JsonSerializer.Deserialize<HtmlPdfResult<Tout>>(resultconvert, jsonoptions)!;
var auxresult = JsonSerializer.Deserialize<HtmlPdfResult<Tout>>(resultconvert, GZipHelper.JsonOptions)!;
if (auxresult.OutputData is null)
{
return auxresult;
Expand All @@ -371,7 +378,7 @@ private async Task<HtmlPdfResult<Tout>> HandleHttpResponse<Tout>(HttpResponseMes
}
else
{
return JsonSerializer.Deserialize<HtmlPdfResult<Tout>>(resultconvert, jsonoptions)!;
return JsonSerializer.Deserialize<HtmlPdfResult<Tout>>(resultconvert, GZipHelper.JsonOptions)!;
}
}
else
Expand Down
8 changes: 2 additions & 6 deletions src/HtmlPdfPlus.Client/HtmlPdfClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

using System.Text.Json;
using HtmlPdfPlus.Client.Core;
using HtmlPdfPlus.Shared.Core;

namespace HtmlPdfPlus
{
Expand Down Expand Up @@ -52,13 +53,8 @@ public static HtmlPdfResult<T> ToHtmlPdfResult<T>(this string dataresponse)
throw new ArgumentException("Response data cannot be null or empty", nameof(dataresponse));
}

return JsonSerializer.Deserialize<HtmlPdfResult<T>>(dataresponse, jsonoptions)!;
return JsonSerializer.Deserialize<HtmlPdfResult<T>>(dataresponse, GZipHelper.JsonOptions)!;
}

private static readonly JsonSerializerOptions jsonoptions = new()
{
PropertyNameCaseInsensitive = true
};
}
}

1 change: 0 additions & 1 deletion src/HtmlPdfPlus.Client/HtmlPdfPlus.Client.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.3" />
<PackageReference Include="NUglify" Version="1.21.13" />
<PackageReference Include="RazorEngineCore" Version="2024.4.1" />
<PackageReference Include="System.Text.Json" Version="9.0.3" />
</ItemGroup>
</Project>
Loading