My current workaround
Run: ENABLE_PDF_EXPORT=1 mkdocs build
. Each markdown file will be exported to a PDF file.
Then, I will define the order of all PDFs when merging into one unique file by putting the PDF name from top to bottom:
In chapters.txt
:
A.pdf
B.pdf
C.pdf
...
Then run the following script. Remember that this script is just a hint of what I have done, it has not been completed yet and has not run "as is".
# ================================================================================================
# Move all pdfs from "site" (the output dir of pdf exporting) to the scripts/pdf_export/pdfs
# ================================================================================================
find site -name "*.pdf" -exec mv {} scripts/pdf_export/pdfs \;
cd scripts/pdf_export/pdfs
# ================================================================================================
# Merge all pdfs into one single pdf file wrt the file name's order in chapters.txt
# ================================================================================================
# REMEMBER to put the chapters.txt into scripts/pdf_export/pdfs.
# Install: https://www.pdflabs.com/tools/pdftk-server/
# Install for M1 only: https://stackoverflow.com/a/60889993/6563277 to avoid the "pdftk: Bad CPU type in executable" on Mac
pdftk $(cat chapters.txt) cat output book.pdf
# ================================================================================================
# Add page numbers
# ================================================================================================
# Count pages https://stackoverflow.com/a/27132157/6563277
pageCount=$(pdftk book.pdf dump_data | grep "NumberOfPages" | cut -d":" -f2)
# Turn back to scripts/pdf_export
cd ..
# https://stackoverflow.com/a/30416992/6563277
# Create an overlay pdf file containing only page numbers
gs -o pagenumbers.pdf \
-sDEVICE=pdfwrite \
-g5950x8420 \
-c "/Helvetica findfont \
12 scalefont setfont \
1 1 ${pageCount} { \
/PageNo exch def \
450 20 moveto \
(Page ) show \
PageNo 3 string cvs \
show \
( of ${pageCount}) show \
showpage \
} for"
# Blend pagenumbers.pdf with the original pdf file
pdftk pdfs/book.pdf \
multistamp pagenumbers.pdf \
output final_book.pdf
However, we need other customization like table of contents, book cover, and author section, ... All the above steps are just merging and adding page nums! Lots of things to do.