-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmd2pdf.ps1
More file actions
379 lines (316 loc) · 12.5 KB
/
Copy pathmd2pdf.ps1
File metadata and controls
379 lines (316 loc) · 12.5 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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
#!/usr/bin/env pwsh
<#
.SYNOPSIS
Convert markdown files to PDF or DOCX.
.DESCRIPTION
Converts one or more markdown files to PDF (via Pandoc + Typst with GitHub styling)
or DOCX (via Pandoc directly). PDF output requires both Pandoc (v3.2+) and Typst.
DOCX output requires only Pandoc.
.PARAMETER InputPath
Path to a markdown file or directory containing markdown files.
.PARAMETER OutputPath
Directory where output files will be saved. Defaults to './output'.
.PARAMETER Format
Output format: 'pdf' (default) or 'docx'.
.PARAMETER Recursive
If specified and InputPath is a directory, process markdown files in subdirectories.
.PARAMETER InstallTypst
If specified, downloads and installs Typst if not already installed (PDF only).
.EXAMPLE
.\md2pdf.ps1 -InputPath "README.md"
Convert a single markdown file to PDF.
.EXAMPLE
.\md2pdf.ps1 -InputPath "README.md" -Format docx
Convert a single markdown file to DOCX.
.EXAMPLE
.\md2pdf.ps1 -InputPath "./docs" -Recursive
Convert all markdown files in the docs directory and subdirectories to PDF.
.EXAMPLE
.\md2pdf.ps1 -InputPath "./docs" -OutputPath "./output" -Recursive
Convert all markdown files to PDF with an explicit output directory.
.EXAMPLE
.\md2pdf.ps1 -InputPath "./docs" -Format docx -Recursive
Convert all markdown files in the docs directory and subdirectories to DOCX.
.EXAMPLE
.\md2pdf.ps1 -InstallTypst
Install Typst before converting documents.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$false, Position=0)]
[string]$InputPath,
[Parameter(Mandatory=$false)]
[string]$OutputPath = "./output",
[Parameter(Mandatory=$false)]
[ValidateSet('pdf', 'docx')]
[string]$Format = "pdf",
[Parameter(Mandatory=$false)]
[switch]$Recursive,
[Parameter(Mandatory=$false)]
[switch]$InstallTypst
)
# Set error action preference
$ErrorActionPreference = "Stop"
# Function to check if a command exists
function Test-CommandExists {
param([string]$Command)
try {
$null = Get-Command $Command -ErrorAction Stop
return $true
}
catch {
return $false
}
}
# Function to install Typst
function Install-Typst {
Write-Host "Installing Typst..." -ForegroundColor Cyan
$typstVersion = "v0.12.0"
$arch = if ([System.Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture -eq [System.Runtime.InteropServices.Architecture]::Arm64) { "aarch64" } else { "x86_64" }
$platform = if ($IsWindows -or $env:OS -match "Windows") { "$arch-pc-windows-msvc" }
elseif ($IsMacOS) { "$arch-apple-darwin" }
elseif ($IsLinux) { "$arch-unknown-linux-musl" }
else { "$arch-pc-windows-msvc" }
$downloadUrl = "https://github.com/typst/typst/releases/download/$typstVersion/typst-$platform.zip"
$tempZip = Join-Path $env:TEMP "typst.zip"
$installDir = Join-Path $HOME ".typst"
try {
# Download Typst
Write-Host "Downloading Typst $typstVersion..." -ForegroundColor Cyan
Invoke-WebRequest -Uri $downloadUrl -OutFile $tempZip -UseBasicParsing
# Create install directory
if (-not (Test-Path $installDir)) {
New-Item -ItemType Directory -Path $installDir -Force | Out-Null
}
# Extract
Write-Host "Extracting..." -ForegroundColor Cyan
Expand-Archive -Path $tempZip -DestinationPath $installDir -Force
# Add to PATH
$typstBin = Join-Path $installDir "typst-$platform"
$currentPath = [Environment]::GetEnvironmentVariable("Path", "User")
if ($currentPath -notlike "*$typstBin*") {
[Environment]::SetEnvironmentVariable("Path", "$currentPath;$typstBin", "User")
$env:Path = "$env:Path;$typstBin"
}
Write-Host "✓ Typst installed successfully to: $typstBin" -ForegroundColor Green
Write-Host " Please restart your terminal for PATH changes to take effect." -ForegroundColor Yellow
Remove-Item $tempZip -Force
return $true
}
catch {
Write-Host "✗ Failed to install Typst: $_" -ForegroundColor Red
return $false
}
}
# Convert a single markdown file to PDF (via Typst) or DOCX (via Pandoc directly)
function Convert-MarkdownFile {
param(
[string]$MarkdownFile,
[string]$OutputFile,
[string]$OutputFormat
)
Write-Host "Converting: $MarkdownFile" -ForegroundColor Cyan
if ($OutputFormat -eq 'docx') {
try {
$pandocOutput = & pandoc $MarkdownFile -o $OutputFile 2>&1
if ($LASTEXITCODE -eq 0) {
Write-Host "✓ Created: $OutputFile" -ForegroundColor Green
return $true
}
else {
Write-Host "✗ Failed to convert: $MarkdownFile" -ForegroundColor Red
if ($pandocOutput) { Write-Host ($pandocOutput -join "`n") -ForegroundColor Red }
return $false
}
}
catch {
Write-Host "✗ Failed to convert: $MarkdownFile" -ForegroundColor Red
Write-Host " Error: $_" -ForegroundColor Red
return $false
}
}
# PDF path: Markdown → Typst (with GitHub styling) → PDF
# Place the .typ file next to the source markdown so Typst resolves relative
# paths (images, includes) against the correct directory.
$typstBaseName = [System.IO.Path]::GetFileNameWithoutExtension($OutputFile)
$sourceDir = Split-Path $MarkdownFile -Parent
$typstFile = Join-Path $sourceDir "._md2pdf_$typstBaseName.typ"
try {
# Step 1: Convert markdown to Typst (--standalone preserves YAML front matter)
$pandocOutput = & pandoc $MarkdownFile -o $typstFile -t typst --standalone 2>&1
if ($LASTEXITCODE -ne 0) {
Write-Host "✗ Failed to convert markdown to Typst: $MarkdownFile" -ForegroundColor Red
if ($pandocOutput) { Write-Host ($pandocOutput -join "`n") -ForegroundColor Red }
return $false
}
# Step 2: Add GitHub styling to the Typst file
$typstContent = Get-Content $typstFile -Raw
$styledTypst = @"
// GitHub-style formatting
#set page(margin: (x: 2.5cm, y: 2.5cm))
#set text(font: ("Segoe UI", "Arial", "Helvetica", "DejaVu Sans"), size: 11pt, fill: rgb("#24292e"))
#set par(justify: false, leading: 0.65em)
#show heading.where(level: 1): it => {
set text(size: 2em, weight: 600)
block(below: 1em, above: 1.5em)[
#it.body
#v(0.3em)
#line(length: 100%, stroke: 0.5pt + rgb("#eaecef"))
]
}
#show heading.where(level: 2): it => {
set text(size: 1.5em, weight: 600)
block(below: 1em, above: 1.5em)[
#it.body
#v(0.3em)
#line(length: 100%, stroke: 0.5pt + rgb("#eaecef"))
]
}
#show link: set text(fill: rgb("#0366d6"))
#show raw.where(block: false): it => box(
fill: rgb("#f6f8fa"),
outset: (x: 3pt, y: 2pt),
radius: 3pt,
)[#set text(font: ("Consolas", "Menlo", "DejaVu Sans Mono", "Courier New"), size: 0.85em); #it]
#show raw.where(block: true): it => block(
fill: rgb("#f6f8fa"),
width: 100%,
inset: 1em,
radius: 6pt,
)[#set text(font: ("Consolas", "Menlo", "DejaVu Sans Mono", "Courier New"), size: 0.85em); #it]
#show quote: it => pad(
left: 1em,
block(
width: 100%,
stroke: (left: 0.25em + rgb("#dfe2e5")),
inset: (left: 1em, rest: 0.5em)
)[#set text(fill: rgb("#6a737d")); #it]
)
$typstContent
"@
Set-Content -Path $typstFile -Value $styledTypst -Encoding UTF8
# Step 3: Compile Typst to PDF
$typstOutput = & typst compile $typstFile $OutputFile 2>&1
if ($LASTEXITCODE -eq 0) {
Remove-Item $typstFile -Force -ErrorAction SilentlyContinue
Write-Host "✓ Created: $OutputFile" -ForegroundColor Green
return $true
}
else {
Write-Host "✗ Failed to compile Typst to PDF: $MarkdownFile" -ForegroundColor Red
if ($typstOutput) { Write-Host ($typstOutput -join "`n") -ForegroundColor Red }
Write-Host " Typst file saved at: $typstFile (for debugging)" -ForegroundColor Yellow
return $false
}
}
catch {
Write-Host "✗ Failed to convert: $MarkdownFile" -ForegroundColor Red
Write-Host " Error: $_" -ForegroundColor Red
return $false
}
}
# Main script execution
Write-Host "=== Markdown Converter ===" -ForegroundColor Yellow
Write-Host ""
# Handle InstallTypst flag
if ($InstallTypst) {
if (Install-Typst) {
Write-Host ""
Write-Host "Typst has been installed. Please restart your terminal and run the script again." -ForegroundColor Yellow
exit 0
}
exit 1
}
# Validate that InputPath is provided
if (-not $InputPath) {
Write-Host "ERROR: InputPath parameter is required" -ForegroundColor Red
Write-Host ""
Write-Host "Usage: .\md2pdf.ps1 -InputPath <path> [-OutputPath <dir>] [-Format pdf|docx]" -ForegroundColor Yellow
Write-Host "Use -InstallTypst flag to install Typst first (required for PDF output)" -ForegroundColor Yellow
exit 1
}
# Check Pandoc (required for all formats)
if (-not (Test-CommandExists "pandoc")) {
Write-Host "ERROR: pandoc is not installed or not in PATH" -ForegroundColor Red
Write-Host "Please install pandoc from: https://pandoc.org/installing.html" -ForegroundColor Yellow
exit 1
}
$pandocVersionRaw = (pandoc --version | Select-Object -First 1) -replace "pandoc ", ""
# Typst and pandoc 3.2+ are only required for PDF output
if ($Format -eq 'pdf') {
$pandocVersionParsed = [version]($pandocVersionRaw -replace "-.*", "")
if ($pandocVersionParsed -lt [version]"3.2") {
Write-Host "ERROR: pandoc $pandocVersionRaw is too old. Version 3.2 or higher is required for PDF output." -ForegroundColor Red
Write-Host "Please upgrade pandoc from: https://pandoc.org/installing.html" -ForegroundColor Yellow
exit 1
}
if (-not (Test-CommandExists "typst")) {
Write-Host "ERROR: Typst is not installed or not in PATH" -ForegroundColor Red
Write-Host ""
Write-Host "To install Typst, run:" -ForegroundColor Yellow
Write-Host " .\md2pdf.ps1 -InstallTypst" -ForegroundColor Cyan
Write-Host ""
Write-Host "Or install manually from: https://github.com/typst/typst/releases" -ForegroundColor Yellow
exit 1
}
$typstVersionFull = (typst --version) -replace "typst ", "" -replace " \(.*\)", ""
Write-Host "Using pandoc $pandocVersionRaw with Typst $typstVersionFull (format: pdf)" -ForegroundColor Cyan
}
else {
Write-Host "Using pandoc $pandocVersionRaw (format: docx)" -ForegroundColor Cyan
}
Write-Host ""
# Create output directory if it doesn't exist
if (-not (Test-Path $OutputPath)) {
New-Item -ItemType Directory -Path $OutputPath | Out-Null
Write-Host "Created output directory: $OutputPath" -ForegroundColor Green
}
# Get markdown files to process
$markdownFiles = @()
if (Test-Path $InputPath -PathType Container) {
Write-Host "Searching for markdown files in: $InputPath" -ForegroundColor Cyan
if ($Recursive) {
$markdownFiles = Get-ChildItem -Path $InputPath -Filter "*.md" -Recurse -File
}
else {
$markdownFiles = Get-ChildItem -Path $InputPath -Filter "*.md" -File
}
}
elseif (Test-Path $InputPath -PathType Leaf) {
if ($InputPath -match '\.md$') {
$markdownFiles = @(Get-Item $InputPath)
}
else {
Write-Host "ERROR: Input file is not a markdown file (.md)" -ForegroundColor Red
exit 1
}
}
else {
Write-Host "ERROR: Input path not found: $InputPath" -ForegroundColor Red
exit 1
}
if ($markdownFiles.Count -eq 0) {
Write-Host "No markdown files found." -ForegroundColor Yellow
exit 0
}
Write-Host "Found $($markdownFiles.Count) markdown file(s)" -ForegroundColor Cyan
Write-Host ""
# Process each markdown file
$successCount = 0
$failCount = 0
foreach ($mdFile in $markdownFiles) {
$outputFileName = [System.IO.Path]::GetFileNameWithoutExtension($mdFile.Name) + ".$Format"
$outputFilePath = Join-Path $OutputPath $outputFileName
if (Convert-MarkdownFile -MarkdownFile $mdFile.FullName -OutputFile $outputFilePath -OutputFormat $Format) {
$successCount++
}
else {
$failCount++
}
}
# Summary
Write-Host ""
Write-Host "=== Conversion Complete ===" -ForegroundColor Yellow
Write-Host "Successful: $successCount" -ForegroundColor Green
Write-Host "Failed: $failCount" -ForegroundColor $(if ($failCount -gt 0) { "Red" } else { "Gray" })
Write-Host "Output directory: $OutputPath" -ForegroundColor Cyan