├── AspNetSample ├── publish.cmd ├── appsettings.Development.json ├── appsettings.json ├── Program.cs ├── WebApplication1.http ├── web.config ├── AspNetSample.csproj ├── Properties │ └── launchSettings.json ├── WebApplication1.websurge └── PdfController.cs ├── icon.png ├── Assets └── RunningUnderIIS.png ├── ConsoleSample ├── Properties │ └── launchsettings.json ├── ConsoleSample.csproj └── Program.cs ├── Westwind.HtmlToPdf.Test ├── PdfSampleFile.pdf ├── Westwind.HtmlToPdf.Test.csproj └── PrintToPdfTests.cs ├── Westwind.WebView.HtmlToPdf ├── PdfPrintOutputModes.cs ├── publish-nuget.ps1 ├── Enums.cs ├── PdfPrintResult.cs ├── Westwind.WebView.HtmlToPdf.csproj ├── Utilities │ ├── StreamExtensions.cs │ └── StringUtils.cs ├── WebViewPrintSettings.cs ├── CoreWebViewHeadlessHost.cs └── HtmlToPdfHost.cs ├── .github └── FUNDING.yml ├── LICENSE.md ├── README.md ├── .gitattributes ├── WestWind.WebView.HtmlToPdf.sln └── .gitignore /AspNetSample/publish.cmd: -------------------------------------------------------------------------------- 1 | IISRESET 2 | dotnet publish -o ../WebApp1_Publish -c Release -------------------------------------------------------------------------------- /icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RickStrahl/WestWind.WebView.HtmlToPdf/HEAD/icon.png -------------------------------------------------------------------------------- /Assets/RunningUnderIIS.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RickStrahl/WestWind.WebView.HtmlToPdf/HEAD/Assets/RunningUnderIIS.png -------------------------------------------------------------------------------- /ConsoleSample/Properties/launchsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "ConsoleApp1": { 4 | "commandName": "Project" 5 | } 6 | } 7 | } -------------------------------------------------------------------------------- /Westwind.HtmlToPdf.Test/PdfSampleFile.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RickStrahl/WestWind.WebView.HtmlToPdf/HEAD/Westwind.HtmlToPdf.Test/PdfSampleFile.pdf -------------------------------------------------------------------------------- /AspNetSample/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Westwind.WebView.HtmlToPdf/PdfPrintOutputModes.cs: -------------------------------------------------------------------------------- 1 | namespace Westwind.WebView.HtmlToPdf 2 | { 3 | internal enum PdfPrintOutputModes 4 | { 5 | File, 6 | Stream 7 | } 8 | } -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: RickStrahl 2 | custom: "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=K677THUA2MJSE&source=url" 3 | custom: "https://store.west-wind.com/product/donation" -------------------------------------------------------------------------------- /AspNetSample/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /AspNetSample/Program.cs: -------------------------------------------------------------------------------- 1 | var builder = WebApplication.CreateBuilder(args); 2 | 3 | // Add services to the container. 4 | 5 | builder.Services.AddControllers(); 6 | 7 | var app = builder.Build(); 8 | 9 | // Configure the HTTP request pipeline. 10 | 11 | app.UseAuthorization(); 12 | 13 | app.MapControllers(); 14 | 15 | app.Run(); 16 | -------------------------------------------------------------------------------- /AspNetSample/WebApplication1.http: -------------------------------------------------------------------------------- 1 | @WebApplication1_HostAddress=http://localhost:5063 2 | 3 | GET http://localhost:5063/pdf HTTP/2.0 4 | Accept: application/json 5 | Websurge-Request-Name: PDF as Json 6 | 7 | ### 8 | 9 | GET http://localhost:5063/pdf/rawpdf HTTP/2.0 10 | Accept-Encoding: gzip,deflate 11 | Websurge-Request-Name: Direct PDF access 12 | 13 | ### 14 | 15 | GET http://localhost:5063/pdf/ping HTTP/2.0 16 | Accept-Encoding: gzip,deflate 17 | Websurge-Request-Name: Ping Info 18 | 19 | ### 20 | 21 | -------------------------------------------------------------------------------- /Westwind.WebView.HtmlToPdf/publish-nuget.ps1: -------------------------------------------------------------------------------- 1 | 2 | if (test-path ./nupkg) { 3 | remove-item ./nupkg -Force -Recurse 4 | } 5 | 6 | dotnet build -c Release 7 | 8 | # $filename = 'LiveReloadServer.0.2.4.nupkg' 9 | $filename = gci "./nupkg/*.nupkg" | sort LastWriteTime | select -last 1 | select -ExpandProperty "Name" 10 | 11 | 12 | $len = $filename.length 13 | 14 | if ($len -gt 0) { 15 | Write-Host "Signing... $filename" 16 | nuget sign ".\nupkg\$filename" -CertificateSubject "West Wind Technologies" -timestamper " http://timestamp.digicert.com" 17 | nuget push ".\nupkg\$filename" -source "https://nuget.org" 18 | } -------------------------------------------------------------------------------- /AspNetSample/web.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /AspNetSample/AspNetSample.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0-windows 5 | 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | PreserveNewest 16 | 17 | 18 | PreserveNewest 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /Westwind.WebView.HtmlToPdf/Enums.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Westwind.WebView.HtmlToPdf 8 | { 9 | public enum WebViewPrintColorModes 10 | { 11 | Color, 12 | Grayscale, 13 | } 14 | 15 | public enum WebViewPrintOrientations 16 | { 17 | Portrait, 18 | Landscape 19 | } 20 | 21 | public enum WebViewPrintCollations 22 | { 23 | Default, 24 | Collated, 25 | UnCollated 26 | } 27 | 28 | public enum WebViewPrintDuplexes 29 | { 30 | Default, 31 | OneSided, 32 | TwoSidedLongEdge, 33 | TwoSidedShortEdge 34 | 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /ConsoleSample/ConsoleSample.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0-windows 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | PreserveNewest 21 | 22 | 23 | PreserveNewest 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /AspNetSample/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:28181", 8 | "sslPort": 0 9 | } 10 | }, 11 | "profiles": { 12 | "http": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "pdf/rawpdf", 17 | "applicationUrl": "http://localhost:5063", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "weatherforecast", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | =========== 3 | 4 | Copyright (c) 2024, West Wind Technologies 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. -------------------------------------------------------------------------------- /Westwind.WebView.HtmlToPdf/PdfPrintResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | 4 | namespace Westwind.WebView.HtmlToPdf 5 | { 6 | 7 | /// 8 | /// Result from a Print to PDF operation. ResultStream is set only 9 | /// on stream operations. 10 | /// 11 | public class PdfPrintResult 12 | { 13 | /// 14 | /// Notifies of sucess or failure of operation 15 | /// 16 | public bool IsSuccess { get; set; } 17 | 18 | /// 19 | /// If in stream mode, the resulting MemoryStream will be assigned 20 | /// to this property. You need to close/dispose of this stream when 21 | /// done with it. 22 | /// 23 | public Stream ResultStream { get; set; } 24 | 25 | /// 26 | /// A message related to the operation - use for error messages if 27 | /// an error occured. 28 | /// 29 | public string Message { get; set; } 30 | 31 | /// 32 | /// The exception that triggered a failed PDF conversion operation 33 | /// 34 | public Exception LastException { get; set; } 35 | } 36 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Westwind.WebView.HtmlToPdf 2 | 3 | ### C# library for WebView2 Html to Pdf Generation 4 | 5 | > [!IMPORTANT] 6 | > This functionality library has been moved into the [Westwind.WebView](https://github.com/RickStrahl/Westwind.WebView) library, keeping feature and syntax compatibility. If you're using existing functionality you can switch to the new NuGet package and remove the old one. 7 | > 8 | > To get source code or get involved please go to: 9 | > * [Westwind.WebView on GitHub](https://github.com/RickStrahl/Westwind.WebView) 10 | > 11 | > This repository is deprecated. 12 | 13 | --- 14 | 15 | 16 | | Library | Nuget Package | 17 | |----------------|----------------| 18 | | Westwind.WebView | [![](https://img.shields.io/nuget/v/Westwind.WebView.svg)](https://www.nuget.org/packages/Westwind.WebView/) [![](https://img.shields.io/nuget/dt/Westwind.WebView.svg)](https://www.nuget.org/packages/Westwind.WebView/) | 19 | | ~~Westwind.WebView.HtmlToPdf (deprecated)~~ | [![](https://img.shields.io/nuget/v/Westwind.WebView.HtmlToPdf.svg)](https://www.nuget.org/packages/Westwind.WebView.HtmlToPdf/) [![](https://img.shields.io/nuget/dt/Westwind.WebView.HtmlToPdf.svg)](https://www.nuget.org/packages/Westwind.WebView.HtmlToPdf/) | 20 | -------------------------------------------------------------------------------- /Westwind.HtmlToPdf.Test/Westwind.HtmlToPdf.Test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net8.0-windows;net472 4 | false 5 | true 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | NETCORE; 19 | 20 | 21 | NETFULL 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | PreserveNewest 30 | 31 | 32 | PreserveNewest 33 | 34 | 35 | Always 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Westwind.WebView.HtmlToPdf/Westwind.WebView.HtmlToPdf.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 0.12 5 | net8.0-windows;net6.0-windows;net472 6 | Latest 7 | True 8 | Rick Strahl 9 | West Wind Technologies 10 | West Wind WebView Html To PDF 11 | Westwind WebView Html to Pdf 12 | (c) West Wind Technologies, 2024 13 | 14 | 15 | 16 | embedded 17 | True 18 | ./nupkg 19 | 20 | Rick Strahl, West Wind Technologies 2024 21 | Westwind Pdf Html WebView 22 | https://github.com/RickStrahl/Westwind.WebView.HtmlToPdf 23 | https://github.com/RickStrahl/Westwind.WebView.HtmlToPdf 24 | Github 25 | 26 | icon.png 27 | LICENSE.md 28 | README.md 29 | 30 | 31 | 32 | NETCORE; 33 | 34 | 35 | NETFULL 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /AspNetSample/WebApplication1.websurge: -------------------------------------------------------------------------------- 1 | GET pdf HTTP/2.0 2 | Accept: application/json 3 | Websurge-Request-Name: PDF as Json 4 | 5 | ------------------------------------------------------------------ 6 | 7 | GET pdf/rawpdf HTTP/2.0 8 | Accept-Encoding: gzip,deflate 9 | Websurge-Request-Name: Direct PDF access 10 | 11 | ------------------------------------------------------------------ 12 | 13 | GET pdf/pdffromurl?url=https://microsoft.com HTTP/2.0 14 | Accept-Encoding: gzip,deflate 15 | Websurge-Request-Name: Direct PDF access EX 16 | 17 | ------------------------------------------------------------------ 18 | 19 | GET pdf/ping HTTP/2.0 20 | Accept-Encoding: gzip,deflate 21 | Websurge-Request-Name: Ping Info 22 | 23 | ------------------------------------------------------------------ 24 | 25 | 26 | ----- Start WebSurge Options ----- 27 | 28 | { 29 | "SiteBaseUrl": "http://localhost/PdfWebApp/", 30 | "RecentSiteBaseUrlList": [ 31 | "http://localhost/PdfWebApp/", 32 | "http://localhost:5063/" 33 | ], 34 | "OnlineSessionId": null, 35 | "SessionVariables": { 36 | "WebApplication1_HostAddress": "http://localhost:5063" 37 | }, 38 | "UseCustomUsers": true, 39 | "HttpProtocolVersion": "1.1", 40 | "IgnoreCertificateErrors": false, 41 | "NoContentDecompression": false, 42 | "UpdateHeadersFromRequest": false, 43 | "SecondsToRun": 60, 44 | "ThreadCount": 2, 45 | "DelayTimeMs": 0, 46 | "WarmupSeconds": 2, 47 | "RequestTimeoutMs": 15000, 48 | "RandomizeRequests": false, 49 | "MaxConnections": 100, 50 | "NoProgressEvents": false, 51 | "RemoveStartAndEndPercentile": 0, 52 | "ReplaceQueryStringValuePairs": null, 53 | "ReplaceCookieValue": null, 54 | "TrackPerSessionCookies": true, 55 | "ReplaceAuthorization": null, 56 | "Username": null, 57 | "Password": null, 58 | "UsernamePasswordType": "Negotiate", 59 | "Users": [], 60 | "UserAgent": null, 61 | "CaptureMinimalResponseData": false, 62 | "MaxResponseSize": 9999999, 63 | "Documentation": [] 64 | } 65 | 66 | // This file was generated by West Wind WebSurge 67 | // Get your free copy at https://websurge.west-wind.com 68 | // to easily test or load test the requests in this file. 69 | 70 | ----- End WebSurge Options ----- 71 | 72 | -------------------------------------------------------------------------------- /Westwind.WebView.HtmlToPdf/Utilities/StreamExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | 3 | namespace System.IO 4 | { 5 | /// 6 | /// MemoryStream Extension Methods that provide conversions to and from strings 7 | /// 8 | internal static class MemoryStreamExtensions 9 | { 10 | /// 11 | /// Returns the content of the stream as a string 12 | /// 13 | /// Memory stream 14 | /// Encoding to use - defaults to Unicode 15 | /// 16 | public static string AsString(this MemoryStream ms, Encoding encoding = null) 17 | { 18 | if (encoding == null) 19 | encoding = Encoding.Unicode; 20 | 21 | return encoding.GetString(ms.ToArray()); 22 | } 23 | 24 | /// 25 | /// Writes the specified string into the memory stream 26 | /// 27 | /// 28 | /// 29 | /// 30 | public static void FromString(this MemoryStream ms, string inputString, Encoding encoding = null) 31 | { 32 | if (encoding == null) 33 | encoding = Encoding.Unicode; 34 | 35 | byte[] buffer = encoding.GetBytes(inputString); 36 | ms.Write(buffer, 0, buffer.Length); 37 | ms.Position = 0; 38 | } 39 | } 40 | 41 | /// 42 | /// Stream Extensions 43 | /// 44 | internal static class StreamExtensions 45 | { 46 | /// 47 | /// Converts a stream by copying it to a memory stream and returning 48 | /// as a string with encoding. 49 | /// 50 | /// stream to turn into a string 51 | /// Encoding of the stream. Defaults to Unicode 52 | /// string 53 | public static string AsString(this Stream s, Encoding encoding = null) 54 | { 55 | using (var ms = new MemoryStream()) 56 | { 57 | s.CopyTo(ms); 58 | s.Position = 0; 59 | return ms.AsString(encoding); 60 | } 61 | } 62 | } 63 | } -------------------------------------------------------------------------------- /ConsoleSample/Program.cs: -------------------------------------------------------------------------------- 1 | // Async or Callback 2 | //#define UseAsync 3 | 4 | using Westwind.WebView.HtmlToPdf; 5 | using Westwind.Utilities; 6 | using System; 7 | 8 | 9 | 10 | namespace ConsoleApp1 11 | { 12 | internal class Program 13 | { 14 | 15 | #if UseAsync 16 | 17 | public static async Task Main(string[] args) 18 | { 19 | Console.WriteLine("Generating Pdf file..."); 20 | 21 | string outputFile = Path.Combine("c:\\temp", "test.pdf"); 22 | File.Delete(outputFile); 23 | var pdfHost = new HtmlToPdfHost() 24 | { 25 | WebViewEnvironmentPath = "C:\\temp\\WebViewEnvironment" 26 | }; 27 | 28 | // full file path or url 29 | var result = await pdfHost.PrintToPdfAsync(Path.GetFullPath("./HtmlSampleFileLonger-SelfContained.html"), outputFile); 30 | 31 | if (result.IsSuccess) 32 | { 33 | Console.WriteLine("Opening Pdf file (async): " + outputFile); 34 | ShellUtils.OpenUrl(outputFile); 35 | }else 36 | { 37 | Console.WriteLine("Pdf generation failed: " + result.Message); 38 | } 39 | } 40 | #else 41 | // Use Events 42 | public static void Main(string[] args) 43 | { 44 | Console.WriteLine("Generating Pdf file..."); 45 | 46 | string outputFile = Path.Combine("c:\\temp", "test.pdf"); 47 | File.Delete(outputFile); 48 | 49 | // Using the non-extended version of the host (no TOC support) 50 | var pdfHost = new HtmlToPdfHost() 51 | { 52 | WebViewEnvironmentPath = "C:\\temp\\WebViewEnvironment" 53 | }; 54 | var onPrintResult = (PdfPrintResult result) => { 55 | if (result.IsSuccess) 56 | { 57 | Console.WriteLine("Opening Pdf file (Callback): " + outputFile); 58 | ShellUtils.OpenUrl(outputFile); 59 | } 60 | else 61 | { 62 | Console.WriteLine("Pdf generation failed: " + result.Message); 63 | } 64 | 65 | Environment.Exit(0); 66 | }; 67 | 68 | // full file path or url 69 | pdfHost.PrintToPdf(Path.GetFullPath("./HtmlSampleFileLonger-SelfContained.html"), outputFile, onPrintResult); 70 | 71 | // wait for completion 72 | Console.ReadKey(); 73 | } 74 | #endif 75 | } 76 | } -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /WestWind.WebView.HtmlToPdf.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.9.34701.34 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Westwind.WebView.HtmlToPdf", "WestWind.WebView.HtmlToPdf\Westwind.WebView.HtmlToPdf.csproj", "{225554B9-0288-4DC8-AE73-1F4334E2B00C}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Westwind.HtmlToPdf.Test", "Westwind.HtmlToPdf.Test\Westwind.HtmlToPdf.Test.csproj", "{413ED39E-1965-40D7-88B0-CA5DF91FDF89}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsoleSample", "ConsoleSample\ConsoleSample.csproj", "{A99DB5D0-033E-4221-8C38-5331DD439486}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "TestAndSamples", "TestAndSamples", "{AD40CB9C-37A2-497A-AB59-E0D634A2FF20}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AspNetSample", "AspNetSample\AspNetSample.csproj", "{0EF5064B-FA8C-4B52-B064-4F60F43FACFC}" 15 | EndProject 16 | Global 17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 18 | Debug|Any CPU = Debug|Any CPU 19 | Release|Any CPU = Release|Any CPU 20 | EndGlobalSection 21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 22 | {225554B9-0288-4DC8-AE73-1F4334E2B00C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {225554B9-0288-4DC8-AE73-1F4334E2B00C}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {225554B9-0288-4DC8-AE73-1F4334E2B00C}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {225554B9-0288-4DC8-AE73-1F4334E2B00C}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {413ED39E-1965-40D7-88B0-CA5DF91FDF89}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {413ED39E-1965-40D7-88B0-CA5DF91FDF89}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {413ED39E-1965-40D7-88B0-CA5DF91FDF89}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {413ED39E-1965-40D7-88B0-CA5DF91FDF89}.Release|Any CPU.Build.0 = Release|Any CPU 30 | {A99DB5D0-033E-4221-8C38-5331DD439486}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 31 | {A99DB5D0-033E-4221-8C38-5331DD439486}.Debug|Any CPU.Build.0 = Debug|Any CPU 32 | {A99DB5D0-033E-4221-8C38-5331DD439486}.Release|Any CPU.ActiveCfg = Release|Any CPU 33 | {A99DB5D0-033E-4221-8C38-5331DD439486}.Release|Any CPU.Build.0 = Release|Any CPU 34 | {0EF5064B-FA8C-4B52-B064-4F60F43FACFC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 35 | {0EF5064B-FA8C-4B52-B064-4F60F43FACFC}.Debug|Any CPU.Build.0 = Debug|Any CPU 36 | {0EF5064B-FA8C-4B52-B064-4F60F43FACFC}.Release|Any CPU.ActiveCfg = Release|Any CPU 37 | {0EF5064B-FA8C-4B52-B064-4F60F43FACFC}.Release|Any CPU.Build.0 = Release|Any CPU 38 | EndGlobalSection 39 | GlobalSection(SolutionProperties) = preSolution 40 | HideSolutionNode = FALSE 41 | EndGlobalSection 42 | GlobalSection(NestedProjects) = preSolution 43 | {413ED39E-1965-40D7-88B0-CA5DF91FDF89} = {AD40CB9C-37A2-497A-AB59-E0D634A2FF20} 44 | {A99DB5D0-033E-4221-8C38-5331DD439486} = {AD40CB9C-37A2-497A-AB59-E0D634A2FF20} 45 | {0EF5064B-FA8C-4B52-B064-4F60F43FACFC} = {AD40CB9C-37A2-497A-AB59-E0D634A2FF20} 46 | EndGlobalSection 47 | GlobalSection(ExtensibilityGlobals) = postSolution 48 | SolutionGuid = {1B163354-AB5A-4370-82F7-E719157ED695} 49 | EndGlobalSection 50 | EndGlobal 51 | -------------------------------------------------------------------------------- /AspNetSample/PdfController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Microsoft.Net.Http.Headers; 3 | using Westwind.WebView.HtmlToPdf; 4 | 5 | namespace WebApplication1 6 | { 7 | 8 | /// 9 | /// IMPORTANT: This works when running locally using Kestrel on the desktop 10 | /// It **does not work** inside of a system context - ie. inside of IIS without a loging 11 | /// (unless you run as INTERACTIVE) 12 | /// 13 | [ApiController] 14 | [Route("pdf")] 15 | public class PdfController : ControllerBase 16 | { 17 | /// 18 | /// Default result = return JSON object with embedded binary data 19 | /// 20 | /// 21 | [HttpGet] 22 | public async Task Get() 23 | { 24 | var file = Path.GetFullPath("./HtmlSampleFile-SelfContained.html"); 25 | 26 | var pdf = new HtmlToPdfHost(); 27 | var pdfResult = await pdf.PrintToPdfStreamAsync(file, new WebViewPrintSettings { PageRanges = "1-5"}); 28 | 29 | if (pdfResult == null || !pdfResult.IsSuccess) 30 | { 31 | return new 32 | { 33 | IsError = true, 34 | Message = pdfResult.Message 35 | }; 36 | } 37 | Response.StatusCode = 200; 38 | 39 | return new 40 | { 41 | IsError = false, 42 | PdfBytes = (pdfResult.ResultStream as MemoryStream).ToArray() 43 | }; 44 | } 45 | 46 | /// 47 | /// Return raw data as PDF 48 | /// 49 | /// 50 | [HttpGet("rawpdf")] 51 | public async Task RawPdf() 52 | { 53 | var file = Path.GetFullPath("./HtmlSampleFile-SelfContained.html"); 54 | 55 | var pdf = new HtmlToPdfHost(); 56 | var pdfResult = await pdf.PrintToPdfStreamAsync(file, new WebViewPrintSettings { PageRanges = "1-10"}); 57 | 58 | if (pdfResult == null || !pdfResult.IsSuccess) 59 | { 60 | Response.StatusCode = 500; 61 | return new JsonResult(new 62 | { 63 | isError = true, 64 | message = pdfResult.Message 65 | }); 66 | } 67 | 68 | return new FileStreamResult(pdfResult.ResultStream, "application/pdf"); 69 | } 70 | 71 | /// 72 | /// Return raw data as PDF 73 | /// 74 | /// 75 | [HttpGet("PdfFromUrl")] 76 | public async Task PdfFromUrl([FromQuery] string url) 77 | { 78 | if (string.IsNullOrEmpty(url)) 79 | url = Path.GetFullPath("./HtmlSampleFile-SelfContained.html"); 80 | 81 | var pdf = new HtmlToPdfHost(); 82 | var pdfResult = await pdf.PrintToPdfStreamAsync(url, new WebViewPrintSettings { }); 83 | 84 | if (pdfResult == null || !pdfResult.IsSuccess) 85 | { 86 | Response.StatusCode = 500; 87 | return new JsonResult(new 88 | { 89 | isError = true, 90 | message = pdfResult.Message 91 | }); 92 | } 93 | 94 | return new FileStreamResult(pdfResult.ResultStream, "application/pdf"); 95 | } 96 | 97 | /// 98 | /// Status info to ensure app works 99 | /// 100 | /// 101 | [HttpGet("ping")] 102 | public object Ping() 103 | { 104 | return new 105 | { 106 | Message = "Hello World.", 107 | Time = DateTime.Now, 108 | User = Environment.UserName, 109 | LoggedOnUser = User?.Identity?.Name 110 | }; 111 | } 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /Westwind.WebView.HtmlToPdf/Utilities/StringUtils.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Text; 4 | 5 | namespace Westwind.WebView.HtmlToPdf.Utilities 6 | { 7 | internal static class StringUtils 8 | { 9 | /// 10 | /// A helper to generate a JSON string from a string value 11 | /// 12 | /// Use this to avoid bringing in a full JSON Serializer for 13 | /// scenarios of string serialization. 14 | /// 15 | /// Note: Function includes surrounding quotes! 16 | /// 17 | /// 18 | /// JSON encoded string ("text"), empty ("") or "null". 19 | internal static string ToJson(this string text, bool noQuotes = false) 20 | { 21 | if (text is null) 22 | return "null"; 23 | 24 | var sb = new StringBuilder(text.Length); 25 | 26 | if (!noQuotes) 27 | sb.Append("\""); 28 | 29 | var ct = text.Length; 30 | 31 | for (int x = 0; x < ct; x++) 32 | { 33 | var c = text[x]; 34 | 35 | switch (c) 36 | { 37 | case '\"': 38 | sb.Append("\\\""); 39 | break; 40 | case '\\': 41 | sb.Append("\\\\"); 42 | break; 43 | case '\b': 44 | sb.Append("\\b"); 45 | break; 46 | case '\f': 47 | sb.Append("\\f"); 48 | break; 49 | case '\n': 50 | sb.Append("\\n"); 51 | break; 52 | case '\r': 53 | sb.Append("\\r"); 54 | break; 55 | case '\t': 56 | sb.Append("\\t"); 57 | break; 58 | default: 59 | uint i = c; 60 | if (i < 32) // || i > 255 61 | sb.Append($"\\u{i:x4}"); 62 | else 63 | sb.Append(c); 64 | break; 65 | } 66 | } 67 | if (!noQuotes) 68 | sb.Append("\""); 69 | 70 | return sb.ToString(); 71 | } 72 | 73 | internal static string ToJson(this double value, int maxDecimals = 2) 74 | { 75 | if (maxDecimals > -1) 76 | value = Math.Round(value, maxDecimals); 77 | 78 | return value.ToString(CultureInfo.InvariantCulture); 79 | } 80 | internal static string ToJson(this bool value) 81 | { 82 | return value ? "true" : "false"; 83 | } 84 | 85 | internal static string ExtractString(string source, 86 | string beginDelim, 87 | string endDelim, 88 | bool caseSensitive = false, 89 | bool allowMissingEndDelimiter = false, 90 | bool returnDelimiters = false) 91 | { 92 | int at1, at2; 93 | 94 | if (string.IsNullOrEmpty(source)) 95 | return string.Empty; 96 | 97 | if (caseSensitive) 98 | { 99 | at1 = source.IndexOf(beginDelim); 100 | if (at1 == -1) 101 | return string.Empty; 102 | 103 | at2 = source.IndexOf(endDelim, at1 + beginDelim.Length); 104 | } 105 | else 106 | { 107 | //string Lower = source.ToLower(); 108 | at1 = source.IndexOf(beginDelim, 0, source.Length, StringComparison.OrdinalIgnoreCase); 109 | if (at1 == -1) 110 | return string.Empty; 111 | 112 | at2 = source.IndexOf(endDelim, at1 + beginDelim.Length, StringComparison.OrdinalIgnoreCase); 113 | } 114 | 115 | if (allowMissingEndDelimiter && at2 < 0) 116 | { 117 | if (!returnDelimiters) 118 | return source.Substring(at1 + beginDelim.Length); 119 | 120 | return source.Substring(at1); 121 | } 122 | 123 | if (at1 > -1 && at2 > 1) 124 | { 125 | if (!returnDelimiters) 126 | return source.Substring(at1 + beginDelim.Length, at2 - at1 - beginDelim.Length); 127 | 128 | return source.Substring(at1, at2 - at1 + endDelim.Length); 129 | } 130 | 131 | return string.Empty; 132 | } 133 | 134 | 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /Westwind.WebView.HtmlToPdf/WebViewPrintSettings.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Web.WebView2.Core; 2 | 3 | namespace Westwind.WebView.HtmlToPdf 4 | { 5 | 6 | /// 7 | /// Proxy object of Core WebView settings options to avoid requiring 8 | /// a direct reference to the WebView control in the calling 9 | /// application/project. 10 | /// 11 | /// Settings map to these specific settings in the WebView: 12 | /// https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF 13 | /// 14 | public class WebViewPrintSettings 15 | { 16 | /// 17 | /// Scale Factor up to 2 18 | /// 19 | public float ScaleFactor 20 | { 21 | get => _scaleFactor; 22 | set 23 | { 24 | _scaleFactor = value; 25 | if (_scaleFactor > 2F) 26 | ScaleFactor = 2F; 27 | } 28 | } 29 | private float _scaleFactor = 1F; 30 | 31 | 32 | /// 33 | /// Portrait, Landscape 34 | /// 35 | public WebViewPrintOrientations Orientation { get; set; } = WebViewPrintOrientations.Portrait; 36 | 37 | /// 38 | /// Width in inches 39 | /// 40 | public double PageWidth { get; set; } = 8.5F; 41 | 42 | /// 43 | /// Height in inches 44 | /// 45 | public double PageHeight { get; set; } = 11F; 46 | 47 | 48 | /// 49 | /// Top Margin in inches 50 | /// 51 | public double MarginTop { get; set; } = 0.4F; 52 | 53 | /// 54 | /// Bottom Margin in inches 55 | /// 56 | public double MarginBottom { get; set; } = 0.30F; 57 | 58 | /// 59 | /// Left Margin in inches 60 | /// 61 | public double MarginLeft { get; set; } = 0.25F; 62 | 63 | /// 64 | /// Right Margin in inches 65 | /// 66 | public double MarginRight { get; set; } = 0.25F; 67 | 68 | 69 | /// 70 | /// Page ranges as specified 1,2,3,5-7 71 | /// 72 | public string PageRanges { get; set; } = string.Empty; 73 | 74 | 75 | /// 76 | /// Determines whether background colors are printed. Use to 77 | /// save ink on printing or for more legible in print/pdf scenarios 78 | /// 79 | public bool ShouldPrintBackgrounds { get; set; } = true; 80 | 81 | 82 | /// 83 | /// Color, Grayscale, Monochrome 84 | /// 85 | /// CURRENTLY DOESN'T WORK FOR PDF GENERATION 86 | /// 87 | public WebViewPrintColorModes ColorMode { get; set; } = WebViewPrintColorModes.Color; 88 | 89 | 90 | /// 91 | /// When true prints only the section of the document selected 92 | /// 93 | public bool ShouldPrintSelectionOnly { get; set; } = false; 94 | 95 | /// 96 | /// Determines whether headers and footers are printed 97 | /// 98 | public bool ShouldPrintHeaderAndFooter { get; set; } = false; 99 | 100 | 101 | public bool GenerateDocumentOutline { get; set; } = true; 102 | 103 | 104 | /// 105 | /// Html Template that renders the header. 106 | /// Refer to for embeddable styles and formatting: 107 | /// https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF 108 | /// 109 | public string HeaderTemplate { get; set; } = "
"; 110 | 111 | 112 | /// 113 | /// Html template that renders the footer 114 | /// Refer to for embeddable styles and formatting: 115 | /// https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF 116 | /// 117 | public string FooterTemplate { get; set; } = "
of
"; 118 | 119 | 120 | 121 | /// 122 | /// This a shortcut for the HeaderTemplate that sets the top of the page header. For more control 123 | /// set the HeaderTemplate directly. 124 | /// 125 | public string HeaderTitle { set 126 | { 127 | if (string.IsNullOrEmpty(value)) 128 | HeaderTemplate = ""; 129 | else 130 | HeaderTemplate = $"
{value}
"; 131 | } 132 | } 133 | 134 | /// 135 | /// This a shortcut for the FooterTemplate that sets the bottom of the page footer. For more control 136 | /// set the FooterTemplate directly. 137 | /// 138 | public string FooterText 139 | { 140 | set 141 | { 142 | if (string.IsNullOrEmpty(value)) 143 | FooterTemplate = ""; 144 | else 145 | FooterTemplate = $"
{value}
"; 146 | } 147 | } 148 | 149 | #region Print Settings - ignored for PDF 150 | 151 | /// 152 | /// Printer name when printing to a printer (not applicable for PDF) 153 | /// 154 | /// NO EFFECT ON PDF PRINTING 155 | /// 156 | public string PrinterName { get; set; } 157 | 158 | /// 159 | /// Number of Copies to print 160 | /// 161 | /// NO EFFECT ON PDF PRINTING 162 | /// 163 | public int Copies { get; set; } = 1; 164 | 165 | /// 166 | /// Default, OneSided, TwoSidedLongEdge, TwoSidedShortEdge 167 | /// 168 | /// NO EFFECT ON PDF PRINTING 169 | /// 170 | public WebViewPrintDuplexes Duplex { get; set; } = WebViewPrintDuplexes.Default; 171 | 172 | /// 173 | /// Default, Collated, Uncollated 174 | /// 175 | /// NO EFFECT OF PDF PRINTING 176 | /// 177 | public WebViewPrintCollations Collation { get; set; } = WebViewPrintCollations.Default; 178 | 179 | /// 180 | /// Allows multiple pages to be packed into a single page. 181 | /// 182 | /// NO EFFECT ON PDF PRINTING 183 | /// 184 | public int PagesPerSide { get; set; } = 1; 185 | 186 | #endregion 187 | } 188 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | *.bak.md 13 | *.bak 14 | 15 | # User-specific files (MonoDevelop/Xamarin Studio) 16 | *.userprefs 17 | 18 | # Mono auto generated files 19 | mono_crash.* 20 | 21 | # Build results 22 | [Dd]ebug/ 23 | [Dd]ebugPublic/ 24 | [Rr]elease/ 25 | [Rr]eleases/ 26 | x64/ 27 | x86/ 28 | [Ww][Ii][Nn]32/ 29 | [Aa][Rr][Mm]/ 30 | [Aa][Rr][Mm]64/ 31 | bld/ 32 | [Bb]in/ 33 | [Oo]bj/ 34 | [Oo]ut/ 35 | [Ll]og/ 36 | [Ll]ogs/ 37 | WebApp1_Publish/ 38 | 39 | # Visual Studio 2015/2017 cache/options directory 40 | .vs/ 41 | # Uncomment if you have tasks that create the project's static files in wwwroot 42 | #wwwroot/ 43 | 44 | # Visual Studio 2017 auto generated files 45 | Generated\ Files/ 46 | 47 | # MSTest test Results 48 | [Tt]est[Rr]esult*/ 49 | [Bb]uild[Ll]og.* 50 | 51 | # NUnit 52 | *.VisualState.xml 53 | TestResult.xml 54 | nunit-*.xml 55 | 56 | # Build Results of an ATL Project 57 | [Dd]ebugPS/ 58 | [Rr]eleasePS/ 59 | dlldata.c 60 | 61 | # Benchmark Results 62 | BenchmarkDotNet.Artifacts/ 63 | 64 | # .NET Core 65 | project.lock.json 66 | project.fragment.lock.json 67 | artifacts/ 68 | 69 | # ASP.NET Scaffolding 70 | ScaffoldingReadMe.txt 71 | 72 | # StyleCop 73 | StyleCopReport.xml 74 | 75 | # Files built by Visual Studio 76 | *_i.c 77 | *_p.c 78 | *_h.h 79 | *.ilk 80 | *.meta 81 | *.obj 82 | *.iobj 83 | *.pch 84 | *.pdb 85 | *.ipdb 86 | *.pgc 87 | *.pgd 88 | *.rsp 89 | *.sbr 90 | *.tlb 91 | *.tli 92 | *.tlh 93 | *.tmp 94 | *.tmp_proj 95 | *_wpftmp.csproj 96 | *.log 97 | *.vspscc 98 | *.vssscc 99 | .builds 100 | *.pidb 101 | *.svclog 102 | *.scc 103 | 104 | # Chutzpah Test files 105 | _Chutzpah* 106 | 107 | # Visual C++ cache files 108 | ipch/ 109 | *.aps 110 | *.ncb 111 | *.opendb 112 | *.opensdf 113 | *.sdf 114 | *.cachefile 115 | *.VC.db 116 | *.VC.VC.opendb 117 | 118 | # Visual Studio profiler 119 | *.psess 120 | *.vsp 121 | *.vspx 122 | *.sap 123 | 124 | # Visual Studio Trace Files 125 | *.e2e 126 | 127 | # TFS 2012 Local Workspace 128 | $tf/ 129 | 130 | # Guidance Automation Toolkit 131 | *.gpState 132 | 133 | # ReSharper is a .NET coding add-in 134 | _ReSharper*/ 135 | *.[Rr]e[Ss]harper 136 | *.DotSettings.user 137 | 138 | # TeamCity is a build add-in 139 | _TeamCity* 140 | 141 | # DotCover is a Code Coverage Tool 142 | *.dotCover 143 | 144 | # AxoCover is a Code Coverage Tool 145 | .axoCover/* 146 | !.axoCover/settings.json 147 | 148 | # Coverlet is a free, cross platform Code Coverage Tool 149 | coverage*.json 150 | coverage*.xml 151 | coverage*.info 152 | 153 | # Visual Studio code coverage results 154 | *.coverage 155 | *.coveragexml 156 | 157 | # NCrunch 158 | _NCrunch_* 159 | .*crunch*.local.xml 160 | nCrunchTemp_* 161 | 162 | # MightyMoose 163 | *.mm.* 164 | AutoTest.Net/ 165 | 166 | # Web workbench (sass) 167 | .sass-cache/ 168 | 169 | # Installshield output folder 170 | [Ee]xpress/ 171 | 172 | # DocProject is a documentation generator add-in 173 | DocProject/buildhelp/ 174 | DocProject/Help/*.HxT 175 | DocProject/Help/*.HxC 176 | DocProject/Help/*.hhc 177 | DocProject/Help/*.hhk 178 | DocProject/Help/*.hhp 179 | DocProject/Help/Html2 180 | DocProject/Help/html 181 | 182 | # Click-Once directory 183 | publish/ 184 | 185 | # Publish Web Output 186 | *.[Pp]ublish.xml 187 | *.azurePubxml 188 | # Note: Comment the next line if you want to checkin your web deploy settings, 189 | # but database connection strings (with potential passwords) will be unencrypted 190 | *.pubxml 191 | *.publishproj 192 | 193 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 194 | # checkin your Azure Web App publish settings, but sensitive information contained 195 | # in these scripts will be unencrypted 196 | PublishScripts/ 197 | 198 | # NuGet Packages 199 | *.nupkg 200 | # NuGet Symbol Packages 201 | *.snupkg 202 | # The packages folder can be ignored because of Package Restore 203 | **/[Pp]ackages/* 204 | # except build/, which is used as an MSBuild target. 205 | !**/[Pp]ackages/build/ 206 | # Uncomment if necessary however generally it will be regenerated when needed 207 | #!**/[Pp]ackages/repositories.config 208 | # NuGet v3's project.json files produces more ignorable files 209 | *.nuget.props 210 | *.nuget.targets 211 | 212 | # Microsoft Azure Build Output 213 | csx/ 214 | *.build.csdef 215 | 216 | # Microsoft Azure Emulator 217 | ecf/ 218 | rcf/ 219 | 220 | # Windows Store app package directories and files 221 | AppPackages/ 222 | BundleArtifacts/ 223 | Package.StoreAssociation.xml 224 | _pkginfo.txt 225 | *.appx 226 | *.appxbundle 227 | *.appxupload 228 | 229 | # Visual Studio cache files 230 | # files ending in .cache can be ignored 231 | *.[Cc]ache 232 | # but keep track of directories ending in .cache 233 | !?*.[Cc]ache/ 234 | 235 | # Others 236 | ClientBin/ 237 | ~$* 238 | *~ 239 | *.dbmdl 240 | *.dbproj.schemaview 241 | *.jfm 242 | *.pfx 243 | *.publishsettings 244 | orleans.codegen.cs 245 | 246 | # Including strong name files can present a security risk 247 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 248 | #*.snk 249 | 250 | # Since there are multiple workflows, uncomment next line to ignore bower_components 251 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 252 | #bower_components/ 253 | 254 | # RIA/Silverlight projects 255 | Generated_Code/ 256 | 257 | # Backup & report files from converting an old project file 258 | # to a newer Visual Studio version. Backup files are not needed, 259 | # because we have git ;-) 260 | _UpgradeReport_Files/ 261 | Backup*/ 262 | UpgradeLog*.XML 263 | UpgradeLog*.htm 264 | ServiceFabricBackup/ 265 | *.rptproj.bak 266 | 267 | # SQL Server files 268 | *.mdf 269 | *.ldf 270 | *.ndf 271 | 272 | # Business Intelligence projects 273 | *.rdl.data 274 | *.bim.layout 275 | *.bim_*.settings 276 | *.rptproj.rsuser 277 | *- [Bb]ackup.rdl 278 | *- [Bb]ackup ([0-9]).rdl 279 | *- [Bb]ackup ([0-9][0-9]).rdl 280 | 281 | # Microsoft Fakes 282 | FakesAssemblies/ 283 | 284 | # GhostDoc plugin setting file 285 | *.GhostDoc.xml 286 | 287 | # Node.js Tools for Visual Studio 288 | .ntvs_analysis.dat 289 | node_modules/ 290 | 291 | # Visual Studio 6 build log 292 | *.plg 293 | 294 | # Visual Studio 6 workspace options file 295 | *.opt 296 | 297 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 298 | *.vbw 299 | 300 | # Visual Studio LightSwitch build output 301 | **/*.HTMLClient/GeneratedArtifacts 302 | **/*.DesktopClient/GeneratedArtifacts 303 | **/*.DesktopClient/ModelManifest.xml 304 | **/*.Server/GeneratedArtifacts 305 | **/*.Server/ModelManifest.xml 306 | _Pvt_Extensions 307 | 308 | # Paket dependency manager 309 | .paket/paket.exe 310 | paket-files/ 311 | 312 | # FAKE - F# Make 313 | .fake/ 314 | 315 | # CodeRush personal settings 316 | .cr/personal 317 | 318 | # Python Tools for Visual Studio (PTVS) 319 | __pycache__/ 320 | *.pyc 321 | 322 | # Cake - Uncomment if you are using it 323 | # tools/** 324 | # !tools/packages.config 325 | 326 | # Tabs Studio 327 | *.tss 328 | 329 | # Telerik's JustMock configuration file 330 | *.jmconfig 331 | 332 | # BizTalk build output 333 | *.btp.cs 334 | *.btm.cs 335 | *.odx.cs 336 | *.xsd.cs 337 | 338 | # OpenCover UI analysis results 339 | OpenCover/ 340 | 341 | # Azure Stream Analytics local run output 342 | ASALocalRun/ 343 | 344 | # MSBuild Binary and Structured Log 345 | *.binlog 346 | 347 | # NVidia Nsight GPU debugger configuration file 348 | *.nvuser 349 | 350 | # MFractors (Xamarin productivity tool) working folder 351 | .mfractor/ 352 | 353 | # Local History for Visual Studio 354 | .localhistory/ 355 | 356 | # BeatPulse healthcheck temp database 357 | healthchecksdb 358 | 359 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 360 | MigrationBackup/ 361 | 362 | # Ionide (cross platform F# VS Code tools) working folder 363 | .ionide/ 364 | 365 | # Fody - auto-generated XML schema 366 | FodyWeavers.xsd -------------------------------------------------------------------------------- /Westwind.HtmlToPdf.Test/PrintToPdfTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.IO; 4 | using System.Text.RegularExpressions; 5 | using System.Threading.Tasks; 6 | using Microsoft.VisualStudio.TestTools.UnitTesting; 7 | using Westwind.Utilities; 8 | using Westwind.WebView.HtmlToPdf; 9 | 10 | namespace Westwind.PdfToHtml.Test 11 | { 12 | 13 | [TestClass] 14 | public class PrintToPdfTests 15 | { 16 | /// 17 | /// Async Result operation - to file 18 | /// 19 | [TestMethod] 20 | public async Task PrintToPdfFileAsyncTest() 21 | { 22 | // File or URL to render 23 | //var url = "file:///C:/temp/TMPLOCAL/_MarkdownMonster_Preview.html"; 24 | //var url = "C:\\temp\\TestReport.html"; 25 | var url = Path.GetFullPath("HtmlSampleFileLonger-SelfContained.html"); 26 | 27 | 28 | var htmlFile = url; 29 | var outputFile = Path.GetFullPath(@".\test2.pdf"); 30 | 31 | File.Delete(outputFile); 32 | 33 | var host = new HtmlToPdfHost() 34 | { 35 | BackgroundHtmlColor = "#ffffff" 36 | }; 37 | host.CssAndScriptOptions.KeepTextTogether = true; 38 | host.CssAndScriptOptions.CssToInject = "h1 { color: red } h2 { color: green } h3 { color: goldenrod }"; 39 | 40 | var pdfPrintSettings = new WebViewPrintSettings() 41 | { 42 | // margins are 0.4F default 43 | MarginTop = 0.5, 44 | MarginBottom = 0.3F, 45 | //ScaleFactor = 0.9F, 46 | 47 | ShouldPrintHeaderAndFooter = true, 48 | HeaderTitle = "Custom Header (centered)", 49 | FooterText = "Custom Footer (lower right)", 50 | 51 | // Optionally customize the header and footer completely - WebView syntax 52 | // HeaderTemplate = "
", 53 | // FooterTemplate = "
of " + 54 | // "
", 55 | 56 | GenerateDocumentOutline = true // default 57 | }; 58 | 59 | // output file is created 60 | var result = await host.PrintToPdfAsync(htmlFile, outputFile, pdfPrintSettings); 61 | 62 | Assert.IsTrue(result.IsSuccess, result.Message); 63 | ShellUtils.OpenUrl(outputFile); // display it 64 | } 65 | 66 | 67 | 68 | /// 69 | /// Async Result Operation - to stream 70 | /// 71 | [TestMethod] 72 | public async Task PrintToPdfStreamAsyncTest() 73 | { 74 | var outputFile = Path.GetFullPath(@".\test3.pdf"); 75 | var htmlFile = Path.GetFullPath("HtmlSampleFileLonger-SelfContained.html"); 76 | 77 | var host = new HtmlToPdfHost() 78 | { 79 | BackgroundHtmlColor = "#ffffff" 80 | }; 81 | host.CssAndScriptOptions.KeepTextTogether = true; 82 | 83 | var pdfPrintSettings = new WebViewPrintSettings() 84 | { 85 | // margins are 0.4F default 86 | MarginTop = 0.5, 87 | MarginBottom = 0.3F, 88 | ScaleFactor = 0.9F, // 1 is default 89 | 90 | ShouldPrintHeaderAndFooter = true, 91 | HeaderTitle = "Custom Header (centered)", 92 | FooterText = "Custom Footer (lower right)", 93 | 94 | // Optionally customize the header and footer completely - WebView syntax 95 | // HeaderTemplate = "
", 96 | // FooterTemplate = "
of " + 97 | // "
", 98 | 99 | GenerateDocumentOutline = true // default 100 | }; 101 | 102 | // We're interested in result.ResultStream 103 | var result = await host.PrintToPdfStreamAsync(htmlFile, pdfPrintSettings); 104 | 105 | Assert.IsTrue(result.IsSuccess, result.Message); 106 | Assert.IsNotNull(result.ResultStream); // THIS 107 | 108 | // Copy resultstream to output file 109 | File.Delete(outputFile); 110 | using (var fstream = new FileStream(outputFile, FileMode.OpenOrCreate, FileAccess.Write)) 111 | { 112 | result.ResultStream.CopyTo(fstream); 113 | result.ResultStream.Close(); // Close returned stream! 114 | } 115 | ShellUtils.OpenUrl(outputFile); 116 | } 117 | 118 | /// 119 | /// Event callback on completion - to stream (in-memory) 120 | /// 121 | /// 122 | /// Using async here only to facilitate waiting for completion. 123 | /// actual call does not require async calling method 124 | /// 125 | [TestMethod] 126 | public async Task PrintToPdfStreamTest() 127 | { 128 | // File or URL 129 | var htmlFile = Path.GetFullPath("HtmlSampleFile-SelfContained.html"); 130 | 131 | var tcs = new TaskCompletionSource(); 132 | 133 | var host = new HtmlToPdfHost(); 134 | Action onPrintComplete = (result) => 135 | { 136 | if (result.IsSuccess) 137 | { 138 | // create file so we can display 139 | var outputFile = Path.GetFullPath(@".\test1.pdf"); 140 | File.Delete(outputFile); 141 | 142 | using (var fstream = new FileStream(outputFile, FileMode.OpenOrCreate, FileAccess.Write)) 143 | { 144 | result.ResultStream.CopyTo(fstream); 145 | 146 | result.ResultStream.Close(); // Close returned stream! 147 | Assert.IsTrue(true); 148 | ShellUtils.OpenUrl(outputFile); 149 | } 150 | } 151 | else 152 | { 153 | Assert.Fail(result.Message); 154 | } 155 | 156 | tcs.SetResult(true); 157 | }; 158 | var pdfPrintSettings = new WebViewPrintSettings() 159 | { 160 | // default margins are 0.4F 161 | MarginBottom = 0.2F, 162 | MarginLeft = 0.2f, 163 | MarginRight = 0.2f, 164 | MarginTop = 0.4f, 165 | ScaleFactor = 0.8f, 166 | PageRanges = "1,2,5-8" 167 | }; 168 | // doesn't wait for completion 169 | host.PrintToPdfStream(htmlFile, onPrintComplete, pdfPrintSettings); 170 | 171 | 172 | // wait for completion 173 | await tcs.Task; 174 | } 175 | 176 | /// 177 | /// Event callback on completion - to file 178 | /// 179 | /// 180 | /// Using async here only to facilitate waiting for completion. 181 | /// actual call does not require async calling method 182 | /// 183 | [TestMethod] 184 | public async Task PrintToPdfFileTest() 185 | { 186 | // File or URL 187 | var htmlFile = Path.GetFullPath("HtmlSampleFile-SelfContained.html"); 188 | // Full Path to output file 189 | var outputFile = Path.GetFullPath(@".\test.pdf"); 190 | File.Delete(outputFile); 191 | 192 | var tcs = new TaskCompletionSource(); 193 | 194 | var host = new HtmlToPdfHost(); 195 | 196 | Action onPrintComplete = (result) => 197 | { 198 | if (result.IsSuccess) 199 | { 200 | Assert.IsTrue(true); 201 | ShellUtils.OpenUrl(outputFile); 202 | } 203 | else 204 | { 205 | Assert.Fail(result.Message); 206 | } 207 | 208 | tcs.SetResult(true); 209 | }; 210 | 211 | // doesn't wait for completion 212 | host.PrintToPdf(htmlFile, outputFile, onPrintComplete); 213 | 214 | // wait for completion 215 | await tcs.Task; 216 | } 217 | 218 | 219 | [TestMethod] 220 | public async Task InjectedCssTest() 221 | { 222 | var outputFile = Path.GetFullPath(@".\test3.pdf"); 223 | var htmlFile = Path.GetFullPath("HtmlSampleFileLonger-SelfContained.html"); 224 | 225 | var host = new HtmlToPdfHost(); 226 | //host.CssAndScriptOptions.KeepTextTogether = true; 227 | host.CssAndScriptOptions.OptimizePdfFonts = true; // force built-in OS fonts (Segoe UI, apple-system, Helvetica) 228 | host.CssAndScriptOptions.CssToInject = "h1 { color: red } h2 { color: green } h3 { color: goldenrod }"; 229 | 230 | // We're interested in result.ResultStream 231 | var result = await host.PrintToPdfStreamAsync(htmlFile); 232 | 233 | Assert.IsTrue(result.IsSuccess, result.Message); 234 | Assert.IsNotNull(result.ResultStream); // THIS 235 | 236 | // Copy resultstream to output file 237 | File.Delete(outputFile); 238 | using (var fstream = new FileStream(outputFile, FileMode.OpenOrCreate, FileAccess.Write)) 239 | { 240 | result.ResultStream.CopyTo(fstream); 241 | result.ResultStream.Close(); // Close returned stream! 242 | } 243 | ShellUtils.OpenUrl(outputFile); 244 | } 245 | 246 | 247 | [TestMethod] 248 | public async Task PrintToPdfDarkMarginsFileAsyncTest() 249 | { 250 | // File or URL to render 251 | //var url = "file:///C:/temp/TMPLOCAL/_MarkdownMonster_Preview.html"; 252 | //var url = "C:\\temp\\TestReport.html"; 253 | var url = Path.GetFullPath("HtmlSampleFileLonger-SelfContained.html"); 254 | 255 | 256 | var htmlFile = url; 257 | var outputFile = Path.GetFullPath(@".\test2.pdf"); 258 | 259 | File.Delete(outputFile); 260 | 261 | var host = new HtmlToPdfHost() 262 | { 263 | BackgroundHtmlColor = "#111" 264 | }; 265 | host.CssAndScriptOptions.KeepTextTogether = true; 266 | 267 | var pdfPrintSettings = new WebViewPrintSettings() 268 | { 269 | // margins are 0.4F default 270 | MarginTop = 0.5, 271 | MarginBottom = 0.5F, 272 | //ScaleFactor = 0.9F, 273 | 274 | // Custom Templates required for dark background so we can set text color 275 | ShouldPrintHeaderAndFooter = true, 276 | HeaderTemplate = "
", 277 | FooterTemplate = "
of " + 278 | "
", 279 | 280 | 281 | GenerateDocumentOutline = true // default 282 | }; 283 | 284 | // output file is created 285 | var result = await host.PrintToPdfAsync(htmlFile, outputFile, pdfPrintSettings); 286 | 287 | Assert.IsTrue(result.IsSuccess, result.Message); 288 | ShellUtils.OpenUrl(outputFile); // display it 289 | } 290 | 291 | 292 | [TestMethod] 293 | public void SettingsCultureJsonSerializationTests() 294 | { 295 | string expectedScale = "1.22"; 296 | // Arrange 297 | var settings = new DevToolsPrintToPdfSettings 298 | { 299 | scale = 1.22, 300 | 301 | }; 302 | CultureInfo.CurrentCulture = new CultureInfo("de-de"); 303 | 304 | // Act 305 | var json = settings.ToJson(); 306 | 307 | Console.WriteLine(json); 308 | 309 | // Assert 310 | Assert.IsTrue(json.Contains($"\"scale\": {expectedScale}")); 311 | } 312 | 313 | } 314 | } -------------------------------------------------------------------------------- /Westwind.WebView.HtmlToPdf/CoreWebViewHeadlessHost.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Web.WebView2.Core; 2 | using System; 3 | using System.Diagnostics; 4 | using System.Drawing; 5 | using System.Globalization; 6 | using System.IO; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | using Westwind.WebView.HtmlToPdf.Utilities; 10 | 11 | 12 | namespace Westwind.WebView.HtmlToPdf 13 | { 14 | 15 | /// 16 | /// This class provides the invisible WebView instance used to 17 | /// print the PDF. 18 | /// 19 | internal class CoreWebViewHeadlessHost 20 | { 21 | /// 22 | /// The internal print settings picked up from the passed in host 23 | /// 24 | internal WebViewPrintSettings WebViewPrintSettings { get; set; } = new WebViewPrintSettings(); 25 | 26 | private string _outputFile { get; set; } 27 | 28 | /// 29 | /// Passed in high level host 30 | /// 31 | internal HtmlToPdfHost HtmlToPdfHost { get; set; } 32 | 33 | 34 | 35 | internal bool IsSuccess { get; set; } = false; 36 | 37 | internal Exception LastException { get; set; } 38 | 39 | internal Stream ResultStream { get; set; } 40 | 41 | //internal Color Color { get; set; } = Color.White; 42 | 43 | /// 44 | /// Determines when PDF output generation is complete 45 | /// 46 | internal bool IsComplete { get; set; } 47 | 48 | /// 49 | /// The internal WebView instance we load and print from 50 | /// 51 | CoreWebView2 WebView { get; set; } 52 | 53 | private PdfPrintOutputModes PdfPrintOutputMode { get; set; } = PdfPrintOutputModes.File; 54 | 55 | protected TaskCompletionSource IsInitializedTaskCompletionSource = new TaskCompletionSource(); 56 | 57 | internal CoreWebViewHeadlessHost(HtmlToPdfHost htmlToPdfHost) 58 | { 59 | HtmlToPdfHost = htmlToPdfHost; 60 | WebViewPrintSettings = htmlToPdfHost.WebViewPrintSettings; 61 | InitializeAsync(); 62 | } 63 | 64 | private IntPtr HWND_MESSAGE = new IntPtr(-3); 65 | 66 | protected async void InitializeAsync() 67 | { 68 | // must create a data folder if running out of a secured folder that can't write like Program Files 69 | var environment = await CoreWebView2Environment.CreateAsync(userDataFolder: HtmlToPdfHost.WebViewEnvironmentPath); 70 | 71 | var controller = await environment.CreateCoreWebView2ControllerAsync(HWND_MESSAGE); 72 | controller.DefaultBackgroundColor = ColorTranslator.FromHtml(HtmlToPdfHost.BackgroundHtmlColor ?? "white"); 73 | 74 | WebView = controller.CoreWebView2; 75 | WebView.DOMContentLoaded += CoreWebView2_DOMContentLoaded; 76 | 77 | // Ensure that control is initialized before we can navigate! 78 | IsInitializedTaskCompletionSource.SetResult(true); 79 | } 80 | 81 | 82 | 83 | /// 84 | /// Internally navigates the the browser to the document to render 85 | /// 86 | /// 87 | /// 88 | /// 89 | internal async Task PrintFromUrl(string url, string outputFile) 90 | { 91 | await IsInitializedTaskCompletionSource.Task; 92 | 93 | PdfPrintOutputMode = PdfPrintOutputModes.File; 94 | _outputFile = outputFile; 95 | WebView.Navigate(url); 96 | } 97 | 98 | /// 99 | /// Internally navigates t 100 | /// 101 | /// 102 | /// 103 | public async Task PrintFromUrlStream(string url) 104 | { 105 | // Can't navigate until initialized 106 | await IsInitializedTaskCompletionSource.Task; 107 | 108 | PdfPrintOutputMode = PdfPrintOutputModes.Stream; 109 | WebView.Navigate(url); 110 | } 111 | 112 | /// 113 | /// Prints from an HTML stream. This allows HTML to be generated from 114 | /// in-memory sources 115 | /// 116 | /// 117 | /// 118 | public async Task PrintFromHtmlStreamToStream(Stream htmlStream, Encoding encoding = null) 119 | { 120 | if (encoding == null) 121 | encoding = Encoding.UTF8; 122 | 123 | // Can't navigate until initialized 124 | await IsInitializedTaskCompletionSource.Task; 125 | 126 | WebView.Navigate("about:blank"); 127 | 128 | PdfPrintOutputMode = PdfPrintOutputModes.Stream; 129 | htmlStream.Position = 0; 130 | string html = htmlStream.AsString(encoding); 131 | 132 | 133 | string encodedHtml = html.ToJson(); 134 | string script = "window.document.write(" + encodedHtml + ")"; 135 | 136 | try 137 | { 138 | await WebView.ExecuteScriptAsync(script); 139 | } 140 | catch(Exception ex) 141 | { 142 | this.LastException = ex; 143 | } 144 | } 145 | 146 | 147 | 148 | private async void CoreWebView2_DOMContentLoaded(object sender, Microsoft.Web.WebView2.Core.CoreWebView2DOMContentLoadedEventArgs e) 149 | { 150 | try 151 | { 152 | await InjectCssAndScript(); 153 | 154 | if (PdfPrintOutputMode == PdfPrintOutputModes.File) 155 | await PrintToPdf(); 156 | else 157 | await PrintToPdfStream(); 158 | } 159 | finally 160 | { 161 | IsComplete = true; 162 | HtmlToPdfHost.IsCompleteTaskCompletionSource.SetResult(true); 163 | } 164 | } 165 | 166 | private async Task InjectCssAndScript() 167 | { 168 | var css = new StringBuilder(); 169 | 170 | if (HtmlToPdfHost.CssAndScriptOptions.OptimizePdfFonts) 171 | { 172 | css.AppendLine(OptimizedFontCss); 173 | } 174 | if (HtmlToPdfHost.CssAndScriptOptions.KeepTextTogether) 175 | { 176 | css.AppendLine(PageBreakCss); 177 | } 178 | if (!string.IsNullOrEmpty(HtmlToPdfHost.CssAndScriptOptions.CssToInject)) 179 | { 180 | css.AppendLine(HtmlToPdfHost.CssAndScriptOptions.CssToInject); 181 | } 182 | 183 | 184 | if (css.Length > 0) 185 | { 186 | var script = "document.head.appendChild(document.createElement('style')).innerHTML = " + StringUtils.ToJson(css.ToString()) + ";"; 187 | await WebView.ExecuteScriptAsync(script); 188 | } 189 | } 190 | 191 | 192 | 193 | /// 194 | /// Prints PDF to an output file 195 | /// 196 | /// 197 | internal async Task PrintToPdf() 198 | { 199 | if (File.Exists(_outputFile)) 200 | File.Delete(_outputFile); 201 | 202 | try 203 | { 204 | if (File.Exists(_outputFile)) 205 | File.Delete(_outputFile); 206 | 207 | // https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF 208 | //{ 209 | // "landscape": false, 210 | // "printBackground": true, 211 | // "scale": 1, 212 | // "paperWidth": 8.5, 213 | // "paperHeight": 11, 214 | // "marginTop": 0.50, 215 | // "marginBottom": 0.30, 216 | // "marginLeft": 0.40, 217 | // "marginRight": 0.40, 218 | // "pageRanges": "", 219 | // "headerTemplate": "
", 220 | // "footerTemplate": "
of
", 221 | // "displayHeaderFooter": true, 222 | // "preferCSSPageSize": false, 223 | // "generateDocumentOutline": true 224 | //} 225 | 226 | if (HtmlToPdfHost.DelayPdfGenerationMs > 0) 227 | { 228 | await Task.Delay(HtmlToPdfHost.DelayPdfGenerationMs); 229 | } 230 | 231 | var json = GetDevToolsWebViewPrintSettingsJson(); 232 | var pdfBase64 = await WebView.CallDevToolsProtocolMethodAsync("Page.printToPDF", json); 233 | 234 | if (!string.IsNullOrEmpty(pdfBase64)) 235 | { 236 | // avoid JSON Serializer Dependency 237 | var b64Data = StringUtils.ExtractString(pdfBase64,"\"data\":\"","\"}"); 238 | var pdfData = Convert.FromBase64String(b64Data); 239 | File.WriteAllBytes(_outputFile, pdfData); // 240 | } 241 | 242 | //await WebView.PrintToPdfAsync(_outputFile, webViewPrintSettings); 243 | 244 | if (File.Exists(_outputFile)) 245 | IsSuccess = true; 246 | else 247 | IsSuccess = false; 248 | } 249 | catch (Exception ex) 250 | { 251 | IsSuccess = false; 252 | LastException = ex; 253 | } 254 | } 255 | 256 | 257 | 258 | 259 | /// 260 | /// Prints the current document in the WebView to a MemoryStream 261 | /// 262 | /// 263 | internal async Task PrintToPdfStream() 264 | { 265 | try 266 | { 267 | var json = GetDevToolsWebViewPrintSettingsJson(); 268 | Console.WriteLine(json); 269 | var pdfBase64 = await WebView.CallDevToolsProtocolMethodAsync("Page.printToPDF", json); 270 | 271 | if (!string.IsNullOrEmpty(pdfBase64)) 272 | { 273 | // avoid JSON Serializer Dependency 274 | var b64Data = StringUtils.ExtractString(pdfBase64, "\"data\":\"", "\"}"); 275 | var pdfData = Convert.FromBase64String(b64Data); 276 | 277 | var ms = new MemoryStream(pdfData); 278 | ResultStream = ms; 279 | IsSuccess = true; 280 | return ResultStream; 281 | } 282 | 283 | IsSuccess = false; 284 | LastException = new InvalidOperationException("No PDF output was generated."); 285 | return null; 286 | } 287 | catch (Exception ex) 288 | { 289 | IsSuccess = false; 290 | LastException = ex; 291 | return null; 292 | } 293 | } 294 | 295 | /// 296 | /// Map our private type to the CoreWebView type. 297 | /// 298 | /// 299 | 300 | private CoreWebView2PrintSettings GetWebViewPrintSettings() 301 | { 302 | var wvps = WebView.Environment.CreatePrintSettings(); 303 | 304 | var ps = WebViewPrintSettings; 305 | 306 | wvps.ScaleFactor = ps.ScaleFactor; 307 | wvps.MarginTop = ps.MarginTop; 308 | wvps.MarginBottom = ps.MarginBottom; 309 | wvps.MarginLeft = ps.MarginLeft; 310 | wvps.MarginRight = ps.MarginRight; 311 | 312 | wvps.PageWidth = ps.PageWidth; 313 | wvps.PageHeight = ps.PageHeight; 314 | 315 | wvps.Copies = ps.Copies; 316 | wvps.PageRanges = ps.PageRanges; 317 | 318 | wvps.ShouldPrintBackgrounds = ps.ShouldPrintBackgrounds; 319 | 320 | wvps.ShouldPrintHeaderAndFooter = ps.ShouldPrintHeaderAndFooter; 321 | wvps.HeaderTitle = ps.HeaderTemplate; 322 | wvps.FooterUri = ps.FooterTemplate; 323 | 324 | wvps.ShouldPrintSelectionOnly = ps.ShouldPrintSelectionOnly; 325 | wvps.Orientation = ps.Orientation == WebViewPrintOrientations.Portrait ? CoreWebView2PrintOrientation.Portrait : CoreWebView2PrintOrientation.Landscape; 326 | wvps.Duplex = ps.Duplex == WebViewPrintDuplexes.Default ? CoreWebView2PrintDuplex.Default : 327 | ps.Duplex == WebViewPrintDuplexes.OneSided ? CoreWebView2PrintDuplex.OneSided : 328 | ps.Duplex == WebViewPrintDuplexes.TwoSidedLongEdge ? CoreWebView2PrintDuplex.TwoSidedLongEdge : 329 | CoreWebView2PrintDuplex.TwoSidedShortEdge; 330 | wvps.Collation = ps.Collation == WebViewPrintCollations.Default ? CoreWebView2PrintCollation.Default : 331 | ps.Collation == WebViewPrintCollations.Collated ? CoreWebView2PrintCollation.Collated : 332 | CoreWebView2PrintCollation.Uncollated; 333 | wvps.ColorMode = ps.ColorMode == WebViewPrintColorModes.Color ? CoreWebView2PrintColorMode.Color : CoreWebView2PrintColorMode.Grayscale; 334 | 335 | 336 | wvps.PrinterName = ps.PrinterName; 337 | wvps.PagesPerSide = ps.PagesPerSide; 338 | 339 | return wvps; 340 | } 341 | 342 | 343 | /// 344 | /// Map WebViewPrintSettings to DevToolsPrintSettings and return as JSON 345 | /// that needs to be passed to the API. 346 | /// 347 | /// 348 | public string GetDevToolsWebViewPrintSettingsJson() 349 | { 350 | var wvps = new DevToolsPrintToPdfSettings(); 351 | 352 | var ps = WebViewPrintSettings; 353 | 354 | wvps.landscape = ps.Orientation == WebViewPrintOrientations.Landscape; 355 | wvps.printBackground = ps.ShouldPrintBackgrounds; 356 | wvps.scale = ps.ScaleFactor; 357 | wvps.paperWidth = ps.PageWidth; 358 | wvps.paperHeight = ps.PageHeight; 359 | wvps.marginTop = ps.MarginTop; 360 | wvps.marginBottom = ps.MarginBottom; 361 | wvps.marginLeft = ps.MarginLeft; 362 | wvps.marginRight = ps.MarginRight; 363 | 364 | wvps.pageRanges = ps.PageRanges; 365 | 366 | wvps.displayHeaderFooter = ps.ShouldPrintHeaderAndFooter; 367 | wvps.headerTemplate = ps.HeaderTemplate; 368 | wvps.footerTemplate = ps.FooterTemplate; 369 | 370 | wvps.generateDocumentOutline = ps.GenerateDocumentOutline; 371 | 372 | return wvps.ToJson(); 373 | } 374 | 375 | 376 | 377 | string PageBreakCss { get; } = @" 378 | html, body { 379 | text-rendering: optimizeLegibility; 380 | height: auto; 381 | } 382 | 383 | pre { 384 | white-space: pre-wrap; 385 | word-break: normal; 386 | word-wrap: normal; 387 | } 388 | pre > code { 389 | white-space: pre-wrap; 390 | padding: 1em !important; 391 | } 392 | 393 | /* keep paragraphs together */ 394 | p, li, ul, code, pre { 395 | page-break-inside: avoid; 396 | break-inside: avoid; 397 | } 398 | 399 | /* keep headers and content together */ 400 | h1, h2, h3, h4, h5, h6 { 401 | page-break-after: avoid; 402 | break-after: avoid; 403 | } 404 | "; 405 | string OptimizedFontCss { get; } = 406 | @"html, body { font-family: ""Segoe UI Emoji"", ""Apple Color Emoji"", -apple-system, BlinkMacSystemFont,""Segoe UI"", Helvetica, Arial, sans-serif; }"; 407 | } 408 | } 409 | 410 | 411 | public class DevToolsPrintToPdfSettings 412 | { 413 | public bool landscape { get; set; } = false; 414 | 415 | public bool printBackground { get; set; } = true; 416 | 417 | public double scale { get; set; } = 1; 418 | public double paperWidth { get; set; } = 8.5; 419 | public double paperHeight { get; set; } = 11; 420 | public double marginTop { get; set; } = 0.4; 421 | public double marginBottom { get; set; } = 0.4; 422 | public double marginLeft { get; set; } = 0.4; 423 | public double marginRight { get; set; } = 0.4; 424 | public string pageRanges { get; set; } = ""; 425 | 426 | public bool displayHeaderFooter { get; set; } = true; 427 | public string headerTemplate { get; set; } = "
"; 428 | public string footerTemplate { get; set; } = "
of "; 429 | 430 | public bool preferCSSPageSize { get; set; } = false; 431 | public bool generateDocumentOutline { get; set; } = true; 432 | 433 | public string ToJson() 434 | { 435 | // avoid using a serializer 436 | return 437 | $$""" 438 | { 439 | "landscape": {{landscape.ToJson()}}, 440 | "printBackground": {{printBackground.ToJson()}}, 441 | "scale": {{scale.ToJson()}}, 442 | "paperWidth": {{paperWidth.ToJson()}}, 443 | "paperHeight": {{paperHeight.ToJson()}}, 444 | "marginTop": {{marginTop.ToJson()}}, 445 | "marginBottom": {{marginBottom.ToJson()}}, 446 | "marginLeft": {{marginLeft.ToJson()}}, 447 | "marginRight": {{marginRight.ToJson()}}, 448 | "pageRanges": {{(pageRanges ?? string.Empty).ToJson()}}, 449 | "headerTemplate": {{headerTemplate.ToJson()}}, 450 | "footerTemplate": {{footerTemplate.ToJson()}}, 451 | "displayHeaderFooter": {{displayHeaderFooter.ToJson()}}, 452 | "preferCSSPageSize": {{preferCSSPageSize.ToJson()}}, 453 | "generateDocumentOutline": {{generateDocumentOutline.ToJson()}} 454 | } 455 | """ 456 | .Trim(); 457 | 458 | 459 | } 460 | } 461 | -------------------------------------------------------------------------------- /Westwind.WebView.HtmlToPdf/HtmlToPdfHost.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Web.WebView2.Core; 2 | using System; 3 | using System.Drawing; 4 | using System.IO; 5 | using System.Text; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | using System.Windows.Forms; 9 | 10 | namespace Westwind.WebView.HtmlToPdf 11 | { 12 | 13 | 14 | /// 15 | /// Converts an HTML document to PDF using the Windows WebView control. 16 | /// 17 | /// 18 | /// * Recommend you use a new instance for each PDF generation 19 | /// * Works only on Windows 20 | /// * Requires net8.0-windows target to work 21 | /// 22 | public class HtmlToPdfHost 23 | { 24 | internal WebViewPrintSettings WebViewPrintSettings = new WebViewPrintSettings(); 25 | internal TaskCompletionSource IsCompleteTaskCompletionSource { get; set; } = new TaskCompletionSource(); 26 | 27 | /// 28 | /// A flag you can check to see if the conversion process has completed. 29 | /// 30 | public bool IsComplete { get; set; } 31 | 32 | /// 33 | /// The location of the WebView environment folder that is required 34 | /// for WebView operation. Uses a default in the temp folder but you 35 | /// can customize to use an application specific folder. 36 | /// 37 | /// (If you already use a WebView keep all WebViews pointing at the same environment: 38 | /// https://weblog.west-wind.com/posts/2023/Oct/31/Caching-your-WebView-Environment-to-manage-multiple-WebView2-Controls 39 | /// 40 | public string WebViewEnvironmentPath { get; set; } = Path.Combine(Path.GetTempPath(), "WebView2_Environment"); 41 | 42 | 43 | /// 44 | /// Options to inject and optimize CSS for print operations in PDF generation. 45 | /// 46 | public PdfCssAndScriptOptions CssAndScriptOptions { get; set; } = new PdfCssAndScriptOptions(); 47 | 48 | 49 | /// 50 | /// Specify the background color of the PDF frame which contains 51 | /// the margins of the document. 52 | /// 53 | /// Defaults to white, but if you use a non-white background for your 54 | /// document you'll likely want to match it to your document background. 55 | /// 56 | /// Also note that non-white colors may have to use custom HeaderTemplate and 57 | /// FooterTemplate to set the foregraound color of the text to match the background. 58 | /// 59 | public string BackgroundHtmlColor { get; set; } = "#ffffff"; 60 | 61 | 62 | /// 63 | /// If set delays PDF generation to allow the document to complete loading if 64 | /// content is dynamically loaded. By default PDF generation fires off 65 | /// DomContentLoaded which fires when all embedded resources have loaded, 66 | /// but in some cases when resources load very slow, or when resources are dynamically 67 | /// loaded you might need to delay the PDF generation to allow the document to 68 | /// completely load. 69 | /// 70 | /// Specify in milliseconds, default is no delay. 71 | /// 72 | public int DelayPdfGenerationMs { get; set; } 73 | 74 | 75 | /// 76 | /// This method prints a PDF from an HTML URl or File to PDF and awaits 77 | /// the result to be returned. Result is returned as a Memory Stream in 78 | /// result.ResultStream on success. 79 | /// 80 | /// Check result.IsSuccess to check for successful completion. 81 | /// 82 | /// File or URL to print to PDF 83 | /// WebView PDF generation settings 84 | public virtual Task PrintToPdfStreamAsync(string url, 85 | WebViewPrintSettings webViewPrintSettings = null) 86 | { 87 | IsComplete = false; 88 | WebViewPrintSettings = webViewPrintSettings ?? WebViewPrintSettings; 89 | 90 | PdfPrintResult result = new PdfPrintResult() 91 | { 92 | IsSuccess = false, 93 | Message = "PDF generation didn't complete.", 94 | }; 95 | 96 | var tcs = new TaskCompletionSource(); 97 | 98 | Thread thread = new Thread( () => 99 | { 100 | // Create a Windows Forms Synchronization Context we can execute 101 | // which works without a desktop! 102 | SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext()); 103 | if (SynchronizationContext.Current == null) 104 | { 105 | tcs.SetResult(new PdfPrintResult { IsSuccess = false, Message = "Couldn't create STA Synchronization Context." }); 106 | return; 107 | } 108 | SynchronizationContext.Current.Post( async (state)=> 109 | { 110 | try 111 | { 112 | IsComplete = false; 113 | IsCompleteTaskCompletionSource = new TaskCompletionSource(); 114 | 115 | var host = new CoreWebViewHeadlessHost(this); 116 | await host.PrintFromUrlStream(url); 117 | 118 | await IsCompleteTaskCompletionSource.Task; 119 | 120 | if (!host.IsComplete) 121 | { 122 | result = new PdfPrintResult() 123 | { 124 | IsSuccess = false, 125 | Message = "Pdf generation timed out or failed to render inside of a non-Desktop context." 126 | }; 127 | } 128 | else 129 | { 130 | result = new PdfPrintResult() 131 | { 132 | IsSuccess = host.IsSuccess, 133 | Message = host.IsSuccess ? "PDF was generated." : "PDF generation failed: " + host.LastException?.Message, 134 | ResultStream = host.ResultStream, 135 | LastException = host.LastException 136 | }; 137 | } 138 | tcs.SetResult(result); 139 | } 140 | catch (Exception ex) 141 | { 142 | result.IsSuccess = false; 143 | result.Message = ex.ToString(); 144 | result.LastException = ex; 145 | tcs.SetResult(result); 146 | } 147 | finally 148 | { 149 | IsComplete = true; 150 | Application.ExitThread(); // now kill the event loop and thread 151 | } 152 | }, null); 153 | Application.Run(); // Windows Event loop needed for WebView in system context! 154 | }); 155 | 156 | thread.SetApartmentState(ApartmentState.STA); // MUST BE STA! 157 | thread.Start(); 158 | 159 | return tcs.Task; 160 | } 161 | 162 | /// 163 | /// This method prints a PDF from an HTML URl or File to PDF and awaits 164 | /// the result to be returned. Result is returned as a Memory Stream in 165 | /// result.ResultStream on success. 166 | /// 167 | /// Check result.IsSuccess to check for successful completion. 168 | /// 169 | /// Stream of an HTML document to print to PDF 170 | /// WebView PDF generation settings 171 | /// Encoding of the HTML stream. Defaults to UTF-8 172 | public virtual Task PrintToPdfStreamAsync(Stream htmlStream, 173 | WebViewPrintSettings webViewPrintSettings = null, 174 | Encoding encoding = null) 175 | { 176 | if (encoding == null) 177 | encoding = Encoding.UTF8; 178 | 179 | IsComplete = false; 180 | WebViewPrintSettings = webViewPrintSettings ?? WebViewPrintSettings; 181 | 182 | PdfPrintResult result = new PdfPrintResult() 183 | { 184 | IsSuccess = false, 185 | Message = "PDF generation didn't complete.", 186 | }; 187 | 188 | var tcs = new TaskCompletionSource(); 189 | 190 | Thread thread = new Thread(() => 191 | { 192 | // Create a Windows Forms Synchronization Context we can execute 193 | // which works without a desktop! 194 | SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext()); 195 | if (SynchronizationContext.Current == null) 196 | { 197 | tcs.SetResult(new PdfPrintResult { IsSuccess = false, Message = "Couldn't create STA Synchronization Context." }); 198 | return; 199 | } 200 | SynchronizationContext.Current.Post(async (state) => 201 | { 202 | try 203 | { 204 | IsComplete = false; 205 | IsCompleteTaskCompletionSource = new TaskCompletionSource(); 206 | 207 | var host = new CoreWebViewHeadlessHost(this); 208 | await host.PrintFromHtmlStreamToStream(htmlStream, encoding); 209 | 210 | await IsCompleteTaskCompletionSource.Task; 211 | 212 | if (!host.IsComplete) 213 | { 214 | result = new PdfPrintResult() 215 | { 216 | IsSuccess = false, 217 | Message = "Pdf generation timed out or failed to render inside of a non-Desktop context." 218 | }; 219 | } 220 | else 221 | { 222 | result = new PdfPrintResult() 223 | { 224 | IsSuccess = host.IsSuccess, 225 | Message = host.IsSuccess ? "PDF was generated." : "PDF generation failed: " + host.LastException?.Message, 226 | ResultStream = host.ResultStream, 227 | LastException = host.LastException 228 | }; 229 | } 230 | tcs.SetResult(result); 231 | } 232 | catch (Exception ex) 233 | { 234 | result.IsSuccess = false; 235 | result.Message = ex.ToString(); 236 | result.LastException = ex; 237 | tcs.SetResult(result); 238 | } 239 | finally 240 | { 241 | IsComplete = true; 242 | Application.ExitThread(); // now kill the event loop and thread 243 | } 244 | }, null); 245 | Application.Run(); // Windows Event loop needed for WebView in system context! 246 | }); 247 | 248 | thread.SetApartmentState(ApartmentState.STA); // MUST BE STA! 249 | thread.Start(); 250 | 251 | return tcs.Task; 252 | } 253 | 254 | 255 | 256 | // await WebBrowser.CoreWebView2.CallDevToolsProtocolMethodAsync("Page.printToPdf", "{}"); 257 | 258 | 259 | 260 | 261 | /// 262 | /// This method prints a PDF from an HTML URl or File to PDF and awaits 263 | /// the result to be returned. Check result.IsSuccess to check for 264 | /// successful completion of the file output generation or use File.Exists() 265 | /// 266 | /// File or URL to print to PDF 267 | /// output file for generated PDF 268 | /// WebView PDF generation settings 269 | public virtual Task PrintToPdfAsync(string url, 270 | string outputFile, 271 | WebViewPrintSettings webViewPrintSettings = null) 272 | { 273 | IsComplete = false; 274 | WebViewPrintSettings = webViewPrintSettings ?? WebViewPrintSettings; 275 | 276 | PdfPrintResult result = new PdfPrintResult { 277 | IsSuccess = false, 278 | Message = "PDF generation didn't complete.", 279 | }; 280 | 281 | var tcs = new TaskCompletionSource(); 282 | Thread thread = new Thread(() => 283 | { 284 | // Create a Windows Forms Synchronization Context we can execute 285 | // which works without a desktop! 286 | SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext()); 287 | if (SynchronizationContext.Current == null) 288 | { 289 | tcs.SetResult(new PdfPrintResult { IsSuccess = false, Message = "Couldn't create STA Synchronization Context." }); 290 | return; 291 | } 292 | SynchronizationContext.Current.Post(async (state) => 293 | { 294 | try 295 | { 296 | IsComplete = false; 297 | IsCompleteTaskCompletionSource = new TaskCompletionSource(); 298 | 299 | var host = new CoreWebViewHeadlessHost(this); 300 | await host.PrintFromUrl(url, outputFile); 301 | 302 | await IsCompleteTaskCompletionSource.Task; 303 | 304 | if (!host.IsComplete) 305 | { 306 | result = new PdfPrintResult() 307 | { 308 | IsSuccess = false, 309 | Message = "Pdf generation timed out or failed to render inside of a non-Desktop context." 310 | }; 311 | } 312 | else 313 | { 314 | result = new PdfPrintResult() 315 | { 316 | IsSuccess = host.IsSuccess, 317 | Message = host.IsSuccess ? "PDF was generated." : "PDF generation failed: " + host.LastException?.Message, 318 | LastException = host.LastException 319 | }; 320 | } 321 | tcs.SetResult(result); 322 | } 323 | catch (Exception ex) 324 | { 325 | result.IsSuccess = false; 326 | result.Message = ex.ToString(); 327 | result.LastException = ex; 328 | tcs.SetResult(result); 329 | } 330 | finally 331 | { 332 | IsComplete = true; 333 | Application.ExitThread(); // now kill the event loop and thread 334 | } 335 | }, null); 336 | Application.Run(); // Windows Event loop needed for WebView in system context! 337 | }); 338 | 339 | thread.SetApartmentState(ApartmentState.STA); // MUST BE STA! 340 | thread.Start(); 341 | 342 | return tcs.Task; 343 | } 344 | 345 | 346 | /// 347 | /// This method prints a PDF from an HTML URl or File to PDF 348 | /// using a new thread and a hosted form returning the result 349 | /// as an in-memory stream in result.ResultStream. 350 | /// 351 | /// You get notified via OnPrintCompleteAction 'event' (Action) when the 352 | /// output operation is complete. 353 | /// 354 | /// The filename or URL to print to PDF 355 | /// Optional action to fire when printing (or failure) is complete 356 | /// PDF output options 357 | public virtual void PrintToPdfStream(string url, Action onPrintComplete = null, WebViewPrintSettings webViewPrintSettings = null) 358 | { 359 | WebViewPrintSettings = webViewPrintSettings ?? WebViewPrintSettings; 360 | 361 | PdfPrintResult result = new PdfPrintResult 362 | { 363 | IsSuccess = false, 364 | Message = "PDF generation didn't complete.", 365 | }; 366 | 367 | Thread thread = new Thread(() => 368 | { 369 | // Create a Windows Forms Synchronization Context we can execute 370 | // which works without a desktop! 371 | SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext()); 372 | if (SynchronizationContext.Current == null) 373 | { 374 | IsComplete = true; 375 | onPrintComplete?.Invoke(new PdfPrintResult { IsSuccess = false, Message = "Couldn't create STA Synchronization Context." }); 376 | return; 377 | } 378 | SynchronizationContext.Current.Post(async (state) => 379 | { 380 | try 381 | { 382 | IsComplete = false; 383 | IsCompleteTaskCompletionSource = new TaskCompletionSource(); 384 | 385 | var host = new CoreWebViewHeadlessHost(this); 386 | await host.PrintFromUrlStream(url); 387 | 388 | await IsCompleteTaskCompletionSource.Task; 389 | 390 | if (!host.IsComplete) 391 | { 392 | result = new PdfPrintResult() 393 | { 394 | IsSuccess = false, 395 | Message = "Pdf generation timed out or failed to render inside of a non-Desktop context." 396 | }; 397 | } 398 | else 399 | { 400 | result = new PdfPrintResult() 401 | { 402 | IsSuccess = host.IsSuccess, 403 | Message = host.IsSuccess ? "PDF was generated." : "PDF generation failed: " + host.LastException?.Message, 404 | ResultStream = host.ResultStream, 405 | LastException = host.LastException 406 | }; 407 | } 408 | onPrintComplete?.Invoke(result); 409 | } 410 | catch (Exception ex) 411 | { 412 | result.IsSuccess = false; 413 | result.Message = ex.ToString(); 414 | result.LastException = ex; 415 | } 416 | finally 417 | { 418 | IsComplete = true; 419 | Application.ExitThread(); // now kill the event loop and thread 420 | } 421 | }, null); 422 | Application.Run(); // Windows Event loop needed for WebView in system context! 423 | }); 424 | 425 | thread.SetApartmentState(ApartmentState.STA); 426 | thread.Start(); 427 | } 428 | 429 | /// 430 | /// This method prints a PDF from an HTML Url or File to PDF 431 | /// using a new thread and a hosted form. The method **returns immediately** 432 | /// and returns completion via the `onPrintComplete` Action parameter. 433 | /// 434 | /// This method works in non-UI scenarios as it creates its own STA thread 435 | /// 436 | /// The filename or URL to print to PDF 437 | /// File to generate the output to 438 | /// Action to fire when printing is complete 439 | /// PDF output options 440 | public virtual void PrintToPdf(string url, string outputFile, 441 | Action onPrintComplete = null, 442 | WebViewPrintSettings webViewPrintSettings = null) 443 | { 444 | WebViewPrintSettings = webViewPrintSettings ?? WebViewPrintSettings; 445 | 446 | PdfPrintResult result = new PdfPrintResult 447 | { 448 | IsSuccess = false, 449 | Message = "PDF generation didn't complete.", 450 | }; 451 | 452 | Thread thread = new Thread(() => 453 | { 454 | // Create a Windows Forms Synchronization Context we can execute 455 | // which works without a desktop! 456 | SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext()); 457 | if (SynchronizationContext.Current == null) 458 | { 459 | IsComplete = true; 460 | onPrintComplete?.Invoke(new PdfPrintResult { IsSuccess = false, Message = "Couldn't create STA Synchronization Context." }); 461 | return; 462 | } 463 | SynchronizationContext.Current.Post(async (state) => 464 | { 465 | try 466 | { 467 | IsComplete = false; 468 | IsCompleteTaskCompletionSource = new TaskCompletionSource(); 469 | 470 | var host = new CoreWebViewHeadlessHost(this); 471 | await host.PrintFromUrl(url, outputFile); 472 | 473 | await IsCompleteTaskCompletionSource.Task; 474 | 475 | if (!host.IsComplete) 476 | { 477 | result = new PdfPrintResult() 478 | { 479 | IsSuccess = false, 480 | Message = "Pdf generation timed out or failed to render inside of a non-Desktop context." 481 | }; 482 | } 483 | else 484 | { 485 | result = new PdfPrintResult() 486 | { 487 | IsSuccess = host.IsSuccess, 488 | Message = host.IsSuccess ? "PDF was generated." : "PDF generation failed: " + host.LastException?.Message, 489 | LastException = host.LastException 490 | }; 491 | } 492 | onPrintComplete?.Invoke(result); 493 | } 494 | catch (Exception ex) 495 | { 496 | result.IsSuccess = false; 497 | result.Message = ex.ToString(); 498 | result.LastException = ex; 499 | } 500 | finally 501 | { 502 | IsComplete = true; 503 | Application.ExitThread(); // now kill the event loop and thread 504 | } 505 | }, null); 506 | Application.Run(); // Windows Event loop needed for WebView in system context! 507 | }); 508 | 509 | thread.SetApartmentState(ApartmentState.STA); 510 | thread.Start(); 511 | } 512 | } 513 | 514 | public class PdfCssAndScriptOptions 515 | { 516 | /// 517 | /// Injects @media print CSS that attempts to keep text from breaking across pages by: 518 | /// 519 | /// * Minimizing paragraph breaks 520 | /// * List breaks 521 | /// * Keeping headers and following text together 522 | /// * Keeping code blocks from breaking 523 | /// 524 | /// Uses page-break and break CSS styles to control page breaks. If you already have 525 | /// @media print style in your HTML source you probably don't need this. 526 | /// 527 | public bool KeepTextTogether { get; set; } = false; 528 | 529 | /// 530 | /// Optionally inject custom CSS into the Html document header before printing. 531 | /// 532 | public string CssToInject { get; set; } 533 | 534 | 535 | /// 536 | /// If set to true adds fonts for Windows and Apple native fonts that work best 537 | /// for PDF generation using built-in fonts. This can help reduce the size of the 538 | /// PDF and also improve rendering for extended characters like emojis. 539 | /// 540 | /// Use this if you see invalid characters in your PDF output 541 | /// 542 | public bool OptimizePdfFonts { get; set; } 543 | 544 | /// 545 | /// Not implemented yet. 546 | /// 547 | /// Optionally inject custom JavaScript that can execute before the page is printed. 548 | /// Allows you to potentially modify the page before printing. 549 | /// 550 | public string ScriptToInject { get; set; } 551 | } 552 | 553 | } 554 | --------------------------------------------------------------------------------