Last active
February 19, 2026 18:01
-
-
Save aspose-com-gists/61d6fe0ccbd8cf21650951d8445ebb61 to your computer and use it in GitHub Desktop.
Batch Convert Multiple HTML Files to PDF with Aspose.HTML in Python via .NET
This file contains hidden or 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
| from pathlib import Path | |
| from aspose.html import HTMLDocument | |
| from aspose.html.saving import PdfSaveOptions | |
| from aspose.html.converters import Converter | |
| def batch_convert_html_to_pdf(input_dir: str, output_dir: str) -> dict: | |
| input_path = Path(input_dir) | |
| output_path = Path(output_dir) | |
| if not input_path.exists(): | |
| raise FileNotFoundError(f"Input folder not found: {input_path}") | |
| output_path.mkdir(parents=True, exist_ok=True) | |
| html_files = sorted( | |
| p for p in input_path.rglob("*") | |
| if p.is_file() and p.suffix.lower() in [".html", ".htm"] | |
| ) | |
| results = { | |
| "total": len(html_files), | |
| "succeeded": 0, | |
| "failed": 0, | |
| "failures": [] | |
| } | |
| pdf_options = PdfSaveOptions() | |
| for html_file in html_files: | |
| try: | |
| relative = html_file.relative_to(input_path) | |
| pdf_file = output_path / relative.with_suffix(".pdf") | |
| pdf_file.parent.mkdir(parents=True, exist_ok=True) | |
| with HTMLDocument(str(html_file)) as document: | |
| Converter.convert_html(document, pdf_options, str(pdf_file)) | |
| results["succeeded"] += 1 | |
| print(f"OK {relative} -> {pdf_file.relative_to(output_path)}") | |
| except Exception as ex: | |
| results["failed"] += 1 | |
| results["failures"].append({"file": str(html_file), "error": str(ex)}) | |
| print(f"ERR {html_file} -> {ex}") | |
| return results | |
| if __name__ == "__main__": | |
| summary = batch_convert_html_to_pdf("input", "output") | |
| print("\nSummary") | |
| print(f"Total : {summary['total']}") | |
| print(f"Succeeded : {summary['succeeded']}") | |
| print(f"Failed : {summary['failed']}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment