Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save yetanotherchris/12aa51288042bc437aa012f634c6e43b to your computer and use it in GitHub Desktop.
Save yetanotherchris/12aa51288042bc437aa012f634c6e43b to your computer and use it in GitHub Desktop.
Convert ePub to Markdown then to HTML then to PDF (in Powershell)
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string]$FileName
)
# This script converts an ePub to Markdown, removing formatting that something like 11reader can't read.
# Then it converts the Markdown to HTML, and finally the HTML to PDF, if you want to retain the images.
# Needs Chrome and NodeJS installed, and Windows.
# Bulk usage:
# Get-ChildItem *.epub | ForEach-Object { .\convert.ps1 $_.Name }
# Check if the file exists
if (Test-Path $FileName) {
Write-Host "The file '$FileName' exists."
} else {
Write-Host "The file '$FileName' does not exist."
}
# epub2md is an NPM tool: https://github.com/uxiew/epub2MD
# npm install epub2md -g
$epubDir = $FileName -replace ".epub", ""
$mdFilename = $FileName -replace ".epub", ".md"
$htmlFilename = $FileName -replace ".epub", ".html"
$pdfFilename = $FileName -replace ".epub", ".pdf"
# Convert the epub to markdown (epub is a zip file with XHTML inside)
epub2md -M $FileName
# Concatenate all the markdown files it created into one
$files = dir "$($epubDir)/*.md"
get-content $files | set-content $mdFilename
# Convert the single markdown file to HTML
$o = ConvertFrom-Markdown $mdFilename
set-content -value $o.Html -Path "$htmlFilename"
# Copy it to the epub directory so images work
cp $htmlFilename "$epubDir/$htmlFilename"
pushd $epubDir
# Use Chrome to convert to a PDF and open the PDF
$fullPath = $(pwd)
& "C:\Program Files\Google\Chrome\Application\chrome.exe" --headless --disable-gpu --no-pdf-header-footer --run-all-compositor-stages-before-draw --print-to-pdf="$fullPath\$pdfFilename" file:///$fullPath/$htmlFilename
sleep 3
echo "$pdfFilename successfully created"
popd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment