Skip to content

feat(PdfReader): add OnPrintingAsync parameter#731

Merged
ArgoZhang merged 2 commits intomasterfrom
dev-pdfreader-allow-print
Nov 27, 2025
Merged

feat(PdfReader): add OnPrintingAsync parameter#731
ArgoZhang merged 2 commits intomasterfrom
dev-pdfreader-allow-print

Conversation

@ArgoZhang
Copy link
Copy Markdown
Member

@ArgoZhang ArgoZhang commented Nov 27, 2025

Link issues

fixes #730

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

Add print support and a printing callback to PdfReader and align JS interop method names.

New Features:

  • Expose an OnPrintingAsync callback on PdfReader to allow consumers to react when printing starts.

Bug Fixes:

  • Correct the JS interop invocation name for the PagesInit callback to match the .NET method.

Enhancements:

  • Add client-side PDF printing via an off-screen iframe and wire it to the PdfReader print control, including cleanup of related event handlers and iframe on dispose.

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

sourcery-ai Bot commented Nov 27, 2025

Reviewer's Guide

Adds a new printing callback to the PdfReader component and wires it up from the JS viewer layer, including a hidden iframe-based print implementation and associated event cleanup.

Sequence diagram for PdfReader printing callback flow

sequenceDiagram
    actor User
    participant Browser as Browser_UI
    participant PdfJs as PdfReader_js
    participant DotNet as PdfReader_dotnet

    User->>Browser: Click print button
    Browser->>PdfJs: click event on .bb-view-print
    activate PdfJs
    PdfJs->>PdfJs: printPdf(url)
    PdfJs->>Browser: Create hidden iframe
    Browser-->>PdfJs: iframe onload
    PdfJs->>Browser: iframe.contentWindow.print()
    PdfJs-->>DotNet: invokeMethodAsync Printing
    activate DotNet
    DotNet->>DotNet: Printing()
    DotNet->>DotNet: OnPrintingAsync?
    alt OnPrintingAsync is not null
        DotNet-->>DotNet: await OnPrintingAsync()
    end
    deactivate DotNet
    Browser-->>Browser: afterprint event
    Browser->>Browser: Remove iframe
    deactivate PdfJs
Loading

Updated class diagram for PdfReader printing callback

classDiagram
    class PdfReader {
        +string? MoreButtonIcon
        +Func~Task~? OnDownloadAsync
        +Func~Task~? OnPrintingAsync
        +Task PageChanged(uint pageIndex)
        +Task Printing()
    }

    class OnDownloadAsyncCallback {
        <<delegate>>
        +Invoke() Task
    }

    class OnPrintingAsyncCallback {
        <<delegate>>
        +Invoke() Task
    }

    PdfReader --> OnDownloadAsyncCallback : uses
    PdfReader --> OnPrintingAsyncCallback : uses
Loading

Flow diagram for PdfReader printPdf and disposal lifecycle

flowchart TD
    A[User clicks .bb-view-print button] --> B[Call printPdf with url]
    B --> C{Existing .bb-view-print-iframe?}
    C -->|Yes| D[Remove existing iframe]
    C -->|No| E[Create new iframe element]
    D --> E
    E --> F[Set class bb-view-print-iframe and hidden fixed position]
    F --> G[Set iframe.src to url]
    G --> H[Append iframe to document.body]
    H --> I[iframe onload handler]
    I --> J[Add afterprint listener on iframe.contentWindow]
    J --> K[Call iframe.contentWindow.focus and print]
    K --> L[User completes browser print]
    L --> M[afterprint event fires]
    M --> N[Remove iframe from document.body]

    subgraph Disposal_cleanup
        O[dispose called with id] --> P[Locate PdfReader element]
        P --> Q[Remove thumbnails click handler]
        Q --> R[Remove .bb-view-controls click handler]
        R --> S{Find .bb-view-print-iframe?}
        S -->|Yes| T[Remove iframe]
        S -->|No| U[No iframe to remove]
    end
Loading

File-Level Changes

Change Details Files
Wire JS-side events to trigger a new .NET printing callback when the print control is clicked.
  • Change the pages initialization JS interop method name from a lowercased identifier to PascalCase to match the .NET method name.
  • Hook into the view controls container to listen for clicks on the print button and call a new print helper using the configured PDF URL.
  • Invoke the new .NET printing callback via JS interop when the print button is clicked.
  • Ensure event handlers and temporary DOM elements are cleaned up in the dispose logic, including print controls click handler and any print iframe instance.
src/components/BootstrapBlazor.PdfReader/PdfReader.razor.js
Expose and implement a new OnPrintingAsync parameter on the PdfReader component and a corresponding JS-invokable method.
  • Add a new OnPrintingAsync Func? parameter with documentation to the PdfReader component API.
  • Implement a new JSInvokable Printing method that awaits the OnPrintingAsync delegate when provided.
src/components/BootstrapBlazor.PdfReader/PdfReader.razor.cs

Assessment against linked issues

Issue Objective Addressed Explanation
#730 Expose an OnPrintingAsync parameter on the PdfReader component and a corresponding JS-invokable .NET method to handle the printing callback.
#730 Invoke the OnPrintingAsync callback when the user triggers printing from the PdfReader UI, wiring up the JavaScript event handler and cleanup logic.

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

@ArgoZhang ArgoZhang merged commit b63be39 into master Nov 27, 2025
6 of 7 checks passed
@ArgoZhang ArgoZhang deleted the dev-pdfreader-allow-print branch November 27, 2025 04:22
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 and found some issues that need to be addressed.

  • In PdfReader.razor.js, the click handler passed to EventHandler.on(controls, "click", ".bb-view-print", e => { ... }) uses await inside a non-async arrow function, which will cause a syntax error; make the handler async e => { ... } or remove the await.
  • When using iframe.contentWindow inside printPdf, consider guarding against it being null (e.g., in some sandboxed or unusual browser contexts) before calling addEventListener, focus, and print to avoid runtime errors.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `PdfReader.razor.js`, the click handler passed to `EventHandler.on(controls, "click", ".bb-view-print", e => { ... })` uses `await` inside a non-async arrow function, which will cause a syntax error; make the handler `async e => { ... }` or remove the `await`.
- When using `iframe.contentWindow` inside `printPdf`, consider guarding against it being `null` (e.g., in some sandboxed or unusual browser contexts) before calling `addEventListener`, `focus`, and `print` to avoid runtime errors.

## Individual Comments

### Comment 1
<location> `src/components/BootstrapBlazor.PdfReader/PdfReader.razor.js:144-145` </location>
<code_context>
         }
+
+        const controls = el.querySelector(".bb-view-controls");
+        EventHandler.on(controls, "click", ".bb-view-print", e => {
+            printPdf(options.url);
+            await invoke.invokeMethodAsync("Printing");
+        });
</code_context>

<issue_to_address>
**issue (bug_risk):** The event handler uses `await` but is not marked `async`, which will cause a syntax error.

In the `pagesloaded` handler, the `EventHandler.on` callback is defined as `e => { ... }` but contains `await invoke.invokeMethodAsync("Printing");`, which is invalid in non-`async` functions and will cause a syntax error. Make the callback `async e => { ... }` or remove `await` and handle the returned promise explicitly.
</issue_to_address>

### Comment 2
<location> `src/components/BootstrapBlazor.PdfReader/PdfReader.razor.js:139-148` </location>
<code_context>
             await invoke.invokeMethodAsync("PagesLoaded", e.pagesCount);
         }
+
+        const controls = el.querySelector(".bb-view-controls");
+        EventHandler.on(controls, "click", ".bb-view-print", e => {
+            printPdf(options.url);
+            await invoke.invokeMethodAsync("Printing");
</code_context>

<issue_to_address>
**suggestion:** Null handling for `.bb-view-controls` should be added before wiring event listeners.

If `.bb-view-controls` is missing, `el.querySelector(".bb-view-controls")` returns `null`, and passing that into `EventHandler.on` will likely throw. Please guard this with a null check (e.g. `if (controls) { EventHandler.on(...); }`) so layouts without controls don’t cause runtime errors.

```suggestion
        if (options.triggerPagesLoaded === true) {
            await invoke.invokeMethodAsync("PagesLoaded", e.pagesCount);
        }

        const controls = el.querySelector(".bb-view-controls");
        if (controls) {
            EventHandler.on(controls, "click", ".bb-view-print", async e => {
                printPdf(options.url);
                await invoke.invokeMethodAsync("Printing");
            });
        }
    })
```
</issue_to_address>

### Comment 3
<location> `src/components/BootstrapBlazor.PdfReader/PdfReader.razor.js:291-292` </location>
<code_context>
+        iframe.remove();
+    }
+
+    iframe = document.createElement("iframe");
+    iframe.classList = "bb-view-print-iframe";
+    iframe.style.position = "fixed";
+    iframe.style.right = "100%";
</code_context>

<issue_to_address>
**issue (bug_risk):** Assigning a string directly to `classList` is incorrect; use `className` or `classList.add` instead.

Because `classList` is a `DOMTokenList`, assigning a string (`iframe.classList = "bb-view-print-iframe";`) won’t reliably apply the class and may be ignored by some browsers. Use `iframe.className = "bb-view-print-iframe";` or `iframe.classList.add("bb-view-print-iframe");` so the iframe actually receives the CSS class.
</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 +144 to +145
EventHandler.on(controls, "click", ".bb-view-print", e => {
printPdf(options.url);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

issue (bug_risk): The event handler uses await but is not marked async, which will cause a syntax error.

In the pagesloaded handler, the EventHandler.on callback is defined as e => { ... } but contains await invoke.invokeMethodAsync("Printing");, which is invalid in non-async functions and will cause a syntax error. Make the callback async e => { ... } or remove await and handle the returned promise explicitly.

Comment on lines 139 to 148
if (options.triggerPagesLoaded === true) {
await invoke.invokeMethodAsync("PagesLoaded", e.pagesCount);
}

const controls = el.querySelector(".bb-view-controls");
EventHandler.on(controls, "click", ".bb-view-print", e => {
printPdf(options.url);
await invoke.invokeMethodAsync("Printing");
});
})
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: Null handling for .bb-view-controls should be added before wiring event listeners.

If .bb-view-controls is missing, el.querySelector(".bb-view-controls") returns null, and passing that into EventHandler.on will likely throw. Please guard this with a null check (e.g. if (controls) { EventHandler.on(...); }) so layouts without controls don’t cause runtime errors.

Suggested change
if (options.triggerPagesLoaded === true) {
await invoke.invokeMethodAsync("PagesLoaded", e.pagesCount);
}
const controls = el.querySelector(".bb-view-controls");
EventHandler.on(controls, "click", ".bb-view-print", e => {
printPdf(options.url);
await invoke.invokeMethodAsync("Printing");
});
})
if (options.triggerPagesLoaded === true) {
await invoke.invokeMethodAsync("PagesLoaded", e.pagesCount);
}
const controls = el.querySelector(".bb-view-controls");
if (controls) {
EventHandler.on(controls, "click", ".bb-view-print", async e => {
printPdf(options.url);
await invoke.invokeMethodAsync("Printing");
});
}
})

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 a new OnPrintingAsync callback parameter to the PdfReader component, allowing consumers to receive notifications when the print function is triggered. The PR also includes a naming consistency fix, changing the JavaScript method invocation from "pagesInit" to "PagesInit" to match the C# PascalCase convention.

Key changes:

  • Added OnPrintingAsync parameter and corresponding Printing() JSInvokable method
  • Implemented printPdf() function that creates a hidden iframe to handle PDF printing
  • Fixed method name from "pagesInit" to "PagesInit" for naming consistency

Reviewed changes

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

File Description
PdfReader.razor.js Fixed "pagesInit" to "PagesInit" for naming consistency; added print event handler and printPdf() function; updated dispose to clean up print-related resources
PdfReader.razor.cs Added OnPrintingAsync parameter and Printing() JSInvokable callback method; updated download callback comment
BootstrapBlazor.PdfReader.csproj Version bump from 10.0.1-beta07 to 10.0.1-beta08
Comments suppressed due to low confidence (1)

src/components/BootstrapBlazor.PdfReader/PdfReader.razor.js:146

  • Error: Unexpected token
            await invoke.invokeMethodAsync("Printing");

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

}

const controls = el.querySelector(".bb-view-controls");
EventHandler.on(controls, "click", ".bb-view-print", e => {
Copy link

Copilot AI Nov 27, 2025

Choose a reason for hiding this comment

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

The event handler callback function is missing the async keyword but uses await on line 146. This will cause a syntax error. The arrow function on line 144 should be declared as async (e) => { instead of e => {.

Suggested change
EventHandler.on(controls, "click", ".bb-view-print", e => {
EventHandler.on(controls, "click", ".bb-view-print", async e => {

Copilot uses AI. Check for mistakes.
Comment on lines +144 to +147
EventHandler.on(controls, "click", ".bb-view-print", e => {
printPdf(options.url);
await invoke.invokeMethodAsync("Printing");
});
Copy link

Copilot AI Nov 27, 2025

Choose a reason for hiding this comment

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

The print event handler should follow the same pattern as other callbacks in this file by checking if the feature is enabled via an options flag. Add a TriggerPrinting option check similar to how triggerPagesInit, triggerPagesLoaded, and triggerPageChanged are used (see lines 129, 139, 169). This prevents unnecessary event handler registration and callback invocations when OnPrintingAsync is null.

Suggested change
EventHandler.on(controls, "click", ".bb-view-print", e => {
printPdf(options.url);
await invoke.invokeMethodAsync("Printing");
});
if (options.triggerPrinting === true) {
EventHandler.on(controls, "click", ".bb-view-print", async e => {
printPdf(options.url);
await invoke.invokeMethodAsync("Printing");
});
}

Copilot uses AI. Check for mistakes.
Comment on lines +142 to 148

const controls = el.querySelector(".bb-view-controls");
EventHandler.on(controls, "click", ".bb-view-print", e => {
printPdf(options.url);
await invoke.invokeMethodAsync("Printing");
});
})
Copy link

Copilot AI Nov 27, 2025

Choose a reason for hiding this comment

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

The print event handler is registered inside the 'pagesloaded' event callback. This means the handler will be registered multiple times if the PDF is reloaded, causing the print function and callback to be invoked multiple times on each print click. Consider registering this handler once in the main addEventListener function body, similar to how the minus/plus button handlers are registered on lines 197-198.

Suggested change
const controls = el.querySelector(".bb-view-controls");
EventHandler.on(controls, "click", ".bb-view-print", e => {
printPdf(options.url);
await invoke.invokeMethodAsync("Printing");
});
})
});
// Register print button click handler once
const controls = el.querySelector(".bb-view-controls");
if (controls) {
EventHandler.on(controls, "click", ".bb-view-print", async e => {
printPdf(options.url);
await invoke.invokeMethodAsync("Printing");
});
}

Copilot uses AI. Check for mistakes.
}

iframe = document.createElement("iframe");
iframe.classList = "bb-view-print-iframe";
Copy link

Copilot AI Nov 27, 2025

Choose a reason for hiding this comment

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

Setting classList directly to a string is incorrect. The classList property is a read-only DOMTokenList. Use iframe.classList.add("bb-view-print-iframe") instead, or use iframe.className = "bb-view-print-iframe" to set the class attribute.

Suggested change
iframe.classList = "bb-view-print-iframe";
iframe.className = "bb-view-print-iframe";

Copilot uses AI. Check for mistakes.
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(PdfReader): add OnPrintingAsync parameter

2 participants