Skip to content

Instantly share code, notes, and snippets.

@scivision
Last active September 19, 2023 02:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scivision/d2884702c8b64f05df5342d4ba1b6dfb to your computer and use it in GitHub Desktop.
Save scivision/d2884702c8b64f05df5342d4ba1b6dfb to your computer and use it in GitHub Desktop.
Python script to collect a directory of images/plots into a single HTML document
#!/usr/bin/env python3
"""
Collect all images (.png) into a single HTML document
Create a PDF from your web browser as usual.
Example:
python images2pdf.py ~/my_plot_folder
that creates "~/my_plot_folder/index.html" and opens your web browser.
Most web browsers can "export" or "print" to PDF for sharing with colleagues.
"""
import argparse
from pathlib import Path
import webbrowser
import sys
if sys.version_info < (3, 6):
raise RuntimeError("Need Python >= 3.6")
p = argparse.ArgumentParser(
description="collect directory of images to single HTML document"
)
p.add_argument("input_dir", help="image / plots directory to collect")
p.add_argument(
"input_format", help="input image / plot format", default="png", nargs="?"
)
P = p.parse_args()
fmt = P.input_format
path = Path(P.input_dir).expanduser().resolve()
if not path.is_dir():
raise NotADirectoryError(path)
# %% write HTML file to display all graphs
html = f"""
<!DOCTYPE html>
<html>
<head>
<title>{path.name} Plots</title>
<style>
img {{
display: block;
margin-left: auto;
margin-right: auto;
width: 100%;
}}
</style>
</head>
<body>
"""
for img_file in path.glob(f"*.{fmt}"):
html += f"""
<figure>
<img src="{img_file.name}" alt="{img_file.stem}">
<figcaption>{img_file.stem}</figcaption>
</figure>
"""
html += """
</body>
</html>
"""
html_path = path / "index.html"
print("writing HTML ", html_path)
html_path.write_text(html)
webbrowser.open(html_path.as_uri())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment