Python script to collect a directory of images/plots into a single HTML document
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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