Files
elwig/WGneu/Documents/Pdf.cs
2023-03-08 01:29:57 +01:00

81 lines
2.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Threading.Tasks;
using PdfSharp.Pdf.IO;
using PuppeteerSharp;
using PuppeteerSharp.Media;
using RazorLight;
using WGneu.Windows;
namespace WGneu.Documents {
public static class Pdf {
private static readonly string CHROMIUM = @"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe";
private static IBrowser? _Browser = null;
private static RazorLightEngine? _Engine = null;
public static void Init() {
var b = Browser;
var e = Engine;
}
private static IBrowser Browser {
get {
_Browser ??= Puppeteer.LaunchAsync(new LaunchOptions {
Headless = true,
ExecutablePath = CHROMIUM,
}).GetAwaiter().GetResult();
return _Browser;
}
}
private static RazorLightEngine Engine {
get {
_Engine ??= new RazorLightEngineBuilder()
.UseFileSystemProject(@"C:\Users\Lorenz\source\repos\WGneu\WGneu\Documents")
.UseMemoryCachingProvider()
.Build();
return _Engine;
}
}
public static async Task Convert(string path_html, string path_pdf) {
using var page = await Browser.NewPageAsync();
await page.GoToAsync("file://" + path_html);
await page.WaitForFunctionAsync("() => window.finished");
await page.PdfAsync(path_pdf, new() {
PreferCSSPageSize = true,
//Format = PaperFormat.A4,
DisplayHeaderFooter = false,
MarginOptions = new() {
Top = "0mm",
Right = "0mm",
Bottom = "0mm",
Left = "0mm",
},
});
}
public static void UpdateMetadata(string path, string title, string author) {
using var doc = PdfReader.Open(path);
doc.Info.Title = title;
doc.Info.Author = author;
doc.Save(path);
}
public static void Display(string title, string path) {
var w = new DocumentViewerWindow(title, path);
w.Show();
}
public static async Task<string> CompileRenderAsync(string key, object model) {
return await Engine.CompileRenderAsync(key, model);
}
}
}