Created
February 16, 2026 10:29
-
-
Save aspose-com-gists/08505b458281da31eea29885045b8c0f to your computer and use it in GitHub Desktop.
Boost Performance of HTML to PDF Conversion 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
| import asyncio | |
| import aspose.html as ahtml | |
| from concurrent.futures import ThreadPoolExecutor | |
| # Paths - update these to match your environment | |
| HTML_INPUT = r"C:\Docs\sample.html" | |
| PDF_OUTPUT = r"C:\Docs\sample_converted.pdf" | |
| def create_converter(): | |
| # Load options with performance tweaks | |
| load_opts = ahtml.loading.HtmlLoadOptions() | |
| load_opts.resource_loading_timeout = 30 | |
| load_opts.enable_memory_cache = False | |
| # Custom font settings (reuse across conversions) | |
| font_opts = ahtml.rendering.FontSettings() | |
| font_opts.add_font_folder(r"C:\MyFonts") | |
| load_opts.font_settings = font_opts | |
| # PDF save options with margins | |
| save_opts = ahtml.saving.PdfSaveOptions() | |
| save_opts.page_margins = ahtml.saving.PageMargins(10, 10, 10, 10) # points | |
| converter = ahtml.conversion.HtmlToPdfConverter() | |
| converter.load_options = load_opts | |
| converter.save_options = save_opts | |
| return converter | |
| async def async_convert(html_path, pdf_path): | |
| converter = create_converter() | |
| try: | |
| await converter.convert_async(html_path, pdf_path) | |
| finally: | |
| # Ensure unmanaged resources are released | |
| converter.dispose() | |
| def run_sync_conversion(): | |
| converter = create_converter() | |
| try: | |
| converter.convert(HTML_INPUT, PDF_OUTPUT) | |
| finally: | |
| converter.dispose() | |
| def run_parallel_conversions(file_pairs): | |
| with ThreadPoolExecutor(max_workers=4) as executor: | |
| futures = [ | |
| executor.submit( | |
| lambda pair: create_converter().convert(pair[0], pair[1]), | |
| pair | |
| ) | |
| for pair in file_pairs | |
| ] | |
| for f in futures: | |
| f.result() # Propagate any exceptions | |
| if __name__ == "__main__": | |
| # Example 1: Simple synchronous conversion | |
| run_sync_conversion() | |
| # Example 2: Asynchronous conversion | |
| asyncio.run(async_convert(HTML_INPUT, PDF_OUTPUT)) | |
| # Example 3: Parallel batch conversion | |
| batch = [ | |
| (r"C:\Docs\doc1.html", r"C:\Docs\doc1.pdf"), | |
| (r"C:\Docs\doc2.html", r"C:\Docs\doc2.pdf"), | |
| (r"C:\Docs\doc3.html", r"C:\Docs\doc3.pdf") | |
| ] | |
| run_parallel_conversions(batch) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment