Skip to content

Instantly share code, notes, and snippets.

@mandli
Created October 30, 2020 18:00
Show Gist options
  • Save mandli/7e202f4b568ac69b01ff4386066b8a4b to your computer and use it in GitHub Desktop.
Save mandli/7e202f4b568ac69b01ff4386066b8a4b to your computer and use it in GitHub Desktop.
Take a bibtex file and create an html version of the compiled bibliography via pandoc.
#!/usr/bin/env python
import os
import subprocess
html_header = r"""
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="Content-Style-Type" content="text/css"/>
<meta name="generator" content="pandoc"/>
<title></title>
<style type="text/css">
code {
white-space: pre;
}
</style>
</head>
<body>
"""
html_footer = r"""
</body>
</html>
"""
def create_html_page(html_path, bib_html_block):
with open(html_path, 'w') as html_file:
html_file.write(html_header)
html_file.write(bib_html_block)
html_file.write(html_footer)
def create_bib_listing(bib_file, latex_file_path="temp.tex", style="ams",
sorting='ydnt', remove_temp_files=True):
# Create temporary latex file - Note that tempfiles actually does not play
# nicely with pandoc so we just go ahead and use a local file
with open(latex_file_path, 'w') as latex_file:
latex_file.write(r"\documentclass{article}")
latex_file.write(r"\usepackage[sorting=%s]{biblatex}" % sorting)
latex_file.write(r"\bibliography{%s}" %
os.path.splitext(os.path.split(bib_file)[-1])[0])
latex_file.write(r"\begin{document}")
latex_file.write(r"\nocite{*}")
latex_file.write(r"\bibliographystyle{%s}" % style)
latex_file.write(r"\printbibliography")
latex_file.write(r"\end{document}")
# Run pandoc to create the html bib block
result = subprocess.run(["pandoc", "--to=html", "--from=latex", latex_file_path,
"--bibliography", bib_file], text=True, capture_output=True)
if remove_temp_files:
os.remove(latex_file_path)
return result.stdout
if __name__ == '__main__':
create_html_page('bib.html', create_bib_listing("./database.bib", style='siam'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment