2023-06-06

Vim Code Buffer to PDF

Vim's builtin command :TOhtml generates an HTML rendering of the active code buffer which includes line numbers and syntax highlighting.

As shown in the video below, Pandoc (version 3.1.3 or newer ) can create a PDF starting from an HTML file, where instead of the default Latex compiler the new Typst compiler has been used.

Pandoc command line

Here's the command line used in the video.

   pandoc.exe webapp.py.html --filter filter_python_codeblock.py --template ./typst_template.typ -V title="Simple Flask Web App" -o webapp.pdf --pdf-engine=C:\\Users\\seve\\bin\\typst.exe

The option --pdf-engine is set to the Typst compiler's path which replaces the default Latex engine, thus installing the entire MikTex typesetting system can be avoided.

The Typst source code created during Pandoc HTML to PDF conversion does not automatically have tags for fenced code blocks. The following Python filter applies Python language tag to code blocks, this allows keeping the syntax highlighting also in the final PDF.

    # filename: filter_python_codeblock.py
    from panflute import *
    def set_codeblock_to_python(elem, doc):
        if isinstance(elem, CodeBlock):
            elem.classes = ["python"]


    def main(doc=None):
        return run_filter(set_codeblock_to_python, doc=doc)

    if __name__ == "__main__":
        main()

The default title of the PDF document is taken from the HTML's title tag which is the initial buffer path plus the html suffix. It's possible to pass the title from a command line variable.

A Pandoc template for the Typst format can be created and saved with the following command:

   pandoc.exe -D typst> typst_template.typ

The title of the document can then be set by specifying the option -V.