# Export MagFass2Car guide Markdown to PDF (requires Chrome or Edge) param( [string]$InputMd = "$PSScriptRoot\MagFass2Car使用指南.md", [string]$OutputPdf = "$PSScriptRoot\MagFass2Car使用指南.pdf" ) $ErrorActionPreference = 'Stop' [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 function Escape-Html([string]$text) { return [System.Net.WebUtility]::HtmlEncode($text) } function Convert-MarkdownToHtml([string]$markdown) { $lines = $markdown -split "`r?`n" $sb = New-Object System.Text.StringBuilder $inCode = $false $inTable = $false $tableRows = New-Object System.Collections.Generic.List[string[]] $inList = $false $listOrdered = $false function Flush-Table { param($builder, [ref]$inTableRef, $rows) if (-not $inTableRef.Value) { return } [void]$builder.AppendLine('
')
$inCode = $true
}
continue
}
if ($inCode) {
[void]$sb.AppendLine((Escape-Html $line))
continue
}
if ($line -match '^\s*\|(.+)\|\s*$') {
Close-List $sb ([ref]$inList) ([ref]$listOrdered)
if ($line -match '^\s*\|[-:\s|]+\|\s*$') { continue }
$cells = ($line.Trim('|') -split '\|') | ForEach-Object { $_.Trim() }
$tableRows.Add($cells)
$inTable = $true
continue
} else {
Flush-Table $sb ([ref]$inTable) $tableRows
}
if ($line -match '^(#{1,6})\s+(.+)$') {
Close-List $sb ([ref]$inList) ([ref]$listOrdered)
$level = $Matches[1].Length
$text = $Matches[2]
[void]$sb.AppendLine("$(Escape-Html $text) ")
continue
}
if ($line -match '^>\s*(.+)$') {
Close-List $sb ([ref]$inList) ([ref]$listOrdered)
$text = $Matches[1]
[void]$sb.AppendLine("$(Escape-Html $text)
")
continue
}
if ($line -match '^---\s*$') {
Close-List $sb ([ref]$inList) ([ref]$listOrdered)
[void]$sb.AppendLine('
')
continue
}
if ($line -match '^\d+\.\s+(.+)$') {
if (-not $inList) { [void]$sb.AppendLine(''); $inList = $true; $listOrdered = $true }
$text = Escape-Html $Matches[1]
$text = $text -replace '`([^`]+)`', '$1'
[void]$sb.AppendLine("- $text
")
continue
}
if ($line -match '^-\s+(.+)$') {
if (-not $inList) { [void]$sb.AppendLine(''); $inList = $true; $listOrdered = $false }
$text = Escape-Html $Matches[1]
$text = $text -replace '`([^`]+)`', '$1'
[void]$sb.AppendLine("- $text
")
continue
}
if ([string]::IsNullOrWhiteSpace($line)) {
Close-List $sb ([ref]$inList) ([ref]$listOrdered)
continue
}
Close-List $sb ([ref]$inList) ([ref]$listOrdered)
$p = Escape-Html $line
$p = $p -replace '`([^`]+)`', '$1'
[void]$sb.AppendLine("$p
")
}
Flush-Table $sb ([ref]$inTable) $tableRows
Close-List $sb ([ref]$inList) ([ref]$listOrdered)
if ($inCode) { [void]$sb.AppendLine('
') }
return $sb.ToString()
}
if (-not (Test-Path $InputMd)) {
throw "Markdown file not found: $InputMd"
}
$md = Get-Content -Path $InputMd -Raw -Encoding UTF8
$body = Convert-MarkdownToHtml $md
$htmlPath = [System.IO.Path]::ChangeExtension($OutputPdf, '.html')
$html = @"