Kozea/WeasyPrint

Automatically generate pdf when html/css changes

Open

#1,360 建立於 2021年5月19日

在 GitHub 查看
 (0 留言) (2 反應) (0 負責人)Python (6,291 star) (630 fork)batch import
documentationgood first issue

描述

I was looking for a way to automatically generate a PDF file upon saving the HTML or CSS files and came up with the following shell script. Maybe it helps some other linux users trying to solve the same problem.

Dependencies

  • inotify-tools
  • fd (This could easily be rewritten to use find or some other command but I prefer fd)

Disclaimer: I'm not very good at shell scripting, use it at your own risk.

This looks for changes to files within the directory this script is placed in and then re-generates the PDF. It takes the first HTML file it finds as input.

It will break if you rename the HTML file while the script is running. To fix this, move the input file detection into the while loop.

I'm sure this can be improved upon a lot.

#!/bin/sh


WATCH_DIR=$(dirname $(realpath $0))
INPUT=$(fd -e html --max-results 1 . $WATCH_DIR)
if [ "$INPUT" = "" ]
then
    printf "\n    NO SUITABLE (HTML) INPUT DOCUMENT FOUND\n"
    exit -1
fi
OUTPUT=$WATCH_DIR/$(basename -s html $INPUT)pdf

while true
do
    inotifywait -r $WATCH_DIR -e modify
    printf "\n"
    weasyprint $INPUT $OUTPUT
    if [ "$?" -ne 0 ]
    then
        printf "\n    FAILED TO COMPILE DOCUMENT %\n\n\n" $INPUT
    else
        printf "\n    COMPILED DOCUMENT TO %s\n\n\n" $OUTPUT
    fi
done

Thanks for the input @grewn0uille and arthur from gitter

貢獻者指南