Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change pdflib puppeteer #2536

Draft
wants to merge 37 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
f1126c6
[+] Added puppeteersharp for pdf creation #2322
SolidProgramming Sep 10, 2024
b9234c0
[~] Changed the spinner controls to hide it's text
SolidProgramming Sep 10, 2024
6fc08c4
[~] Moved the PDF generation with puppeteer to reportbase
SolidProgramming Sep 11, 2024
1e9ef5b
[+] Added overloads for pdf creation with puppeteer
SolidProgramming Sep 12, 2024
ed5ac52
[+] Added custom pdf size for puppeteer
SolidProgramming Sep 12, 2024
105dedb
[-] Removed wkhtml
SolidProgramming Sep 13, 2024
1c56417
[-] Removed wkhtml
SolidProgramming Sep 13, 2024
454e924
Merge branch 'change_pdflib_puppeteer' of https://github.com/SolidPro…
SolidProgramming Sep 13, 2024
6ae7dbc
[~] Fixed PDF generation test
SolidProgramming Sep 13, 2024
50d62be
Merge branch 'develop' into change_pdflib_puppeteer
tpurschke Sep 16, 2024
6e28414
[~] Github Test Build fix?
SolidProgramming Sep 16, 2024
0e3f3f9
Merge branch 'change_pdflib_puppeteer' of https://github.com/SolidPro…
SolidProgramming Sep 16, 2024
de2002b
test push
SolidProgramming Sep 17, 2024
7a4edea
test push
SolidProgramming Sep 17, 2024
75e2f99
test push
SolidProgramming Sep 17, 2024
e1b4f7f
test push
SolidProgramming Sep 17, 2024
9229cb5
test push
SolidProgramming Sep 17, 2024
c1974e1
test push
SolidProgramming Sep 17, 2024
c6beba7
test push
SolidProgramming Sep 20, 2024
be08ae9
test push
SolidProgramming Sep 20, 2024
a660446
[~] test push
SolidProgramming Sep 26, 2024
3eb133a
[~] test push
SolidProgramming Sep 26, 2024
61379b3
[~] test push
SolidProgramming Sep 26, 2024
4225d29
[~] test push
SolidProgramming Sep 26, 2024
9323193
.
SolidProgramming Sep 27, 2024
70a6762
.
SolidProgramming Sep 27, 2024
ec8cf45
.
SolidProgramming Sep 27, 2024
b3d2b10
.
SolidProgramming Sep 27, 2024
8ab4735
.
SolidProgramming Sep 27, 2024
44cef85
.
SolidProgramming Sep 27, 2024
9c699d9
.
SolidProgramming Sep 27, 2024
7b58627
.
SolidProgramming Sep 27, 2024
5e23089
.
SolidProgramming Sep 27, 2024
a677a1a
.
SolidProgramming Sep 27, 2024
0013d39
.
SolidProgramming Sep 27, 2024
3e80b5c
.
SolidProgramming Sep 27, 2024
a4b7b31
.
SolidProgramming Sep 27, 2024
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
2 changes: 2 additions & 0 deletions roles/lib/files/FWO.GlobalConstants/GlobalConstants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ public struct GlobalConst
public const string kUndefinedText = "(undefined text)";

public const string kStyleHighlighted = "color:red;";

public const string FworchUnixBrowserBinPath = "/usr/local/fworch/";
}

public struct PageName
Expand Down
2 changes: 1 addition & 1 deletion roles/lib/files/FWO.Report/FWO.Report.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Haukcode.WkHtmlToPdfDotNet" Version="1.5.90" />
<PackageReference Include="PuppeteerSharp" Version="20.0.2" />
</ItemGroup>

<ItemGroup>
Expand Down
18 changes: 18 additions & 0 deletions roles/lib/files/FWO.Report/PaperFormat.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
namespace FWO.Report
{
public enum PaperFormat
{
A0,
A1,
A2,
A3,
A4,
A5,
A6,
Letter,
Legal,
Tabloid,
Ledger,
Custom
}
}
112 changes: 65 additions & 47 deletions roles/lib/files/FWO.Report/ReportBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@
using FWO.Report.Filter;
using FWO.Config.Api;
using System.Text;
using WkHtmlToPdfDotNet;
using PuppeteerSharp.Media;
using PuppeteerSharp;
using System.Reflection;

namespace FWO.Report
{
public enum RsbTab
{
all = 10,
report = 20,
all = 10,
report = 20,
rule = 30,

usedObj = 40,
Expand All @@ -21,8 +23,8 @@ public enum RsbTab
public enum ObjCategory
{
all = 0,
nobj = 1,
nsrv = 2,
nobj = 1,
nsrv = 2,
user = 3
}

Expand All @@ -42,7 +44,7 @@ public enum OutputLocation

public abstract class ReportBase
{
protected StringBuilder HtmlTemplate = new ($@"
protected StringBuilder HtmlTemplate = new($@"
<!DOCTYPE html>
<html>
<head>
Expand Down Expand Up @@ -86,11 +88,11 @@ public abstract class ReportBase
protected UserConfig userConfig;
public ReportType ReportType;
public ReportData ReportData = new();
public int CustomWidth = 0;
public int CustomHeight = 0;

protected string htmlExport = "";

// Pdf converter
protected static readonly SynchronizedConverter converter = new (new PdfTools());
public bool GotObjectsInReport { get; protected set; } = false;


Expand Down Expand Up @@ -160,14 +162,14 @@ protected string GenerateHtmlFrameBase(string title, string filter, DateTime dat
HtmlTemplate = HtmlTemplate.Replace("##Filter##", userConfig.GetText("filter") + ": " + filter);
HtmlTemplate = HtmlTemplate.Replace("##GeneratedOn##", userConfig.GetText("generated_on"));
HtmlTemplate = HtmlTemplate.Replace("##Date##", date.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK"));
if(ReportType.IsChangeReport())
if (ReportType.IsChangeReport())
{
string timeRange = $"{userConfig.GetText("change_time")}: " +
$"{userConfig.GetText("from")}: {ToUtcString(Query.QueryVariables["start"]?.ToString())}, " +
$"{userConfig.GetText("until")}: {ToUtcString(Query.QueryVariables["stop"]?.ToString())}";
HtmlTemplate = HtmlTemplate.Replace("##Date-of-Config##: ##GeneratedFor##", timeRange);
}
else if(ReportType.IsRuleReport() || ReportType == ReportType.Statistics)
else if (ReportType.IsRuleReport() || ReportType == ReportType.Statistics)
{
HtmlTemplate = HtmlTemplate.Replace("##Date-of-Config##", userConfig.GetText("date_of_config"));
HtmlTemplate = HtmlTemplate.Replace("##GeneratedFor##", ToUtcString(Query.ReportTimeString));
Expand All @@ -186,7 +188,7 @@ protected string GenerateHtmlFrameBase(string title, string filter, DateTime dat
HtmlTemplate = HtmlTemplate.Replace("<p>##OwnerFilters##</p>", "");
}

if(deviceFilter != null)
if (deviceFilter != null)
{
HtmlTemplate = HtmlTemplate.Replace("##OtherFilters##", userConfig.GetText("devices") + ": " + deviceFilter);
}
Expand All @@ -206,58 +208,74 @@ public static string ToUtcString(string? timestring)
{
return timestring != null ? DateTime.Parse(timestring).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK") : "";
}
catch(Exception)
catch (Exception)
{
return timestring ?? "";
}
}

public virtual byte[] ToPdf(PaperKind paperKind, int width = -1, int height = -1)
private async Task<string?> CreatePDFViaPuppeteer(string html, PaperFormat format)
{
// HTML
if (string.IsNullOrEmpty(htmlExport))
using IBrowser? browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
htmlExport = ExportToHtml();
}
Headless = true
});

GlobalSettings globalSettings = new ()
try
{
ColorMode = ColorMode.Color,
Orientation = Orientation.Landscape,
};
using IPage page = await browser.NewPageAsync();
await page.SetContentAsync(html);

if (paperKind == PaperKind.Custom)
PuppeteerSharp.Media.PaperFormat? pupformat = GetPuppeteerPaperFormat(format) ?? throw new Exception();

PdfOptions pdfOptions = new() { DisplayHeaderFooter = true, Landscape = true, PrintBackground = true, Format = pupformat, MarginOptions = new MarginOptions { Top = "1cm", Bottom = "1cm", Left = "1cm", Right = "1cm" } };
byte[] pdfData = await page.PdfDataAsync(pdfOptions);

return Convert.ToBase64String(pdfData);
}
catch (Exception)
{
if (width > 0 && height > 0)
{
globalSettings.PaperSize = new PechkinPaperSize(width + "mm", height + "mm");
}
else
{
throw new Exception("Custom paper size: width or height <= 0");
}
throw new Exception("This paper kind is currently not supported. Please choose another one or \"Custom\" for a custom size.");
}
else
finally
{
globalSettings.PaperSize = paperKind;
await browser.CloseAsync();
}
}

HtmlToPdfDocument doc = new ()
{
GlobalSettings = globalSettings,
Objects =
{
new ObjectSettings()
{
PagesCount = true,
HtmlContent = htmlExport,
WebSettings = { DefaultEncoding = "utf-8" },
HeaderSettings = { FontSize = 9, Right = "Page [page] of [toPage]", Line = true, Spacing = 2.812 }
}
}
};
private PuppeteerSharp.Media.PaperFormat? GetPuppeteerPaperFormat(PaperFormat format)
{
if (format == PaperFormat.Custom)
return new PuppeteerSharp.Media.PaperFormat(CustomWidth, CustomHeight);

PropertyInfo[] propertyInfos = typeof(PuppeteerSharp.Media.PaperFormat).GetProperties(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic);

PropertyInfo? prop = propertyInfos.SingleOrDefault(_ => _.Name == format.ToString());

if (prop == null)
return default;

PuppeteerSharp.Media.PaperFormat? propFormat = (PuppeteerSharp.Media.PaperFormat)prop.GetValue(null);

if (propFormat is null)
return default;

return propFormat;
}

public virtual async Task<string?> ToPdf(string html, PaperFormat format)
{
return await CreatePDFViaPuppeteer(html, format);
}

return converter.Convert(doc);
public virtual async Task<string?> ToPdf(string html)
{
return await CreatePDFViaPuppeteer(html, PaperFormat.A4);
}

public virtual async Task<string?> ToPdf(PaperFormat format)
{
return await CreatePDFViaPuppeteer(htmlExport, format);
}

public static string GetIconClass(ObjCategory? objCategory, string? objType)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
using Newtonsoft.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using WkHtmlToPdfDotNet;
using PuppeteerSharp.Media;

namespace FWO.Middleware.Server
{
Expand Down Expand Up @@ -175,11 +175,14 @@ private async Task SendEmail()
EmailConnection emailConnection = new(globalConfig.EmailServerAddress, globalConfig.EmailPort,
globalConfig.EmailTls, globalConfig.EmailUser, decryptedSecret, globalConfig.EmailSenderAddress);
MailKitMailer mailer = new(emailConnection);
await mailer.SendAsync(PrepareEmail(), emailConnection, new CancellationToken(),

MailData? mail = await PrepareEmail();

await mailer.SendAsync(mail, emailConnection, new CancellationToken(),
globalConfig.ImpChangeNotifyType == (int)ImpChangeNotificationType.HtmlInBody);
}

private MailData PrepareEmail()
private async Task<MailData> PrepareEmail()
{
string subject = globalConfig.ImpChangeNotifySubject;
string body = CreateBody();
Expand All @@ -192,7 +195,12 @@ private MailData PrepareEmail()
body += changeReport?.ExportToHtml();
break;
case (int)ImpChangeNotificationType.PdfAsAttachment:
attachment = CreateAttachment(Convert.ToBase64String(changeReport?.ToPdf(PaperKind.A4) ?? throw new Exception("No Pdf generated.")), GlobalConst.kPdf);
string? pdfData = await changeReport.ToPdf(Report.PaperFormat.A4);

if (string.IsNullOrWhiteSpace(pdfData))
throw new Exception("No Pdf generated.");

attachment = CreateAttachment(pdfData, GlobalConst.kPdf);
break;
case (int)ImpChangeNotificationType.HtmlAsAttachment:
attachment = CreateAttachment(changeReport?.ExportToHtml(), GlobalConst.kHtml);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
using FWO.Report;
using FWO.Report.Filter;
using System.Timers;
using WkHtmlToPdfDotNet;
using FWO.Config.File;
using PuppeteerSharp.Media;

namespace FWO.Middleware.Server
{
Expand Down Expand Up @@ -255,7 +255,7 @@ private static async Task AdaptDeviceFilter(ReportParams reportParams, ApiConnec
}
}

private static void WriteReportFile(ReportBase report, List<FileFormat> fileFormats, ReportFile reportFile)
private static async Task WriteReportFile(ReportBase report, List<FileFormat> fileFormats, ReportFile reportFile)
{
reportFile.Json = report.ExportToJson();
foreach (FileFormat format in fileFormats)
Expand All @@ -271,7 +271,7 @@ private static void WriteReportFile(ReportBase report, List<FileFormat> fileForm
break;

case GlobalConst.kPdf:
reportFile.Pdf = Convert.ToBase64String(report.ToPdf(PaperKind.A4));
reportFile.Pdf = await report.ToPdf(Report.PaperFormat.A4);
break;

case GlobalConst.kJson:
Expand Down
2 changes: 1 addition & 1 deletion roles/test/files/FWO.Test/FWO.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Haukcode.WkHtmlToPdfDotNet" Version="1.5.90" />
<PackageReference Include="NUnit" Version="4.1.0" />
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.0.0" />
<PackageReference Include="PuppeteerSharp" Version="20.0.2" />
</ItemGroup>

<ItemGroup>
Expand Down
Loading