URI rewriting

Use uri_export_strategy with CustomUriExportStrategy and a Python callable to rewrite resource URIs in the Markdown output. This is useful when images are served from a CDN or a different path than where they’re saved.

Note
URI rewriting works with file-based image strategies (ExportImagesToFileSystemStrategy or CustomImagesStrategy). It has no effect when images are embedded as Base64.

Prepend a CDN base URL

from groupdocs.markdown import (
    MarkdownConverter, ConvertOptions,
    ExportImagesToFileSystemStrategy, CustomUriExportStrategy
)

def uri_rewriting_cdn():
    """Rewrite image URIs to point to a CDN base URL in the Markdown output."""

    # Step 1: Define the CDN base URL
    CDN_BASE = "https://cdn.example.com/assets/"

    # Step 2: Create a handler that prepends the CDN URL to each resource
    def cdn_handler(call_info):
        """Called for each resource URI during conversion.
        Receives context with ResourceFileName, ResourceFileUri.
        Returns dict with resource_file_uri to override the URI."""
        ctx = call_info["context"]
        original = ctx["ResourceFileName"]
        return {"resource_file_uri": CDN_BASE + original}

    # Step 3: Configure image and URI export strategies
    options = ConvertOptions()
    options.image_export_strategy = ExportImagesToFileSystemStrategy("./output/images")
    options.uri_export_strategy = CustomUriExportStrategy(cdn_handler)

    # Step 4: Convert and save using keyword argument for options
    MarkdownConverter.to_file("business-plan.docx", "output/report.md", convert_options=options)
    # Images saved locally to output/images/
    # Markdown references: ![](https://cdn.example.com/assets/img-001.png)

if __name__ == "__main__":
    import os
    os.makedirs("output/images", exist_ok=True)
    uri_rewriting_cdn()

business-plan.docx is sample file used in this example. Click here to download it.

output/images/img-001.png (4 KB)
output/images/img-002.jpg (41 KB)
output/images/img-003.png (14 KB)
output/report.md (5 KB)

Download full output

UriSavingArgs properties

PropertyDescription
ResourceFileNameDefault file name generated by the library
ResourceFileUriDefault URI that would appear in the Markdown
resource_file_uriOverride the URI written to the Markdown output (return value)
Close
Loading

Analyzing your prompt, please hold on...

An error occurred while retrieving the results. Please refresh the page and try again.