Skip to content

feat(Mermaid): add DownloadPdfAsync method#705

Merged
ArgoZhang merged 4 commits intomasterfrom
dev-mermaid
Nov 19, 2025
Merged

feat(Mermaid): add DownloadPdfAsync method#705
ArgoZhang merged 4 commits intomasterfrom
dev-mermaid

Conversation

@ArgoZhang
Copy link
Copy Markdown
Member

@ArgoZhang ArgoZhang commented Nov 18, 2025

Link issues

fixes #704

Summary By Copilot

Regression?

  • Yes
  • No

Risk

  • High
  • Medium
  • Low

Verification

  • Manual (required)
  • Automated

Packaging changes reviewed?

  • Yes
  • No
  • N/A

☑️ Self Check before Merge

⚠️ Please check all items below before review. ⚠️

  • Doc is updated/provided or not needed
  • Demo is updated/provided or not needed
  • Merge the latest code from the main branch

Summary by Sourcery

Enable PDF export and download for Mermaid diagrams, refactor the rendering API, and enhance the JavaScript integration by dynamically loading scripts and providing helper methods.

New Features:

  • Add ExportPdfAsync method to generate a PDF stream from a rendered Mermaid diagram
  • Add DownloadPdfAsync method to save Mermaid diagrams as PDF via the download service

Enhancements:

  • Introduce Render method for re-rendering diagrams and deprecate the MermaidChanged method
  • Refactor JavaScript to dynamically load Mermaid scripts, unify init/render calls, and expose getSvgHtml helper

Chores:

  • Update copyright attribution in the component header

Copilot AI review requested due to automatic review settings November 18, 2025 06:51
@bb-auto bb-auto Bot added the enhancement New feature or request label Nov 18, 2025
@bb-auto bb-auto Bot added this to the v9.2.0 milestone Nov 18, 2025
@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Nov 18, 2025

Reviewer's Guide

This pull request adds asynchronous PDF export and download capabilities to the Mermaid component by injecting HTML-to-PDF and download services, refactoring the rendering API, and extending the JavaScript interop to support SVG extraction.

Sequence diagram for DownloadPdfAsync method in Mermaid component

sequenceDiagram
participant Mermaid
participant Html2PdfService
participant DownloadService
participant JSInterop

Mermaid->>JSInterop: getSvgHtml(id)
JSInterop-->>Mermaid: SVG HTML string
Mermaid->>Html2PdfService: PdfStreamFromHtmlAsync(html)
Html2PdfService-->>Mermaid: PDF stream
Mermaid->>DownloadService: DownloadFromStreamAsync(fileName, stream)
DownloadService-->>Mermaid: (download complete)
Loading

Sequence diagram for Render method replacing MermaidChanged

sequenceDiagram
participant Mermaid
participant JSInterop

Mermaid->>JSInterop: render(id, BuildDiagramText())
JSInterop-->>Mermaid: (diagram rendered)
Loading

Class diagram for updated Mermaid component with PDF export and download

classDiagram
class Mermaid {
  +string? Title
  +Task<string?> ExportBase64MermaidAsync()
  +Task<Stream?> ExportPdfAsync(CancellationToken token = default)
  +Task DownloadPdfAsync(string fileName, CancellationToken token = default)
  +Task Render()
  -IHtml2Pdf Html2PdfService
  -DownloadService DownloadService
}

class IHtml2Pdf {
  +Task<Stream?> PdfStreamFromHtmlAsync(string html)
}

class DownloadService {
  +Task DownloadFromStreamAsync(string fileName, Stream stream)
}

Mermaid --> IHtml2Pdf : uses
Mermaid --> DownloadService : uses
Loading

File-Level Changes

Change Details Files
Inject and utilize services for PDF generation and downloading
  • Added IHtml2Pdf and DownloadService injections
  • Implemented ExportPdfAsync to convert SVG HTML to PDF stream
  • Implemented DownloadPdfAsync to save PDF via DownloadService
Mermaid.razor.cs
Refactor component rendering API
  • Marked obsolete MermaidChanged method and excluded it from coverage
  • Introduced new Render method for re-rendering diagrams
  • Updated OnParametersSetAsync to call Render instead of MermaidChanged
Mermaid.razor.cs
Enhance JavaScript interop for rendering and SVG extraction
  • Loaded mermaid.min.js dynamically via addScript
  • Split init and render functions and updated render logic
  • Added getSvgHtml to retrieve SVG element HTML for PDF conversion
Mermaid.razor.js

Assessment against linked issues

Issue Objective Addressed Explanation
#704 Add a DownloadPdfAsync method to the Mermaid component that enables downloading the rendered diagram as a PDF.

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes - here's some feedback:

  • Ensure addScript is idempotent so that mermaid.min.js isn’t re-loaded on every Render call and to avoid redundant network requests.
  • In ExportPdfAsync, consider throwing or logging a clear exception when getSvgHtml returns null or empty instead of returning a null Stream to surface failures sooner.
  • Propagate the CancellationToken into DownloadService.DownloadFromStreamAsync (or extend its API) so that long‐running downloads can be cancelled.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Ensure addScript is idempotent so that mermaid.min.js isn’t re-loaded on every Render call and to avoid redundant network requests.
- In ExportPdfAsync, consider throwing or logging a clear exception when getSvgHtml returns null or empty instead of returning a null Stream to surface failures sooner.
- Propagate the CancellationToken into DownloadService.DownloadFromStreamAsync (or extend its API) so that long‐running downloads can be cancelled.

## Individual Comments

### Comment 1
<location> `src/components/BootstrapBlazor.Mermaid/Mermaid.razor.cs:88-93` </location>
<code_context>
+    /// 导出图为 Pdf 文档流
     /// </summary>
-    /// <returns></returns>
+    public async Task<Stream?> ExportPdfAsync(CancellationToken token = default)
+    {
+        Stream? stream = null;
+        var html = await InvokeAsync<string?>("getSvgHtml", token, Id);
+        if (html != null)
+        {
</code_context>

<issue_to_address>
**suggestion:** Check for null or empty HTML before passing to PDF service.

Also check for string.IsNullOrWhiteSpace(html) to avoid unnecessary PDF service calls with empty content.

```suggestion
    public async Task<Stream?> ExportPdfAsync(CancellationToken token = default)
    {
        Stream? stream = null;
        var html = await InvokeAsync<string?>("getSvgHtml", token, Id);
        if (!string.IsNullOrWhiteSpace(html))
        {
```
</issue_to_address>

### Comment 2
<location> `src/components/BootstrapBlazor.Mermaid/Mermaid.razor.cs:106-112` </location>
<code_context>
+    /// <returns>base64 string of the diagram</returns>
+    public async Task DownloadPdfAsync(string fileName, CancellationToken token = default)
+    {
+        ArgumentNullException.ThrowIfNull(fileName);
+
+        var stream = await ExportPdfAsync(token);
</code_context>

<issue_to_address>
**suggestion (bug_risk):** Consider validating fileName for empty or whitespace values.

Also check for empty or whitespace-only fileName values using string.IsNullOrWhiteSpace(fileName).

```suggestion
        ArgumentNullException.ThrowIfNull(fileName);
        if (string.IsNullOrWhiteSpace(fileName))
        {
            throw new ArgumentException("fileName cannot be empty or whitespace.", nameof(fileName));
        }

        var stream = await ExportPdfAsync(token);
        if (stream != null)
        {
            await DownloadService.DownloadFromStreamAsync(fileName, stream);
        }
```
</issue_to_address>

### Comment 3
<location> `src/components/BootstrapBlazor.Mermaid/Mermaid.razor.js:3-7` </location>
<code_context>
+import { addScript } from '../BootstrapBlazor/modules/utility.js'

 export async function init(id, content) {
+    await addScript('./_content/BootstrapBlazor.Mermaid/mermaid.min.js');
+
+    await render(id, content);
</code_context>

<issue_to_address>
**suggestion (bug_risk):** Consider handling addScript errors to avoid silent failures.

If addScript fails, later mermaid calls may throw. Wrap in try/catch or verify script load success.

```suggestion
export async function init(id, content) {
    try {
        await addScript('./_content/BootstrapBlazor.Mermaid/mermaid.min.js');
    } catch (error) {
        console.error('Failed to load mermaid script:', error);
        return;
    }

    await render(id, content);
}
```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +106 to +112
ArgumentNullException.ThrowIfNull(fileName);

var stream = await ExportPdfAsync(token);
if (stream != null)
{
await DownloadService.DownloadFromStreamAsync(fileName, stream);
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (bug_risk): Consider validating fileName for empty or whitespace values.

Also check for empty or whitespace-only fileName values using string.IsNullOrWhiteSpace(fileName).

Suggested change
ArgumentNullException.ThrowIfNull(fileName);
var stream = await ExportPdfAsync(token);
if (stream != null)
{
await DownloadService.DownloadFromStreamAsync(fileName, stream);
}
ArgumentNullException.ThrowIfNull(fileName);
if (string.IsNullOrWhiteSpace(fileName))
{
throw new ArgumentException("fileName cannot be empty or whitespace.", nameof(fileName));
}
var stream = await ExportPdfAsync(token);
if (stream != null)
{
await DownloadService.DownloadFromStreamAsync(fileName, stream);
}

Comment thread src/components/BootstrapBlazor.Mermaid/Mermaid.razor.js
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR adds the ability to download Mermaid diagrams as PDF documents by introducing new export and download methods that leverage the IHtml2Pdf service.

Key Changes:

  • Added DownloadPdfAsync method to enable direct PDF downloads of Mermaid diagrams
  • Refactored JavaScript initialization to support dynamic script loading and separate rendering logic
  • Deprecated the MermaidChanged method in favor of a new Render method

Reviewed Changes

Copilot reviewed 3 out of 4 changed files in this pull request and generated 7 comments.

File Description
Mermaid.razor.js Refactored to use dynamic script loading, added new render and getSvgHtml functions to support PDF export functionality
Mermaid.razor.cs Added ExportPdfAsync and DownloadPdfAsync methods with IHtml2Pdf and DownloadService injections; deprecated MermaidChanged in favor of Render
BootstrapBlazor.Mermaid.csproj Updated version to 10.0.1

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/components/BootstrapBlazor.Mermaid/Mermaid.razor.cs
Comment thread src/components/BootstrapBlazor.Mermaid/Mermaid.razor.js
Comment thread src/components/BootstrapBlazor.Mermaid/Mermaid.razor.js
Comment thread src/components/BootstrapBlazor.Mermaid/Mermaid.razor.cs
Comment thread src/components/BootstrapBlazor.Mermaid/Mermaid.razor.cs
Comment thread src/components/BootstrapBlazor.Mermaid/Mermaid.razor.cs
Comment thread src/components/BootstrapBlazor.Mermaid/Mermaid.razor.cs
@ArgoZhang ArgoZhang merged commit 0db83d7 into master Nov 19, 2025
9 checks passed
@ArgoZhang ArgoZhang deleted the dev-mermaid branch November 19, 2025 00:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(Mermaid): add DownloadPdfAsync method

2 participants