├── .gitattributes
├── .gitignore
├── HTMLToQPDF.Example
├── App.xaml
├── App.xaml.cs
├── AssemblyInfo.cs
├── Assets
│ ├── testHtml.html
│ └── web-programming.ico
├── FodyWeavers.xml
├── HTMLToQPDF.Example.csproj
├── MainWindow.xaml
├── MainWindow.xaml.cs
├── Properties
│ ├── Resources.Designer.cs
│ └── Resources.resx
├── Utilities
│ ├── FileDialogHelper.cs
│ └── PDFCreator.cs
└── ViewModels
│ └── MainWindowViewModel.cs
├── HTMLToQPDF.sln
├── HTMLToQPDF
├── Assets
│ └── icon.png
├── Components
│ ├── BaseHTMLComponent.cs
│ ├── HTMLComponent.cs
│ ├── HTMLComponentsArgs.cs
│ ├── ParagraphComponent.cs
│ └── Tags
│ │ ├── AComponent.cs
│ │ ├── BrComponent.cs
│ │ ├── ImgComponent.cs
│ │ ├── ListComponent.cs
│ │ └── TableComponent.cs
├── Extensions
│ ├── HTMLComponentExtensions.cs
│ ├── HtmlNodeExtensions.cs
│ └── IContainerExtensions.cs
├── HTMLDescriptor.cs
├── HTMLToQPDF.csproj
├── StyleSettings.cs
└── Utils
│ ├── HTMLUtils.cs
│ ├── ImgUtils.cs
│ └── UnitUtils.cs
├── LICENSE.txt
└── README.md
/.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 |
--------------------------------------------------------------------------------
/.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 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Oo]ut/
33 | [Ll]og/
34 | [Ll]ogs/
35 |
36 | # Visual Studio 2015/2017 cache/options directory
37 | .vs/
38 | # Uncomment if you have tasks that create the project's static files in wwwroot
39 | #wwwroot/
40 |
41 | # Visual Studio 2017 auto generated files
42 | Generated\ Files/
43 |
44 | # MSTest test Results
45 | [Tt]est[Rr]esult*/
46 | [Bb]uild[Ll]og.*
47 |
48 | # NUnit
49 | *.VisualState.xml
50 | TestResult.xml
51 | nunit-*.xml
52 |
53 | # Build Results of an ATL Project
54 | [Dd]ebugPS/
55 | [Rr]eleasePS/
56 | dlldata.c
57 |
58 | # Benchmark Results
59 | BenchmarkDotNet.Artifacts/
60 |
61 | # .NET Core
62 | project.lock.json
63 | project.fragment.lock.json
64 | artifacts/
65 |
66 | # ASP.NET Scaffolding
67 | ScaffoldingReadMe.txt
68 |
69 | # StyleCop
70 | StyleCopReport.xml
71 |
72 | # Files built by Visual Studio
73 | *_i.c
74 | *_p.c
75 | *_h.h
76 | *.ilk
77 | *.meta
78 | *.obj
79 | *.iobj
80 | *.pch
81 | *.pdb
82 | *.ipdb
83 | *.pgc
84 | *.pgd
85 | *.rsp
86 | *.sbr
87 | *.tlb
88 | *.tli
89 | *.tlh
90 | *.tmp
91 | *.tmp_proj
92 | *_wpftmp.csproj
93 | *.log
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Coverlet is a free, cross platform Code Coverage Tool
146 | coverage*.json
147 | coverage*.xml
148 | coverage*.info
149 |
150 | # Visual Studio code coverage results
151 | *.coverage
152 | *.coveragexml
153 |
154 | # NCrunch
155 | _NCrunch_*
156 | .*crunch*.local.xml
157 | nCrunchTemp_*
158 |
159 | # MightyMoose
160 | *.mm.*
161 | AutoTest.Net/
162 |
163 | # Web workbench (sass)
164 | .sass-cache/
165 |
166 | # Installshield output folder
167 | [Ee]xpress/
168 |
169 | # DocProject is a documentation generator add-in
170 | DocProject/buildhelp/
171 | DocProject/Help/*.HxT
172 | DocProject/Help/*.HxC
173 | DocProject/Help/*.hhc
174 | DocProject/Help/*.hhk
175 | DocProject/Help/*.hhp
176 | DocProject/Help/Html2
177 | DocProject/Help/html
178 |
179 | # Click-Once directory
180 | publish/
181 |
182 | # Publish Web Output
183 | *.[Pp]ublish.xml
184 | *.azurePubxml
185 | # Note: Comment the next line if you want to checkin your web deploy settings,
186 | # but database connection strings (with potential passwords) will be unencrypted
187 | *.pubxml
188 | *.publishproj
189 |
190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
191 | # checkin your Azure Web App publish settings, but sensitive information contained
192 | # in these scripts will be unencrypted
193 | PublishScripts/
194 |
195 | # NuGet Packages
196 | *.nupkg
197 | # NuGet Symbol Packages
198 | *.snupkg
199 | # The packages folder can be ignored because of Package Restore
200 | **/[Pp]ackages/*
201 | # except build/, which is used as an MSBuild target.
202 | !**/[Pp]ackages/build/
203 | # Uncomment if necessary however generally it will be regenerated when needed
204 | #!**/[Pp]ackages/repositories.config
205 | # NuGet v3's project.json files produces more ignorable files
206 | *.nuget.props
207 | *.nuget.targets
208 |
209 | # Microsoft Azure Build Output
210 | csx/
211 | *.build.csdef
212 |
213 | # Microsoft Azure Emulator
214 | ecf/
215 | rcf/
216 |
217 | # Windows Store app package directories and files
218 | AppPackages/
219 | BundleArtifacts/
220 | Package.StoreAssociation.xml
221 | _pkginfo.txt
222 | *.appx
223 | *.appxbundle
224 | *.appxupload
225 |
226 | # Visual Studio cache files
227 | # files ending in .cache can be ignored
228 | *.[Cc]ache
229 | # but keep track of directories ending in .cache
230 | !?*.[Cc]ache/
231 |
232 | # Others
233 | ClientBin/
234 | ~$*
235 | *~
236 | *.dbmdl
237 | *.dbproj.schemaview
238 | *.jfm
239 | *.pfx
240 | *.publishsettings
241 | orleans.codegen.cs
242 |
243 | # Including strong name files can present a security risk
244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
245 | #*.snk
246 |
247 | # Since there are multiple workflows, uncomment next line to ignore bower_components
248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
249 | #bower_components/
250 |
251 | # RIA/Silverlight projects
252 | Generated_Code/
253 |
254 | # Backup & report files from converting an old project file
255 | # to a newer Visual Studio version. Backup files are not needed,
256 | # because we have git ;-)
257 | _UpgradeReport_Files/
258 | Backup*/
259 | UpgradeLog*.XML
260 | UpgradeLog*.htm
261 | ServiceFabricBackup/
262 | *.rptproj.bak
263 |
264 | # SQL Server files
265 | *.mdf
266 | *.ldf
267 | *.ndf
268 |
269 | # Business Intelligence projects
270 | *.rdl.data
271 | *.bim.layout
272 | *.bim_*.settings
273 | *.rptproj.rsuser
274 | *- [Bb]ackup.rdl
275 | *- [Bb]ackup ([0-9]).rdl
276 | *- [Bb]ackup ([0-9][0-9]).rdl
277 |
278 | # Microsoft Fakes
279 | FakesAssemblies/
280 |
281 | # GhostDoc plugin setting file
282 | *.GhostDoc.xml
283 |
284 | # Node.js Tools for Visual Studio
285 | .ntvs_analysis.dat
286 | node_modules/
287 |
288 | # Visual Studio 6 build log
289 | *.plg
290 |
291 | # Visual Studio 6 workspace options file
292 | *.opt
293 |
294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
295 | *.vbw
296 |
297 | # Visual Studio LightSwitch build output
298 | **/*.HTMLClient/GeneratedArtifacts
299 | **/*.DesktopClient/GeneratedArtifacts
300 | **/*.DesktopClient/ModelManifest.xml
301 | **/*.Server/GeneratedArtifacts
302 | **/*.Server/ModelManifest.xml
303 | _Pvt_Extensions
304 |
305 | # Paket dependency manager
306 | .paket/paket.exe
307 | paket-files/
308 |
309 | # FAKE - F# Make
310 | .fake/
311 |
312 | # CodeRush personal settings
313 | .cr/personal
314 |
315 | # Python Tools for Visual Studio (PTVS)
316 | __pycache__/
317 | *.pyc
318 |
319 | # Cake - Uncomment if you are using it
320 | # tools/**
321 | # !tools/packages.config
322 |
323 | # Tabs Studio
324 | *.tss
325 |
326 | # Telerik's JustMock configuration file
327 | *.jmconfig
328 |
329 | # BizTalk build output
330 | *.btp.cs
331 | *.btm.cs
332 | *.odx.cs
333 | *.xsd.cs
334 |
335 | # OpenCover UI analysis results
336 | OpenCover/
337 |
338 | # Azure Stream Analytics local run output
339 | ASALocalRun/
340 |
341 | # MSBuild Binary and Structured Log
342 | *.binlog
343 |
344 | # NVidia Nsight GPU debugger configuration file
345 | *.nvuser
346 |
347 | # MFractors (Xamarin productivity tool) working folder
348 | .mfractor/
349 |
350 | # Local History for Visual Studio
351 | .localhistory/
352 |
353 | # BeatPulse healthcheck temp database
354 | healthchecksdb
355 |
356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
357 | MigrationBackup/
358 |
359 | # Ionide (cross platform F# VS Code tools) working folder
360 | .ionide/
361 |
362 | # Fody - auto-generated XML schema
363 | FodyWeavers.xsd
--------------------------------------------------------------------------------
/HTMLToQPDF.Example/App.xaml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/HTMLToQPDF.Example/App.xaml.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 |
3 | namespace HTMLToQPDF.Example
4 | {
5 | ///
6 | /// Interaction logic for App.xaml
7 | ///
8 | public partial class App : Application
9 | {
10 | }
11 | }
--------------------------------------------------------------------------------
/HTMLToQPDF.Example/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 |
3 | [assembly: ThemeInfo(
4 | ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
5 | //(used if a resource is not found in the page,
6 | // or application resource dictionaries)
7 | ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
8 | //(used if a resource is not found in the page,
9 | // app, or any theme specific resource dictionaries)
10 | )]
--------------------------------------------------------------------------------
/HTMLToQPDF.Example/Assets/testHtml.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Document
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
Lorem
17 |
h1
18 |
h2
19 |
h3
20 |
h4
21 |
h5
22 |
23 |
24 |
h6
25 |
26 | Lorem ipsum dolor
27 | sit, amet consectetur adipisicing elit. Illo
28 | aperiam perferendis soluta nam ducimus ipsa
29 | alias animi asperiores quisquam aut ex minus, cum
30 | possimus accusamus corporis
31 | Test link consequatur
32 | ipsam praesentium.
33 |
34 |
35 |
36 |
37 | 1
38 | 2
39 | 3
40 | 4
41 |
42 |
43 | 5
44 | 6
45 |
46 |
47 | 7
48 | 8
49 |
50 |
51 |
52 |
53 |
54 |
55 | First Name
56 | Last Name
57 | Email Address
58 |
59 |
60 | Hillary
61 | Nyakundi
62 | tables@mail.com
63 |
64 |
65 | Lary
66 | Mak
67 | developer@mail.com
68 |
69 |
70 |
71 |
72 |
73 |
74 | Lorem ipsum dolor
75 | sit, amet consectetur adipisicing elit. Illo
76 | aperiam perferendis soluta nam ducimus ipsa
77 | alias animi asperiores quisquam aut ex minus, cum
78 | possimus accusamus corporis
79 | Test link consequatur
80 | ipsam praesentium.
81 |
82 |
83 | lorem
84 |
85 | Lorem ipsum dolor sit amet consectetur adipisicing elit. Ullam
86 | voluptates dignissimos, praesentium non necessitatibus reiciendis
87 | nihil repudiandae quibusdam deleniti, placeat accusantium impedit
88 | aperiam laborum. Cupiditate sed repellendus eos quam harum.
89 |
90 | Option 1
91 | Option 2
92 |
93 |
94 |
95 |
96 |
97 | Лорем ипсум долор сит амет, хинц феугаит албуциус не пер, вис еу темпор
98 | номинати маиестатис. Еу ерос оптион яуи. Ерат миним ехерци хас еа, нец
99 | легимус детерруиссет ат. Еирмод тхеопхрастус те хис, еи яуо видит аугуе,
100 | дицтас цонсецтетуер при ад. Бруте сенсибус вис ат, нам путант форенсибус
101 | ид, мел еа порро толлит перфецто. Яуот цлита ут нец. Ан иус алиа
102 | цонсецтетуер, те хис тале неморе. Цу сусципит апеириан торяуатос цум.
103 | Яуи ут адхуц аппареат цомпрехенсам, граецис еррорибус еи вел.
104 |
105 |
106 |
—————————————————————
107 |
108 |
● Lorem ipsum dolor sit amet
109 |
● Lorem ipsum dolor sit amet
110 |
Lorem ipsum dolor sit amet. 😊
111 |
112 |
113 |
--------------------------------------------------------------------------------
/HTMLToQPDF.Example/Assets/web-programming.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Relorer/HTMLToQPDF/6e5726de4aae45f4e6ea824e9818d3730584156a/HTMLToQPDF.Example/Assets/web-programming.ico
--------------------------------------------------------------------------------
/HTMLToQPDF.Example/FodyWeavers.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/HTMLToQPDF.Example/HTMLToQPDF.Example.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | WinExe
5 | net6.0-windows
6 | enable
7 | true
8 | Assets\web-programming.ico
9 | true
10 | true
11 | embedded
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 | all
23 | runtime; build; native; contentfiles; analyzers; buildtransitive
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 | True
37 | True
38 | Resources.resx
39 |
40 |
41 |
42 |
43 |
44 | ResXFileCodeGenerator
45 | Resources.Designer.cs
46 |
47 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/HTMLToQPDF.Example/MainWindow.xaml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
26 |
30 |
35 |
36 |
37 |
41 |
48 |
49 |
50 |
51 |
59 |
60 |
--------------------------------------------------------------------------------
/HTMLToQPDF.Example/MainWindow.xaml.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 |
3 | namespace HTMLToQPDF.Example
4 | {
5 | ///
6 | /// Interaction logic for MainWindow.xaml
7 | ///
8 | public partial class MainWindow : Window
9 | {
10 | public MainWindow()
11 | {
12 | InitializeComponent();
13 | }
14 | }
15 | }
--------------------------------------------------------------------------------
/HTMLToQPDF.Example/Properties/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.42000
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace HTMLToQPDF.Example.Properties {
12 | using System;
13 |
14 |
15 | ///
16 | /// A strongly-typed resource class, for looking up localized strings, etc.
17 | ///
18 | // This class was auto-generated by the StronglyTypedResourceBuilder
19 | // class via a tool like ResGen or Visual Studio.
20 | // To add or remove a member, edit your .ResX file then rerun ResGen
21 | // with the /str option, or rebuild your VS project.
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | internal class Resources {
26 |
27 | private static global::System.Resources.ResourceManager resourceMan;
28 |
29 | private static global::System.Globalization.CultureInfo resourceCulture;
30 |
31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
32 | internal Resources() {
33 | }
34 |
35 | ///
36 | /// Returns the cached ResourceManager instance used by this class.
37 | ///
38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
39 | internal static global::System.Resources.ResourceManager ResourceManager {
40 | get {
41 | if (object.ReferenceEquals(resourceMan, null)) {
42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("HTMLToQPDF.Example.Properties.Resources", typeof(Resources).Assembly);
43 | resourceMan = temp;
44 | }
45 | return resourceMan;
46 | }
47 | }
48 |
49 | ///
50 | /// Overrides the current thread's CurrentUICulture property for all
51 | /// resource lookups using this strongly typed resource class.
52 | ///
53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
54 | internal static global::System.Globalization.CultureInfo Culture {
55 | get {
56 | return resourceCulture;
57 | }
58 | set {
59 | resourceCulture = value;
60 | }
61 | }
62 |
63 | ///
64 | /// Looks up a localized string similar to <div class="reader-container container container_center">
65 | /// <div class="article-image">
66 | /// <a href="https://github.com/">
67 | /// <img class="lazyload"
68 | /// data-background=""
69 | /// src="shortTestImage.png" />
70 | /// </a>
71 | /// </div>
72 | /// <p>Lorem</p>
73 | /// <h1>h1</h1>
74 | /// <h2><s>h2</s></h2>
75 | /// <h3>h3</h3>
76 | /// <h4>h4</h4>
77 | /// <h5>h5</h5>
78 | /// <br />
79 | /// <br />
80 | /// <br />
81 | /// <br />
82 | /// <h6>h6</h6>
83 | /// <p>
84 | /// <s>Lorem ipsum</s> dolor <br /> [rest of string was truncated]";.
85 | ///
86 | internal static string testHtml {
87 | get {
88 | return ResourceManager.GetString("testHtml", resourceCulture);
89 | }
90 | }
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/HTMLToQPDF.Example/Properties/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
121 |
122 | ..\assets\testhtml.html;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8
123 |
124 |
--------------------------------------------------------------------------------
/HTMLToQPDF.Example/Utilities/FileDialogHelper.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Win32;
2 |
3 | namespace HTMLToQPDF.Example.DialogWindows
4 | {
5 | internal static class FileDialogHelper
6 | {
7 | public static string GetSaveFilePath(string file)
8 | {
9 | SaveFileDialog saveFileDialog = new SaveFileDialog();
10 |
11 | saveFileDialog.Filter = "PDF file|*.pdf";
12 | saveFileDialog.Title = $"Save an PDF File";
13 | saveFileDialog.FileName = file;
14 | saveFileDialog.ShowDialog();
15 |
16 | if (saveFileDialog.FileName != "")
17 | {
18 | file = saveFileDialog.FileName;
19 | }
20 |
21 | return file;
22 | }
23 | }
24 | }
--------------------------------------------------------------------------------
/HTMLToQPDF.Example/Utilities/PDFCreator.cs:
--------------------------------------------------------------------------------
1 | using HTMLQuestPDF.Extensions;
2 | using QuestPDF.Fluent;
3 | using QuestPDF.Helpers;
4 | using QuestPDF.Infrastructure;
5 |
6 | namespace HTMLToQPDF.Example.Utilities
7 | {
8 | internal static class PDFCreator
9 | {
10 | public static void Create(string html, string path, bool customStyles)
11 | {
12 |
13 | QuestPDF.Settings.License = LicenseType.Community;
14 | Document.Create(container =>
15 | {
16 | container.Page(page =>
17 | {
18 | page.Size(PageSizes.A4);
19 | page.MarginHorizontal(0.5f, Unit.Centimetre);
20 | page.MarginVertical(1f, Unit.Centimetre);
21 |
22 | page.DefaultTextStyle(TextStyle.Default.FontFamily("Arial").FontSize(8).Fallback(y => y.FontFamily("Segoe UI Emoji")));
23 |
24 | /* page.DefaultTextStyle(TextStyle.Default
25 | // .Fallback(y => y.FontFamily("MS Reference Sans Serif")
26 | .Fallback(y => y.FontFamily("Segoe UI Emoji")
27 | // .Fallback(y => y.FontFamily("Microsoft YaHei")))
28 | ));
29 | */
30 |
31 | page.Content().Column(col =>
32 | {
33 | col.Item().HTML(handler =>
34 | {
35 | if (customStyles)
36 | {
37 | handler.SetTextStyleForHtmlElement("h1", TextStyle.Default.FontColor(Colors.DeepOrange.Accent4).FontSize(32).Bold());
38 | handler.SetContainerStyleForHtmlElement("div", c => c.Background(Colors.Teal.Lighten5));
39 | handler.SetContainerStyleForHtmlElement("img", c => c.MaxHeight(7, Unit.Centimetre));
40 | handler.SetContainerStyleForHtmlElement("table", c => c.Background(Colors.Pink.Lighten5));
41 | handler.SetListVerticalPadding(40);
42 | }
43 | handler.SetHtml(html);
44 | });
45 | });
46 | });
47 | }).GeneratePdf(path);
48 | }
49 | }
50 | }
--------------------------------------------------------------------------------
/HTMLToQPDF.Example/ViewModels/MainWindowViewModel.cs:
--------------------------------------------------------------------------------
1 | using DevExpress.Mvvm;
2 | using DevExpress.Mvvm.CodeGenerators;
3 | using HTMLToQPDF.Example.DialogWindows;
4 | using HTMLToQPDF.Example.Properties;
5 | using HTMLToQPDF.Example.Utilities;
6 | using System;
7 | using System.IO;
8 |
9 | namespace HTMLToQPDF.Example.ViewModels
10 | {
11 | [GenerateViewModel]
12 | public partial class MainWindowViewModel : ViewModelBase
13 | {
14 | public string HTML { get; set; }
15 | public string SavePath { get; set; }
16 | public bool CustomStyles { get; set; }
17 |
18 | public MainWindowViewModel()
19 | {
20 | HTML = Resources.testHtml;
21 | string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
22 | SavePath = Path.Combine(desktop, "example.pdf");
23 | }
24 |
25 | [GenerateCommand]
26 | private void SelectSavePath()
27 | {
28 | SavePath = FileDialogHelper.GetSaveFilePath(SavePath);
29 | }
30 |
31 | [GenerateCommand]
32 | private void CreatePDF()
33 | {
34 | PDFCreator.Create(HTML, SavePath, CustomStyles);
35 | }
36 |
37 | private bool CanCreatePDF() => !string.IsNullOrEmpty(HTML);
38 | }
39 | }
--------------------------------------------------------------------------------
/HTMLToQPDF.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.3.32922.545
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HTMLToQPDF", "HTMLToQPDF\HTMLToQPDF.csproj", "{22118559-FF76-4BF7-973F-C4A277B9746B}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HTMLToQPDF.Example", "HTMLToQPDF.Example\HTMLToQPDF.Example.csproj", "{EADB2A0E-2D7C-47AB-8AC4-189700FA1EE2}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|Any CPU = Debug|Any CPU
13 | Release|Any CPU = Release|Any CPU
14 | EndGlobalSection
15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
16 | {22118559-FF76-4BF7-973F-C4A277B9746B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
17 | {22118559-FF76-4BF7-973F-C4A277B9746B}.Debug|Any CPU.Build.0 = Debug|Any CPU
18 | {22118559-FF76-4BF7-973F-C4A277B9746B}.Release|Any CPU.ActiveCfg = Release|Any CPU
19 | {22118559-FF76-4BF7-973F-C4A277B9746B}.Release|Any CPU.Build.0 = Release|Any CPU
20 | {EADB2A0E-2D7C-47AB-8AC4-189700FA1EE2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {EADB2A0E-2D7C-47AB-8AC4-189700FA1EE2}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {EADB2A0E-2D7C-47AB-8AC4-189700FA1EE2}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {EADB2A0E-2D7C-47AB-8AC4-189700FA1EE2}.Release|Any CPU.Build.0 = Release|Any CPU
24 | EndGlobalSection
25 | GlobalSection(SolutionProperties) = preSolution
26 | HideSolutionNode = FALSE
27 | EndGlobalSection
28 | GlobalSection(ExtensibilityGlobals) = postSolution
29 | SolutionGuid = {056F73DD-D9C7-4CC6-9D4F-415CF88A3935}
30 | EndGlobalSection
31 | EndGlobal
32 |
--------------------------------------------------------------------------------
/HTMLToQPDF/Assets/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Relorer/HTMLToQPDF/6e5726de4aae45f4e6ea824e9818d3730584156a/HTMLToQPDF/Assets/icon.png
--------------------------------------------------------------------------------
/HTMLToQPDF/Components/BaseHTMLComponent.cs:
--------------------------------------------------------------------------------
1 | using HtmlAgilityPack;
2 | using HTMLQuestPDF.Extensions;
3 | using HTMLToQPDF.Components;
4 | using QuestPDF.Fluent;
5 | using QuestPDF.Infrastructure;
6 |
7 | namespace HTMLQuestPDF.Components
8 | {
9 | internal class BaseHTMLComponent : IComponent
10 | {
11 | protected readonly HTMLComponentsArgs args;
12 | protected readonly HtmlNode node;
13 |
14 | public BaseHTMLComponent(HtmlNode node, HTMLComponentsArgs args)
15 | {
16 | this.node = node;
17 | this.args = args;
18 | }
19 |
20 | public void Compose(IContainer container)
21 | {
22 | if (!node.HasContent() || node.Name.ToLower() == "head") return;
23 |
24 | container = ApplyStyles(container);
25 |
26 | if (node.ChildNodes.Any())
27 | {
28 | ComposeMany(container);
29 | }
30 | else
31 | {
32 | ComposeSingle(container);
33 | }
34 | }
35 |
36 | protected virtual IContainer ApplyStyles(IContainer container)
37 | {
38 | return args.ContainerStyles.TryGetValue(node.Name.ToLower(), out var style) ? style(container) : container;
39 | }
40 |
41 | protected virtual void ComposeSingle(IContainer container)
42 | {
43 | }
44 |
45 | protected virtual void ComposeMany(IContainer container)
46 | {
47 | container.Column(col =>
48 | {
49 | var buffer = new List();
50 | foreach (var item in node.ChildNodes)
51 | {
52 | if (item.IsBlockNode() || item.HasBlockElement())
53 | {
54 | ComposeMany(col, buffer);
55 | buffer.Clear();
56 |
57 | col.Item().Component(item.GetComponent(args));
58 | }
59 | else
60 | {
61 | buffer.Add(item);
62 | }
63 | }
64 | ComposeMany(col, buffer);
65 | });
66 | }
67 |
68 | private void ComposeMany(ColumnDescriptor col, List nodes)
69 | {
70 | if (nodes.Count == 1)
71 | {
72 | col.Item().Component(nodes.First().GetComponent(args));
73 | }
74 | else if (nodes.Count > 0)
75 | {
76 | col.Item().Component(new ParagraphComponent(nodes, args));
77 | }
78 | }
79 | }
80 | }
--------------------------------------------------------------------------------
/HTMLToQPDF/Components/HTMLComponent.cs:
--------------------------------------------------------------------------------
1 | using HtmlAgilityPack;
2 | using HTMLQuestPDF;
3 | using HTMLQuestPDF.Extensions;
4 | using HTMLQuestPDF.Utils;
5 | using HTMLToQPDF.Utils;
6 | using QuestPDF.Fluent;
7 | using QuestPDF.Infrastructure;
8 |
9 | namespace HTMLToQPDF.Components
10 | {
11 | internal delegate void ContainerAction(IContainer container);
12 |
13 | internal delegate void TextSpanAction(TextSpanDescriptor textSpan);
14 |
15 | internal class HTMLComponent : IComponent
16 | {
17 | public GetImgBySrc GetImgBySrc { get; set; } = ImgUtils.GetImgBySrc;
18 |
19 | public Dictionary TextStyles { get; } = new Dictionary()
20 | {
21 | { "h1", TextStyle.Default.FontSize(32).Bold() },
22 | { "h2", TextStyle.Default.FontSize(28).Bold() },
23 | { "h3", TextStyle.Default.FontSize(24).Bold() },
24 | { "h4", TextStyle.Default.FontSize(20).Bold() },
25 | { "h5", TextStyle.Default.FontSize(16).Bold() },
26 | { "h6", TextStyle.Default.FontSize(12).Bold() },
27 | { "b", TextStyle.Default.Bold() },
28 | { "strong", TextStyle.Default.Bold() },
29 | { "i", TextStyle.Default.Italic() },
30 | { "em", TextStyle.Default.Italic() },
31 | { "small", TextStyle.Default.Light() },
32 | { "strike", TextStyle.Default.Strikethrough() },
33 | { "del", TextStyle.Default.Strikethrough() },
34 | { "s", TextStyle.Default.Strikethrough() },
35 | { "u", TextStyle.Default.Underline() },
36 | { "a", TextStyle.Default.Underline() },
37 | { "sup", TextStyle.Default.Superscript() },
38 | { "sub", TextStyle.Default.Subscript() },
39 |
40 | };
41 |
42 | public Dictionary> ContainerStyles { get; } = new Dictionary>()
43 | {
44 | { "p", c => c.PaddingVertical(6) },
45 | { "ul", c => c.PaddingLeft(30) },
46 | { "ol", c => c.PaddingLeft(30) }
47 | };
48 |
49 | public float ListVerticalPadding { get; set; } = 12;
50 |
51 | public string HTML { get; set; } = "";
52 |
53 | public void Compose(IContainer container)
54 | {
55 | var doc = new HtmlDocument();
56 | doc.LoadHtml(HTMLUtils.PrepareHTML(HTML));
57 | var node = doc.DocumentNode;
58 |
59 | CreateSeparateBranchesForTextNodes(node);
60 |
61 | container.Component(node.GetComponent(new HTMLComponentsArgs(TextStyles, ContainerStyles, ListVerticalPadding, GetImgBySrc)));
62 | }
63 |
64 | ///
65 | /// Separate branches are created for block and text nodes located in the same linear node
66 | ///
67 | ///
div
text in stext in p
68 | /// to
69 | ///
div
text in s text in p
70 | ///
71 | /// This is necessary to avoid extra line breaks
72 | ///
73 | ///
74 | private void CreateSeparateBranchesForTextNodes(HtmlNode node)
75 | {
76 | if (node.IsLineNode() && node.HasBlockElement())
77 | {
78 | var slices = node.GetSlices(new List() { node });
79 |
80 | var parent = node.ParentNode;
81 | var children = node.ParentNode.ChildNodes.ToList();
82 |
83 | foreach (var slice in slices)
84 | {
85 | HtmlNode? newNode = null;
86 |
87 | foreach (var item in slice)
88 | {
89 | if (newNode == null)
90 | {
91 | newNode = item.CloneNode(false);
92 | children.Insert(children.IndexOf(node), newNode);
93 | }
94 | else
95 | {
96 | var temp = item.CloneNode(false);
97 | newNode.AppendChild(temp);
98 | newNode = temp;
99 | }
100 | }
101 |
102 | if (newNode != null)
103 | {
104 | newNode.InnerHtml = newNode.InnerText.Trim();
105 | }
106 | }
107 |
108 | children.Remove(node);
109 |
110 | node.ParentNode.RemoveAllChildren();
111 | foreach (var item in children)
112 | {
113 | parent.AppendChild(item);
114 | }
115 | }
116 | else
117 | {
118 | foreach (var item in node.ChildNodes.ToList())
119 | {
120 | CreateSeparateBranchesForTextNodes(item);
121 | }
122 | }
123 | }
124 | }
125 | }
--------------------------------------------------------------------------------
/HTMLToQPDF/Components/HTMLComponentsArgs.cs:
--------------------------------------------------------------------------------
1 | using QuestPDF.Infrastructure;
2 |
3 | namespace HTMLToQPDF.Components
4 | {
5 | public delegate byte[]? GetImgBySrc(string src);
6 |
7 | internal class HTMLComponentsArgs
8 | {
9 | public Dictionary TextStyles { get; }
10 | public Dictionary> ContainerStyles { get; }
11 | public float ListVerticalPadding { get; }
12 | public GetImgBySrc GetImgBySrc { get; }
13 |
14 | public HTMLComponentsArgs(Dictionary textStyles, Dictionary> containerStyles, float listVerticalPadding, GetImgBySrc getImgBySrc)
15 | {
16 | TextStyles = textStyles;
17 | ContainerStyles = containerStyles;
18 | ListVerticalPadding = listVerticalPadding;
19 | GetImgBySrc = getImgBySrc;
20 | }
21 | }
22 | }
--------------------------------------------------------------------------------
/HTMLToQPDF/Components/ParagraphComponent.cs:
--------------------------------------------------------------------------------
1 | using HtmlAgilityPack;
2 | using HTMLQuestPDF.Extensions;
3 | using HTMLToQPDF.Components;
4 | using QuestPDF.Fluent;
5 | using QuestPDF.Infrastructure;
6 |
7 | namespace HTMLQuestPDF.Components
8 | {
9 | internal class ParagraphComponent : IComponent
10 | {
11 | private readonly List lineNodes;
12 | private readonly Dictionary textStyles;
13 |
14 | public ParagraphComponent(List lineNodes, HTMLComponentsArgs args)
15 | {
16 | this.lineNodes = lineNodes;
17 | this.textStyles = args.TextStyles;
18 | }
19 |
20 | private HtmlNode? GetParrentBlock(HtmlNode node)
21 | {
22 | if (node == null) return null;
23 | return node.IsBlockNode() ? node : GetParrentBlock(node.ParentNode);
24 | }
25 |
26 | private HtmlNode? GetListItemNode(HtmlNode node)
27 | {
28 | if (node == null || node.IsList()) return null;
29 | return node.IsListItem() ? node : GetListItemNode(node.ParentNode);
30 | }
31 |
32 | public void Compose(IContainer container)
33 | {
34 | var listItemNode = GetListItemNode(lineNodes.First()) ?? GetParrentBlock(lineNodes.First());
35 | if (listItemNode == null) return;
36 |
37 | var numberInList = listItemNode.GetNumberInList();
38 |
39 | if (numberInList != -1 || listItemNode.GetListNode() != null)
40 | {
41 | container.Row(row =>
42 | {
43 | var listPrefix = numberInList == -1 ? "" : numberInList == 0 ? "• " : $"{numberInList}. ";
44 | row.AutoItem().MinWidth(26).AlignCenter().Text(listPrefix);
45 | container = row.RelativeItem();
46 | });
47 | }
48 |
49 | var first = lineNodes.First();
50 | var last = lineNodes.First();
51 |
52 | first.InnerHtml = first.InnerHtml.TrimStart();
53 | last.InnerHtml = last.InnerHtml.TrimEnd();
54 |
55 | container.Text(GetAction(lineNodes));
56 | }
57 |
58 | private Action GetAction(List nodes)
59 | {
60 | return text =>
61 | {
62 | lineNodes.ForEach(node => GetAction(node).Invoke(text));
63 | };
64 | }
65 |
66 | private Action GetAction(HtmlNode node)
67 | {
68 | return text =>
69 | {
70 | if (node.NodeType == HtmlNodeType.Text)
71 | {
72 | var span = text.Span(node.InnerText);
73 | GetTextSpanAction(node).Invoke(span);
74 | }
75 | else if (node.IsBr())
76 | {
77 | var span = text.Span("\n");
78 | GetTextSpanAction(node).Invoke(span);
79 | }
80 | else
81 | {
82 | foreach (var item in node.ChildNodes)
83 | {
84 | var action = GetAction(item);
85 | action(text);
86 | }
87 | }
88 | };
89 | }
90 |
91 | private TextSpanAction GetTextSpanAction(HtmlNode node)
92 | {
93 | return spanAction =>
94 | {
95 | var action = GetTextStyles(node);
96 | action(spanAction);
97 | if (node.ParentNode != null)
98 | {
99 | var parrentAction = GetTextSpanAction(node.ParentNode);
100 | parrentAction(spanAction);
101 | }
102 | };
103 | }
104 |
105 | public TextSpanAction GetTextStyles(HtmlNode element)
106 | {
107 | return (span) => span.Style(GetTextStyle(element));
108 | }
109 |
110 | public TextStyle GetTextStyle(HtmlNode element)
111 | {
112 | return textStyles.TryGetValue(element.Name.ToLower(), out TextStyle? style) ? style : TextStyle.Default;
113 | }
114 | }
115 | }
--------------------------------------------------------------------------------
/HTMLToQPDF/Components/Tags/AComponent.cs:
--------------------------------------------------------------------------------
1 | using HtmlAgilityPack;
2 | using HTMLQuestPDF.Extensions;
3 | using HTMLToQPDF.Components;
4 | using QuestPDF.Fluent;
5 | using QuestPDF.Infrastructure;
6 |
7 | namespace HTMLQuestPDF.Components.Tags
8 | {
9 | internal class AComponent : BaseHTMLComponent
10 | {
11 | public AComponent(HtmlNode node, HTMLComponentsArgs args) : base(node, args)
12 | {
13 | }
14 |
15 | protected override IContainer ApplyStyles(IContainer container)
16 | {
17 | container = base.ApplyStyles(container);
18 | return node.TryGetLink(out string link) ? container.Hyperlink(link) : container;
19 | }
20 | }
21 | }
--------------------------------------------------------------------------------
/HTMLToQPDF/Components/Tags/BrComponent.cs:
--------------------------------------------------------------------------------
1 | using HtmlAgilityPack;
2 | using HTMLToQPDF.Components;
3 | using QuestPDF.Fluent;
4 | using QuestPDF.Infrastructure;
5 |
6 | namespace HTMLQuestPDF.Components.Tags
7 | {
8 | internal class BrComponent : BaseHTMLComponent
9 | {
10 | public BrComponent(HtmlNode node, HTMLComponentsArgs args) : base(node, args)
11 | {
12 | }
13 |
14 | protected override void ComposeSingle(IContainer container)
15 | {
16 | container.Text("");
17 | }
18 | }
19 | }
--------------------------------------------------------------------------------
/HTMLToQPDF/Components/Tags/ImgComponent.cs:
--------------------------------------------------------------------------------
1 | using HtmlAgilityPack;
2 | using HTMLToQPDF.Components;
3 | using QuestPDF.Fluent;
4 | using QuestPDF.Helpers;
5 | using QuestPDF.Infrastructure;
6 |
7 | namespace HTMLQuestPDF.Components.Tags
8 | {
9 | internal class ImgComponent : BaseHTMLComponent
10 | {
11 | private readonly GetImgBySrc getImgBySrc;
12 |
13 | public ImgComponent(HtmlNode node, HTMLComponentsArgs args) : base(node, args)
14 | {
15 | this.getImgBySrc = args.GetImgBySrc;
16 | }
17 |
18 | protected override void ComposeSingle(IContainer container)
19 | {
20 | var src = node.GetAttributeValue("src", "");
21 | var img = getImgBySrc(src) ?? Placeholders.Image(200, 100);
22 | container.AlignCenter().Image(img).FitArea();
23 |
24 | }
25 | }
26 | }
--------------------------------------------------------------------------------
/HTMLToQPDF/Components/Tags/ListComponent.cs:
--------------------------------------------------------------------------------
1 | using HtmlAgilityPack;
2 | using HTMLQuestPDF.Extensions;
3 | using HTMLToQPDF.Components;
4 | using QuestPDF.Fluent;
5 | using QuestPDF.Infrastructure;
6 |
7 | namespace HTMLQuestPDF.Components.Tags
8 | {
9 | internal class ListComponent : BaseHTMLComponent
10 | {
11 | public ListComponent(HtmlNode node, HTMLComponentsArgs args) : base(node, args)
12 | {
13 | }
14 |
15 | protected override IContainer ApplyStyles(IContainer container)
16 | {
17 | var first = IsFirstList(node);
18 | return base.ApplyStyles(container).Element(e => first ? e.PaddingVertical(args.ListVerticalPadding) : e);
19 | }
20 |
21 | private bool IsFirstList(HtmlNode node)
22 | {
23 | if (node.ParentNode == null) return true;
24 | return !node.ParentNode.IsList() && IsFirstList(node.ParentNode);
25 | }
26 | }
27 | }
--------------------------------------------------------------------------------
/HTMLToQPDF/Components/Tags/TableComponent.cs:
--------------------------------------------------------------------------------
1 | using HtmlAgilityPack;
2 | using HTMLQuestPDF.Extensions;
3 | using HTMLToQPDF.Components;
4 | using QuestPDF.Fluent;
5 | using QuestPDF.Infrastructure;
6 |
7 | namespace HTMLQuestPDF.Components.Tags
8 | {
9 | internal class TableComponent : BaseHTMLComponent
10 | {
11 | private delegate (uint, uint) GetPositionDelegate(int rowIndex, uint colSpan, uint rowSpan);
12 |
13 | public TableComponent(HtmlNode node, HTMLComponentsArgs args) : base(node, args)
14 | {
15 | }
16 |
17 | private HtmlNodeCollection GetCellNodes()
18 | {
19 | node.Id = String.IsNullOrEmpty(node.Id) ? Guid.NewGuid().ToString() : node.Id;
20 | return node.SelectNodes($"(//table[@id=\"{node.Id}\"]//th | //table[@id=\"{node.Id}\"]//td)");
21 | }
22 |
23 | private List> GetTableLines()
24 | {
25 | var tableItems = GetCellNodes();
26 |
27 | List> lines = new List>();
28 |
29 | List lastLine = new List();
30 | HtmlNode? lastTr = GetTr(tableItems.First());
31 |
32 | foreach (var item in tableItems)
33 | {
34 | var currentTr = GetTr(item);
35 | if (lastTr != currentTr)
36 | {
37 | lines.Add(lastLine);
38 | lastLine = new List();
39 | lastTr = currentTr;
40 | }
41 | lastLine.Add(item);
42 | }
43 |
44 | if (lastLine != null) lines.Add(lastLine);
45 |
46 | return lines;
47 | }
48 |
49 | protected override void ComposeMany(IContainer container)
50 | {
51 | container.Table(table =>
52 | {
53 | var lines = GetTableLines();
54 |
55 | var maxColumns = lines.Max(l => l.Select(n => n.GetAttributeValue("colspan", 1)).Aggregate((a, b) => a + b));
56 |
57 | table.ColumnsDefinition(columns =>
58 | {
59 | for (int i = 0; i < maxColumns; i++)
60 | {
61 | columns.RelativeColumn();
62 | }
63 | });
64 |
65 | var getNextPosition = GetFuncGettingNextPosition(maxColumns);
66 |
67 | foreach (var line in lines)
68 | {
69 | foreach (var cell in line)
70 | {
71 | uint colSpan = (uint)cell.GetAttributeValue("colspan", 1);
72 | uint rowSpan = (uint)cell.GetAttributeValue("rowspan", 1);
73 |
74 | (uint col, uint row) = getNextPosition(lines.IndexOf(line), colSpan, rowSpan);
75 |
76 | table.Cell()
77 | .ColumnSpan(colSpan)
78 | .Column(col)
79 | .Row(row)
80 | .RowSpan(rowSpan)
81 | .Border(1)
82 | .Padding(5)
83 | .Component(cell.GetComponent(args));
84 | }
85 | }
86 | });
87 | }
88 |
89 | private GetPositionDelegate GetFuncGettingNextPosition(int maxColumns)
90 | {
91 | var rows = new List();
92 | return (int rowIndex, uint colSpan, uint rowSpan) =>
93 | {
94 | uint col = 0;
95 | uint row = (uint)rowIndex;
96 |
97 | if (rows.Count <= rowIndex) rows.Add(new bool[maxColumns]);
98 |
99 | while (rows[rowIndex][col])
100 | {
101 | col++;
102 | }
103 |
104 | for (int j = 0; j < rowSpan; j++)
105 | {
106 | for (int i = 0; i < colSpan; i++)
107 | {
108 | if (rows.Count <= rowIndex + j) rows.Add(new bool[maxColumns]);
109 | rows[rowIndex + j][col + i] = true;
110 | }
111 | }
112 |
113 | return (col + 1, row + 1);
114 | };
115 | }
116 |
117 | private HtmlNode? GetTr(HtmlNode node)
118 | {
119 | if (node.IsTable() || node == null) return null;
120 | return node.IsTr() ? node : GetTr(node.ParentNode);
121 | }
122 | }
123 | }
--------------------------------------------------------------------------------
/HTMLToQPDF/Extensions/HTMLComponentExtensions.cs:
--------------------------------------------------------------------------------
1 | using QuestPDF.Fluent;
2 | using QuestPDF.Infrastructure;
3 |
4 | namespace HTMLQuestPDF.Extensions
5 | {
6 | public static class HTMLComponentExtensions
7 | {
8 | public static void HTML(this IContainer container, Action handler)
9 | {
10 | var htmlPageDescriptor = new HTMLDescriptor();
11 | handler(htmlPageDescriptor);
12 | container.Component(htmlPageDescriptor.PDFPage);
13 | }
14 | }
15 | }
--------------------------------------------------------------------------------
/HTMLToQPDF/Extensions/HtmlNodeExtensions.cs:
--------------------------------------------------------------------------------
1 | using HtmlAgilityPack;
2 |
3 | namespace HTMLQuestPDF.Extensions
4 | {
5 | internal static class HtmlNodeExtensions
6 | {
7 | public static HtmlNode? GetListNode(this HtmlNode node)
8 | {
9 | if (node.IsList()) return node;
10 | if (node.ParentNode == null) return null;
11 | return GetListNode(node.ParentNode);
12 | }
13 |
14 | ///
15 | ///
16 | ///
17 | ///
18 | ///
19 | /// -1 - not a list
20 | /// 0 - marked list
21 | /// > 0 - number in the list
22 | ///
23 | public static int GetNumberInList(this HtmlNode node)
24 | {
25 | HtmlNode? listItem = null;
26 |
27 | if (node != null && node.IsListItem()) listItem = node;
28 | if (node?.ParentNode != null && node.ParentNode.IsListItem()) listItem = node.ParentNode;
29 |
30 | if (listItem != null)
31 | {
32 | var listNode = listItem.GetListNode();
33 | if (listNode == null || listNode.IsMarkedList()) return 0;
34 |
35 | return listNode.Descendants("li").Where(n => n.GetListNode() == listNode).ToList().IndexOf(listItem) + 1;
36 | }
37 | return -1;
38 | }
39 |
40 | public static List> GetSlices(this HtmlNode node, List slice)
41 | {
42 | var result = new List>();
43 |
44 | if (!node.ChildNodes.Any() || node.NodeType == HtmlNodeType.Text)
45 | {
46 | result.Add(slice);
47 | return result;
48 | }
49 | else
50 | {
51 | foreach (var item in node.ChildNodes)
52 | {
53 | result.AddRange(GetSlices(item, new List(slice) { item }));
54 | }
55 | }
56 |
57 | return result;
58 | }
59 |
60 | public static bool HasBlockElement(this HtmlNode node)
61 | {
62 | foreach (var child in node.ChildNodes)
63 | {
64 | return child.IsBlockNode() || HasBlockElement(child);
65 | }
66 | return false;
67 | }
68 |
69 | public static bool HasContent(this HtmlNode node)
70 | {
71 | foreach (var item in node.ChildNodes)
72 | {
73 | if (HasContent(item)) return true;
74 | }
75 | return !node.IsEmpty();
76 | }
77 |
78 | public static bool IsBlockNode(this HtmlNode node)
79 | {
80 | return HTMLMapSettings.BlockElements.Contains(node.Name.ToLower());
81 | }
82 |
83 | public static bool IsBr(this HtmlNode node)
84 | {
85 | return node.Name.ToLower() == "br";
86 | }
87 |
88 | public static bool IsTr(this HtmlNode node)
89 | {
90 | return node.Name.ToLower() == "tr";
91 | }
92 |
93 | public static bool IsEmpty(this HtmlNode node)
94 | {
95 | return string.IsNullOrEmpty(node.InnerText) && !node.IsImg() && !node.IsBr();
96 | }
97 |
98 | public static bool IsImg(this HtmlNode node)
99 | {
100 | return node.Name.ToLower() == "img";
101 | }
102 |
103 | public static bool IsTable(this HtmlNode node)
104 | {
105 | return node.Name.ToLower() == "table";
106 | }
107 |
108 | public static bool IsLineNode(this HtmlNode node)
109 | {
110 | return HTMLMapSettings.LineElements.Contains(node.Name.ToLower());
111 | }
112 |
113 | public static bool IsLink(this HtmlNode node)
114 | {
115 | return node.Name.ToLower() == "a";
116 | }
117 |
118 | public static bool IsList(this HtmlNode node)
119 | {
120 | return node.IsMarkedList() || node.IsNumberedList();
121 | }
122 |
123 | public static bool IsListItem(this HtmlNode node)
124 | {
125 | return node.Name.ToLower() == "li";
126 | }
127 |
128 | public static bool IsMarkedList(this HtmlNode node)
129 | {
130 | return node.Name.ToLower() == "ul";
131 | }
132 |
133 | public static bool IsNumberedList(this HtmlNode node)
134 | {
135 | return node.Name.ToLower() == "ol";
136 | }
137 |
138 | public static bool TryGetLink(this HtmlNode node, out string url)
139 | {
140 | var current = node;
141 | while (current != null)
142 | {
143 | if (node.IsLink())
144 | {
145 | url = node.GetAttributeValue("href", "");
146 | return true;
147 | }
148 | current = node.ParentNode;
149 | }
150 |
151 | url = "";
152 | return false;
153 | }
154 | }
155 | }
--------------------------------------------------------------------------------
/HTMLToQPDF/Extensions/IContainerExtensions.cs:
--------------------------------------------------------------------------------
1 | using QuestPDF.Fluent;
2 | using QuestPDF.Infrastructure;
3 |
4 | namespace HTMLQuestPDF.Extensions
5 | {
6 | #if DEBUG
7 |
8 | internal static class IContainerExtensions
9 | {
10 | private static Random random = new Random();
11 |
12 | public static IContainer Debug(this IContainer container, string name) => container.DebugArea(name, String.Format("#{0:X6}", random.Next(0x1000000)));
13 | }
14 |
15 | #endif
16 | }
--------------------------------------------------------------------------------
/HTMLToQPDF/HTMLDescriptor.cs:
--------------------------------------------------------------------------------
1 | using HTMLToQPDF.Components;
2 | using HTMLToQPDF.Utils;
3 | using QuestPDF.Infrastructure;
4 |
5 | namespace HTMLQuestPDF
6 | {
7 | public class HTMLDescriptor
8 | {
9 | internal HTMLComponent PDFPage { get; } = new HTMLComponent();
10 |
11 | public void SetHtml(string html)
12 | {
13 | PDFPage.HTML = html;
14 | }
15 |
16 | public void OverloadImgReceivingFunc(GetImgBySrc getImg)
17 | {
18 | PDFPage.GetImgBySrc = getImg;
19 | }
20 |
21 | public void SetTextStyleForHtmlElement(string tagName, TextStyle style)
22 | {
23 | PDFPage.TextStyles[tagName.ToLower()] = style;
24 | }
25 |
26 | public void SetContainerStyleForHtmlElement(string tagName, Func style)
27 | {
28 | PDFPage.ContainerStyles[tagName.ToLower()] = style;
29 | }
30 |
31 | public void SetListVerticalPadding(float value, Unit unit = Unit.Point)
32 | {
33 | PDFPage.ListVerticalPadding = UnitUtils.ToPoints(value, unit);
34 | }
35 | }
36 | }
--------------------------------------------------------------------------------
/HTMLToQPDF/HTMLToQPDF.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 | enable
6 | enable
7 | Relorer.QuestPDF.HTML
8 |
9 | Relorer
10 | Relorer.QuestPDF.HTML is an extension for QuestPDF that allows to generate PDF from HTML
11 | https://github.com/Relorer/HTMLToQPDF
12 | icon.png
13 | README.md
14 | https://github.com/Relorer/HTMLToQPDF
15 | pdf, file, export, generate, generation, tool, create, creation, render, document, format, quest, html, library, converter, open, source, free, standard, core
16 | MIT
17 | 1.1.0
18 |
19 |
20 |
21 |
22 | True
23 | \
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 | True
35 | \
36 |
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/HTMLToQPDF/StyleSettings.cs:
--------------------------------------------------------------------------------
1 | using HtmlAgilityPack;
2 | using HTMLQuestPDF.Components;
3 | using HTMLQuestPDF.Components.Tags;
4 | using HTMLToQPDF.Components;
5 | using QuestPDF.Infrastructure;
6 |
7 | namespace HTMLQuestPDF
8 | {
9 | internal static class HTMLMapSettings
10 | {
11 | public static readonly string[] LineElements = new string[] {
12 | "a",
13 | "b",
14 | "br",
15 | "del",
16 | "em",
17 | "i",
18 | "s",
19 | "small",
20 | "space",
21 | "strike",
22 | "strong",
23 | "sub",
24 | "sup",
25 | "tbody",
26 | "td",
27 | "th",
28 | "thead",
29 | "tr",
30 | "u",
31 | "img",
32 | "text"
33 | };
34 |
35 | public static readonly string[] BlockElements = new string[] {
36 | "#document",
37 | "div",
38 | "h1",
39 | "h2",
40 | "h3",
41 | "h4",
42 | "h5",
43 | "h6",
44 | "li",
45 | "ol",
46 | "p",
47 | "table",
48 | "ul",
49 | "section",
50 | "header",
51 | "footer",
52 | "head",
53 | "html"
54 | };
55 |
56 | public static IComponent GetComponent(this HtmlNode node, HTMLComponentsArgs args)
57 | {
58 | return node.Name.ToLower() switch
59 | {
60 | "#text" or "h1" or "h2" or "h3" or "h4" or "h5" or "h6" or "b" or "s" or "strike" or "i" or "small" or "u" or "del" or "em" or "strong" or "sub" or "sup"
61 | => new ParagraphComponent(new List() { node }, args),
62 | "br" => new BrComponent(node, args),
63 | "a" => new AComponent(node, args),
64 | "div" => new BaseHTMLComponent(node, args),
65 | "table" => new TableComponent(node, args),
66 | "ul" or "ol" => new ListComponent(node, args),
67 | "img" => new ImgComponent(node, args),
68 | _ => new BaseHTMLComponent(node, args),
69 | };
70 | }
71 | }
72 | }
--------------------------------------------------------------------------------
/HTMLToQPDF/Utils/HTMLUtils.cs:
--------------------------------------------------------------------------------
1 | using System.Text.RegularExpressions;
2 | using System.Web;
3 |
4 | namespace HTMLQuestPDF.Utils
5 | {
6 | internal static class HTMLUtils
7 | {
8 | private static readonly string spaceAfterLineElementPattern = @$"\S<\/({string.Join("|", HTMLMapSettings.LineElements)})> ";
9 |
10 | public static string PrepareHTML(string value)
11 | {
12 | var result = HttpUtility.HtmlDecode(value);
13 | result = RemoveExtraSpacesAndBreaks(result);
14 | result = RemoveSpacesAroundBr(result);
15 | result = WrapSpacesAfterLineElement(result);
16 | result = RemoveSpacesBetweenElements(result);
17 | return result;
18 | }
19 |
20 | private static string RemoveExtraSpacesAndBreaks(string html)
21 | {
22 | return Regex.Replace(html, @"[ \r\n]+", " ");
23 | }
24 |
25 | private static string RemoveSpacesBetweenElements(string html)
26 | {
27 | return Regex.Replace(html, @">\s+<", _ => @"><").Replace(" ", " ");
28 | }
29 |
30 | private static string RemoveSpacesAroundBr(string html)
31 | {
32 | return Regex.Replace(html, @"\s+<\/?br\s*\/?>\s+", _ => @$" ");
33 | }
34 |
35 | private static string WrapSpacesAfterLineElement(string html)
36 | {
37 | return Regex.Replace(html, spaceAfterLineElementPattern, m => $"{m.Value.Substring(0, m.Value.Length - 1)} ");
38 | }
39 | }
40 | }
--------------------------------------------------------------------------------
/HTMLToQPDF/Utils/ImgUtils.cs:
--------------------------------------------------------------------------------
1 | using System.Net;
2 |
3 | namespace HTMLToQPDF.Utils
4 | {
5 | internal static class ImgUtils
6 | {
7 |
8 | private static HttpClient _SingletonClient;
9 |
10 | static ImgUtils() {
11 |
12 | if (_SingletonClient == null)
13 | {
14 | _SingletonClient = new HttpClient();
15 | }
16 | }
17 |
18 | ///
19 | /// Call this manually at the end of the appliction life : Static classes don't auto Dispose.
20 | ///
21 | public static void Dispose() {
22 |
23 | if (_SingletonClient != null)
24 | {
25 | _SingletonClient.Dispose();
26 | }
27 | }
28 |
29 | public static byte[]? GetImgBySrc(string src)
30 | {
31 | try
32 | {
33 | if (src.Contains("base64"))
34 | {
35 | var base64 = src.Substring(src.IndexOf("base64,") + "base64,".Length);
36 | return Convert.FromBase64String(base64);
37 | }
38 |
39 | else {
40 | return Download(src).Result;
41 | }
42 |
43 |
44 | }
45 | catch
46 | {
47 | return null;
48 | }
49 | }
50 |
51 | private static Task Download(string src)
52 | {
53 |
54 | if (_SingletonClient != null)
55 | {
56 | Uri uri = new Uri(src);
57 | return _SingletonClient.GetByteArrayAsync(uri);
58 | }
59 | else
60 | {
61 | // To prevent memory and IO socket Leaks HttpClient should be a singleton for life.
62 | throw new Exception("HttpClient not Available");
63 | }
64 | }
65 |
66 | }
67 | }
--------------------------------------------------------------------------------
/HTMLToQPDF/Utils/UnitUtils.cs:
--------------------------------------------------------------------------------
1 | using QuestPDF.Infrastructure;
2 |
3 | namespace HTMLToQPDF.Utils
4 | {
5 | internal static class UnitUtils
6 | {
7 | public static float ToPoints(float value, Unit unit)
8 | {
9 | return value * GetConversionFactor();
10 | float GetConversionFactor()
11 | {
12 | return unit switch
13 | {
14 | Unit.Point => 1f,
15 | Unit.Meter => 2834.64575f,
16 | Unit.Centimetre => 28.3464565f,
17 | Unit.Millimetre => 2.83464575f,
18 | Unit.Feet => 864f,
19 | Unit.Inch => 72f,
20 | Unit.Mil => 0.072f,
21 | _ => throw new ArgumentOutOfRangeException("unit", unit, null),
22 | };
23 | }
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) [year] [fullname]
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Relorer.QuestPDF.HTML is an extension for QuestPDF that allows to generate PDF from HTML
2 |
3 | [QuestPDF](https://github.com/QuestPDF/QuestPDF) currently does not support inserting html into a pdf document. So I wrote a small library for this. It doesn't support the full functionality of html and css, but I think it should be enough for most cases.
4 |
5 |
6 |
7 | #### Dependencies
8 | - [QuestPDF](https://github.com/QuestPDF/QuestPDF)
9 | - [HtmlAgilityPack](https://html-agility-pack.net/) is used for html parsing
10 |
11 | #### Usage
12 |
13 | The simplest example of use:
14 | ```
15 | Document.Create(container =>
16 | {
17 | container.Page(page =>
18 | {
19 | page.Content().Column(col =>
20 | {
21 | col.Item().HTML(handler =>
22 | {
23 | handler.SetHtml(html);
24 | });
25 | });
26 | });
27 | }).GeneratePdf(path);
28 | ```
29 | **I strongly recommend overloading the image upload method, because the outdated WebClient is used by default without using asynchronous.**
30 | To do this, you can use the OverloadImgReceivingFunc:
31 | ```
32 | col.Item().HTML(handler =>
33 | {
34 | handler.OverloadImgReceivingFunc(GetImgBySrc);
35 | handler.SetHtml(html);
36 | });
37 | ```
38 |
39 | You can customize the styles of text and containers for tags:
40 | ```
41 | handler.SetTextStyleForHtmlElement("div", TextStyle.Default.FontColor(Colors.Grey.Medium));
42 | handler.SetTextStyleForHtmlElement("h1", TextStyle.Default.FontColor(Colors.DeepOrange.Accent4).FontSize(32).Bold());
43 | handler.SetContainerStyleForHtmlElement("table", c => c.Background(Colors.Pink.Lighten5));
44 | handler.SetContainerStyleForHtmlElement("ul", c => c.PaddingVertical(10));
45 | ```
46 |
47 | You can set the vertical padding size for lists. This padding will not apply to sub-lists:
48 | ```
49 | handler.SetListVerticalPadding(40);
50 | ```
51 |
52 | You can use [HTMLToQPDF.Example](https://github.com/Relorer/HTMLToQPDF/releases/tag/1.0.0) to try out the capabilities of this extension.
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 | Default Styles
62 | Options for changing styles
63 |
64 |
65 |
66 |
67 |
68 |
69 |
--------------------------------------------------------------------------------