1+ using System . Runtime . InteropServices ;
2+ using PdfSharp ;
3+ using PdfSharp . Drawing ;
4+ using TheArtOfDev . HtmlRenderer . Core . Entities ;
5+ using TheArtOfDev . HtmlRenderer . Demo . Common ;
6+ using TheArtOfDev . HtmlRenderer . PdfSharp ;
7+
8+ namespace HtmlRenderer . PdfSharp . Test ;
9+
10+ [ TestClass ]
11+ public sealed class PdfGeneratorTests
12+ {
13+ [ TestMethod ]
14+ public void GeneratePdf_FromHtml_CreatesPdfDocument ( )
15+ {
16+ var config = new PdfGenerateConfig
17+ {
18+ PageSize = PageSize . A4
19+ } ;
20+ config . SetMargins ( 20 ) ;
21+
22+ const string html = """
23+ <html>
24+ <head>
25+ <link rel="Stylesheet" href="StyleSheet" />
26+ </head>
27+ <body>
28+ <h1>PdfSharp</h1>
29+ <p>This is html rendered text <img src="ImageIcon" /></p>
30+ </body>
31+ </html>
32+ """ ;
33+
34+ using var document = PdfGenerator . GeneratePdf ( html , config , null , DemoUtils . OnStylesheetLoad , OnImageLoadPdfSharp ) ;
35+
36+ Assert . AreEqual ( 1 , document . Pages . Count ) ;
37+
38+ using var stream = new MemoryStream ( ) ;
39+ document . Save ( stream , false ) ;
40+
41+ var pdf = stream . ToArray ( ) ;
42+ Assert . IsGreaterThan ( 4 , pdf . Length ) ;
43+ Assert . AreEqual ( "%PDF" , System . Text . Encoding . ASCII . GetString ( pdf , 0 , 4 ) ) ;
44+
45+ var pdfOutputDirectory = Environment . GetEnvironmentVariable ( "PDF_OUTPUT_DIRECTORY" ) ;
46+ if ( string . IsNullOrWhiteSpace ( pdfOutputDirectory ) )
47+ {
48+ pdfOutputDirectory = Path . Combine ( Path . GetTempPath ( ) , "html-renderer-pdf-artifacts" ) ;
49+ }
50+
51+ Directory . CreateDirectory ( pdfOutputDirectory ) ;
52+
53+ var pdfPath = Path . Combine (
54+ pdfOutputDirectory ,
55+ $ "{ nameof ( GeneratePdf_FromHtml_CreatesPdfDocument ) } -{ GetPlatformName ( ) } .pdf") ;
56+ File . WriteAllBytes ( pdfPath , pdf ) ;
57+ }
58+
59+ private static void OnImageLoadPdfSharp ( object ? sender , HtmlImageLoadEventArgs e )
60+ {
61+ if ( ! string . Equals ( e . Src , "ImageIcon" , StringComparison . OrdinalIgnoreCase ) )
62+ {
63+ return ;
64+ }
65+
66+ using var imageStream = DemoUtils . GetImageStream ( e . Src ) ;
67+ if ( imageStream == null )
68+ {
69+ throw new InvalidOperationException ( "Expected demo image resource was not found." ) ;
70+ }
71+
72+ e . Callback ( XImage . FromStream ( imageStream ) ) ;
73+ }
74+
75+ private static string GetPlatformName ( )
76+ {
77+ if ( OperatingSystem . IsWindows ( ) )
78+ {
79+ return "windows" ;
80+ }
81+
82+ if ( OperatingSystem . IsMacOS ( ) )
83+ {
84+ return "macos" ;
85+ }
86+
87+ if ( OperatingSystem . IsLinux ( ) )
88+ {
89+ return "linux" ;
90+ }
91+
92+ return RuntimeInformation . RuntimeIdentifier ;
93+ }
94+ }
0 commit comments