Files
akmon/Convert-MermaidToPdf.ps1
2026-01-20 08:04:15 +08:00

90 lines
2.5 KiB
PowerShell

param(
[Parameter(Mandatory=$true)]
[string]$InputFile,
[Parameter(Mandatory=$true)]
[string]$OutputFile
)
Write-Host "Converting $InputFile to $OutputFile with Mermaid support..."
# Read the markdown content
$content = Get-Content $InputFile -Raw
# Create temp directory
$tempDir = Join-Path $env:TEMP ("mermaid_temp_" + [guid]::NewGuid().ToString())
New-Item -ItemType Directory -Path $tempDir | Out-Null
# Process mermaid blocks
$mermaidPattern = '(?s)```mermaid\s*\n(.*?)\n```'
$matches = [regex]::Matches($content, $mermaidPattern)
for ($i = 0; $i -lt $matches.Count; $i++) {
$match = $matches[$i]
$mermaidCode = $match.Groups[1].Value
# Create temp mermaid file
$mermaidFile = Join-Path $tempDir "diagram_$i.mmd"
$pngFile = Join-Path $tempDir "diagram_$i.png"
# Write mermaid code to file
$mermaidCode | Out-File -FilePath $mermaidFile -Encoding UTF8
# Try to find mmdc executable
$mmdcPaths = @(
"mmdc",
(Join-Path $env:APPDATA "npm\mmdc.cmd"),
"D:\scoop\apps\yarn\current\global\bin\mmdc.cmd"
)
$mmdcFound = $false
foreach ($mmdcPath in $mmdcPaths) {
if (Test-Path $mmdcPath) {
Write-Host "Using mmdc at: $mmdcPath"
& $mmdcPath -i $mermaidFile -o $pngFile -t dark -b transparent
if ($LASTEXITCODE -eq 0) {
$mmdcFound = $true
break
}
}
}
# Replace mermaid code with image reference
if ((Test-Path $pngFile) -and $mmdcFound) {
$imageRef = "![Mermaid Diagram $i]($pngFile)"
$content = $content.Replace($match.Value, $imageRef)
}
}
# Write processed content to temp file
$processedFile = Join-Path $tempDir "processed.md"
$content | Out-File -FilePath $processedFile -Encoding UTF8
# Convert to PDF using pandoc with wkhtmltopdf if available, otherwise try other engines
$engines = @("--pdf-engine=wkhtmltopdf", "--pdf-engine=weasyprint", "")
$success = $false
foreach ($engine in $engines) {
try {
if ($engine) {
pandoc $processedFile -o $OutputFile $engine
} else {
pandoc $processedFile -o $OutputFile
}
if ($LASTEXITCODE -eq 0) {
$success = $true
break
}
} catch {
continue
}
}
# Clean up
Remove-Item $tempDir -Recurse -Force
if ($success) {
Write-Host "Conversion completed successfully!"
} else {
Write-Host "Conversion failed - no suitable PDF engine found!"
}