-
-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathCmdletConvertHTMLToPDF.cs
More file actions
177 lines (157 loc) · 6.03 KB
/
CmdletConvertHTMLToPDF.cs
File metadata and controls
177 lines (157 loc) · 6.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
using System;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace PSWritePDF.Cmdlets;
/// <summary>Converts HTML content to a PDF file.</summary>
/// <para>Accepts HTML from a URI, string content, or file and writes a PDF to disk.</para>
/// <list type="alertSet">
/// <item>
/// <term>Note</term>
/// <description>Existing output files are overwritten when <c>-Force</c> is specified.</description>
/// </item>
/// </list>
/// <example>
/// <summary>Convert from URI.</summary>
/// <code>
/// <prefix>PS> </prefix>Convert-HTMLToPDF -Uri 'https://example.com' -OutputFilePath 'page.pdf'
/// </code>
/// <para>Downloads the page and saves it as PDF.</para>
/// </example>
/// <example>
/// <summary>Convert from file with CSS.</summary>
/// <code>
/// <prefix>PS> </prefix>Convert-HTMLToPDF -FilePath 'index.html' -CssFilePath 'style.css' -OutputFilePath 'out.pdf'
/// </code>
/// <para>Applies the specified CSS and writes the PDF.</para>
/// </example>
/// <seealso href="https://learn.microsoft.com/dotnet/api/system.management.automation.cmdlet">MS Learn</seealso>
/// <seealso href="https://evotec.xyz/hub/scripts/pswritepdf/">Project documentation</seealso>
[Cmdlet(VerbsData.Convert, "HTMLToPDF", DefaultParameterSetName = ParameterSetNames.Uri, SupportsShouldProcess = true)]
public class CmdletConvertHTMLToPDF : AsyncPSCmdlet
{
private static class ParameterSetNames
{
public const string Uri = "Uri";
public const string Content = "Content";
public const string File = "File";
}
/// <summary>URI of the HTML page.</summary>
[Parameter(Mandatory = true, ParameterSetName = ParameterSetNames.Uri)]
public string Uri { get; set; }
/// <summary>Raw HTML content.</summary>
[Parameter(Mandatory = true, ParameterSetName = ParameterSetNames.Content)]
public string Content { get; set; }
/// <summary>Path to an HTML file.</summary>
[Parameter(Mandatory = true, ParameterSetName = ParameterSetNames.File)]
public string FilePath { get; set; }
/// <summary>Output PDF path.</summary>
[Parameter(Mandatory = true)]
public string OutputFilePath { get; set; }
/// <summary>Open the PDF after creation.</summary>
[Parameter]
public SwitchParameter Open { get; set; }
/// <summary>Overwrite existing files.</summary>
[Parameter]
public SwitchParameter Force { get; set; }
/// <summary>Base URI for relative links.</summary>
[Parameter]
public string BaseUri { get; set; }
/// <summary>Paths to CSS files to include.</summary>
[Parameter]
public string[] CssFilePath { get; set; }
protected override async Task ProcessRecordAsync()
{
string html = Content;
string? filePath = null;
if (ParameterSetName == ParameterSetNames.File)
{
filePath = GetUnresolvedProviderPathFromPSPath(FilePath);
if (!File.Exists(filePath))
{
WriteWarning($"File '{filePath}' doesn't exist.");
return;
}
html = File.ReadAllText(filePath);
}
else if (ParameterSetName == ParameterSetNames.Uri)
{
try
{
using var client = new HttpClient();
html = await client.GetStringAsync(Uri).ConfigureAwait(false);
}
catch (Exception ex)
{
WriteWarning($"Failed to download '{Uri}': {ex.Message}");
return;
}
}
if (string.IsNullOrEmpty(html))
{
return;
}
var outputFilePath = GetUnresolvedProviderPathFromPSPath(OutputFilePath);
if (File.Exists(outputFilePath) && !Force.IsPresent)
{
WriteWarning($"File '{outputFilePath}' already exists. Use -Force to overwrite.");
return;
}
if (!ShouldProcess(outputFilePath, "Convert HTML to PDF"))
{
return;
}
try
{
var cssFiles = CssFilePath?.Select(p => GetUnresolvedProviderPathFromPSPath(p)).ToArray();
if (cssFiles != null && cssFiles.Length > 0)
{
var cssContent = new StringBuilder();
foreach (var css in cssFiles.Where(File.Exists))
{
cssContent.AppendLine(File.ReadAllText(css));
}
foreach (var missing in cssFiles.Where(p => !File.Exists(p)))
{
WriteWarning($"CSS file '{missing}' doesn't exist.");
}
if (cssContent.Length > 0)
{
var styleTag = $"<style>{cssContent}</style>";
var headCloseIndex = html.IndexOf("</head>", StringComparison.OrdinalIgnoreCase);
html = headCloseIndex >= 0
? html.Insert(headCloseIndex, styleTag)
: styleTag + html;
}
}
using var fs = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write);
var properties = new iText.Html2pdf.ConverterProperties();
var baseUri = !string.IsNullOrEmpty(BaseUri) ? GetUnresolvedProviderPathFromPSPath(BaseUri) : null;
if (!string.IsNullOrEmpty(baseUri))
{
properties.SetBaseUri(baseUri);
}
iText.Html2pdf.HtmlConverter.ConvertToPdf(html, fs, properties);
if (Open.IsPresent)
{
var psi = new System.Diagnostics.ProcessStartInfo
{
FileName = outputFilePath,
UseShellExecute = true,
};
System.Diagnostics.Process.Start(psi);
}
if (ShouldProcess(outputFilePath, "Write output"))
{
WriteObject(outputFilePath);
}
}
catch (Exception ex)
{
WriteWarning($"Error converting to PDF: {ex.Message}");
}
}
}