Save HTML with Resources in Python

HTML documents can depend on external stylesheets, images, fonts, and JavaScript files. Aspose.HTML for Python via .NET can save these resources as separate files or embed supported resources directly into the output HTML.

To save HTML with images and CSS in Python, load the document into an HTMLDocument and call save() with a FileSystemResourceHandler or HTMLSaveOptions. Use FileSystemResourceHandler to select an output folder, or set ResourceHandling.EMBED to create a self-contained HTML file.

Choose How to Save HTML Resources

The ResourceHandlingOptions object available through HTMLSaveOptions controls how linked resources are processed. Its properties accept values from the ResourceHandling enumeration.

SettingResult
ResourceHandling.SAVESaves handled resources as separate files and updates their references in the output HTML. This is the default behavior.
ResourceHandling.EMBEDEmbeds handled resources into the HTML, for example as a <style> element or a data URI.
ResourceHandling.IGNOREDoes not save or embed the resource. The output keeps a reference to its original location, so it may not work after the HTML file is moved.
ResourceHandling.DISCARDRemoves handled JavaScript from the saved output when assigned to java_script. Do not assign DISCARD to default; that combination is not supported.

The default property controls CSS, images, fonts, and other general resources. The java_script property controls external scripts separately. For example, use options.resource_handling_options.java_script = sav.ResourceHandling.EMBED when scripts must be embedded instead of saved as separate files.

Save HTML and Resources to a Folder

Use FileSystemResourceHandler when the HTML document and its resources must be written to a selected local directory. The following example uses html-with-resources.html, html-resources.css, and html-resources.svg as source files.

To save HTML with linked resources to a folder:

  1. Place the HTML file and its linked CSS and image files in the data directory.
  2. Load the HTML file into an HTMLDocument.
  3. Create a FileSystemResourceHandler for the destination directory.
  4. Pass the handler to document.save() to save the HTML and handled resources.
 1# Save HTML file with resources to folder using Python
 2
 3import os
 4import aspose.html as ah
 5import aspose.html.saving.resourcehandlers as handlers
 6
 7data_dir = "data"
 8output_dir = os.path.join("output", "file-system")
 9os.makedirs(output_dir, exist_ok=True)
10
11input_path = os.path.join(data_dir, "html-with-resources.html")
12
13# Load the HTML document with linked CSS and SVG
14with ah.HTMLDocument(input_path) as document:
15    # The trailing separator identifies the path as a directory
16    handler = handlers.FileSystemResourceHandler(output_dir + os.sep)
17
18    # Save the document and all handled resources
19    document.save(handler)
20
21print(f"HTML and resources were saved to {output_dir}")

The handler creates the following output structure and rewrites the resource URLs in the saved HTML:

1output/
2└── file-system/
3    ├── html-with-resources.html
4    └── html-with-resources_files/
5        ├── html-resources.css
6        └── html-resources.svg

The trailing path separator passed to FileSystemResourceHandler is significant because it identifies the supplied path as a directory.

Embed CSS and Images in HTML

Set HTMLSaveOptions.resource_handling_options.default to ResourceHandling.EMBED when the output should contain its CSS and images instead of referencing separate files.

To embed linked resources in an HTML file:

  1. Load an HTML document that references external CSS and images.
  2. Create an HTMLSaveOptions object.
  3. Set the default resource handling behavior to EMBED.
  4. Save the document to the required output path.
 1# Embed CSS and images in HTML using Python
 2
 3import os
 4import aspose.html as ah
 5import aspose.html.saving as sav
 6
 7data_dir = "data"
 8output_dir = "output"
 9os.makedirs(output_dir, exist_ok=True)
10
11input_path = os.path.join(data_dir, "html-with-resources.html")
12output_path = os.path.join(output_dir, "embedded-resources.html")
13
14# Load the HTML document with linked CSS and SVG
15with ah.HTMLDocument(input_path) as document:
16    options = sav.HTMLSaveOptions()
17
18    # Embed handled resources into the HTML document
19    options.resource_handling_options.default = sav.ResourceHandling.EMBED
20
21    document.save(output_path, options)
22
23print(f"HTML with embedded resources was saved to {output_path}")

The result is one embedded-resources.html file. In this example, the external stylesheet becomes a <style> element and the SVG image becomes a Base64-encoded data URI. No adjacent resource directory is created.

Embedding resources increases the HTML file size. Use separate files when resources should be cached, reused by several pages, or managed independently.

Control Resource URLs and Linked Pages

Resource handling depends not only on SAVE, EMBED, or IGNORE, but also on URL restrictions and linked-page depth.

PropertyWhat it controls
resource_url_restrictionWhich CSS, image, font, script, and other resource URLs may be processed. The default restriction is the same host.
page_url_restrictionWhich linked HTML pages may be processed. By default, pages are restricted to the root location and its subfolders.
max_handling_depthHow many levels of linked HTML pages may be processed. A value of 0 handles only the current document, 1 includes directly linked pages, and -1 removes the depth limit.

max_handling_depth applies to linked HTML pages, not to ordinary CSS or image references required by the current page. Relax URL restrictions only when the source is trusted and external resources are intentionally required.

Save Directly Linked HTML Pages

The following example uses save-with-linked-page.html and linked-page.html to demonstrate how max_handling_depth affects linked HTML pages.

To save a document and its directly linked page:

  1. Place the main HTML file and its linked page in the data directory.
  2. Load the main file into an HTMLDocument.
  3. Create HTMLSaveOptions and set max_handling_depth to 1.
  4. Save the main document with the configured options.
 1# Save HTML document with a linked resources using Python
 2
 3import os
 4import aspose.html as ah
 5import aspose.html.saving as sav
 6
 7data_dir = "data"
 8output_dir = "output"
 9os.makedirs(output_dir, exist_ok=True)
10
11input_path = os.path.join(data_dir, "save-with-linked-page.html")
12output_path = os.path.join(output_dir, "save-with-linked-page.html")
13
14# Load the main HTML document
15with ah.HTMLDocument(input_path) as document:
16    options = sav.HTMLSaveOptions()
17
18    # Include directly linked HTML pages
19    options.resource_handling_options.max_handling_depth = 1
20
21    document.save(output_path, options)

The save operation creates the following output:

1output/
2├── save-with-linked-page.html
3└── save-with-linked-page_files/
4    └── linked-page.html

In the saved main document, the original link is rewritten to save-with-linked-page_files/linked-page.html. Setting max_handling_depth to 1 permits directly linked pages to be processed, but page_url_restriction can still exclude a page whose location is not allowed.

Common Resource Saving Issues

ProblemCause and solution
CSS or images are missingCheck the document base URL, linked paths, and resource_url_restriction. A relative URL cannot be resolved correctly without a valid source location.
Saved HTML still depends on external filesUse ResourceHandling.EMBED for general resources and configure java_script separately if external scripts must also be embedded.
The output is created at an unexpected pathPass a directory path ending with os.sep to FileSystemResourceHandler.
A linked HTML page is not savedIncrease max_handling_depth and verify page_url_restriction. This setting affects linked pages rather than CSS, images, or fonts.
The embedded HTML file is very largeSave resources as separate files with SAVE or use FileSystemResourceHandler instead of embedding them.

FAQ

How do I save HTML with images and CSS in Python?

Load the document with HTMLDocument and pass a FileSystemResourceHandler to save(). Aspose.HTML writes the main HTML file and handled resources to the selected directory and updates their references.

How do I save HTML as one self-contained file?

Create HTMLSaveOptions, set resource_handling_options.default to ResourceHandling.EMBED, and save the document. Configure resource_handling_options.java_script separately when external JavaScript must also be embedded.

Can I ignore or remove linked resources?

Use IGNORE to leave a resource at its original location without copying or embedding it. Use DISCARD with the java_script property to remove handled scripts from the saved output. DISCARD is not supported as the general default behavior.

Can I implement a custom ResourceHandler in Python?

Use the built-in FileSystemResourceHandler to direct HTML and resources to a user-selected local folder. The custom ResourceHandler subclasses used in C# ZIP or memory examples cannot be transferred directly because ResourceHandler is not exposed as a subclassable Python type.

Other Platforms

Related Articles