Skip to content

feat(PdfReader): print pdf function support stream#841

Merged
ArgoZhang merged 3 commits intomasterfrom
feat-pdf
Dec 18, 2025
Merged

feat(PdfReader): print pdf function support stream#841
ArgoZhang merged 3 commits intomasterfrom
feat-pdf

Conversation

@ArgoZhang
Copy link
Copy Markdown
Member

@ArgoZhang ArgoZhang commented Dec 18, 2025

Link issues

fixes #840

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

Support printing and downloading PDFs from either URLs or in-memory data streams in the PdfReader component.

New Features:

  • Enable PdfReader printing when the PDF is provided as a binary data stream instead of only as a URL.
  • Allow PdfReader downloads to work with both URL-based and in-memory PDF sources via a shared helper.

Enhancements:

  • Scope the temporary print iframe to the PdfReader element and ensure it is cleaned up on dispose.
  • Refactor PDF URL handling into a reusable helper that abstracts URL vs. data stream sources.

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

sourcery-ai Bot commented Dec 18, 2025

Reviewer's Guide

Refactors the PdfReader print and download behaviors to work with both URL-based and in-memory PDF streams by centralizing blob/URL handling into a new helper, updating toolbar event handlers, and ensuring print iframes are scoped and cleaned up per component instance.

Sequence diagram for PdfReader print flow with URL or stream

sequenceDiagram
    actor User
    participant PdfReaderToolbar as PdfReaderToolbar
    participant PdfReaderJs as PdfReaderJsModule
    participant getPdfUrl as getPdfUrl
    participant Iframe as PrintIframe

    User->>PdfReaderToolbar: Click bb_view_print button
    PdfReaderToolbar->>PdfReaderJs: printPdf(el, options)

    alt No existing print iframe in component
        PdfReaderJs->>PdfReaderJs: Create iframe
        PdfReaderJs->>PdfReaderJs: Append iframe to el
    else Existing iframe found
        PdfReaderJs->>PdfReaderJs: Reuse iframe
    end

    PdfReaderJs->>getPdfUrl: getPdfUrl(options, callback)

    alt options.url present
        getPdfUrl-->>PdfReaderJs: callback(options.url)
    else options.data present
        getPdfUrl->>getPdfUrl: Create Blob from options.data
        getPdfUrl->>getPdfUrl: CreateObjectURL(blob) -> url
        getPdfUrl-->>PdfReaderJs: await callback(url)
        getPdfUrl->>getPdfUrl: RevokeObjectURL(url)
    end

    PdfReaderJs->>Iframe: Set iframe.src = url
    Iframe->>Iframe: onload
    Iframe->>Iframe: contentWindow.focus()
    Iframe->>Iframe: contentWindow.print()

    PdfReaderToolbar->>PdfReaderJs: invoke.invokeMethodAsync Printing
Loading

Sequence diagram for PdfReader download flow with URL or stream

sequenceDiagram
    actor User
    participant PdfReaderToolbar as PdfReaderToolbar
    participant PdfReaderJs as PdfReaderJsModule
    participant getPdfUrl as getPdfUrl
    participant Anchor as DownloadAnchor

    User->>PdfReaderToolbar: Click bb_view_download button
    PdfReaderToolbar->>PdfReaderJs: downloadPdf(options, fileName)

    alt fileName attribute present on element
        PdfReaderJs->>PdfReaderJs: Use data_bb_download
    else fileName not set
        PdfReaderJs->>PdfReaderJs: Read .bb_view_subject text
        alt subject found
            PdfReaderJs->>PdfReaderJs: Use subject text
        else subject not found
            PdfReaderJs->>PdfReaderJs: Use default download.pdf
        end
    end

    PdfReaderJs->>getPdfUrl: getPdfUrl(options, callback)

    alt options.url present
        getPdfUrl-->>PdfReaderJs: callback(options.url)
    else options.data present
        getPdfUrl->>getPdfUrl: Create Blob from options.data
        getPdfUrl->>getPdfUrl: CreateObjectURL(blob) -> url
        getPdfUrl-->>PdfReaderJs: await callback(url)
        getPdfUrl->>getPdfUrl: RevokeObjectURL(url)
    end

    PdfReaderJs->>Anchor: Create anchor element
    PdfReaderJs->>Anchor: Set href = url, download = fileName
    PdfReaderJs->>Anchor: Append to document.body
    PdfReaderJs->>Anchor: anchor.click()
    PdfReaderJs->>Anchor: Remove from document.body
Loading

File-Level Changes

Change Details Files
Update toolbar print and download handlers to use async helpers that support both URL and in-memory PDF data.
  • Change print toolbar click handler to call an async printPdf(el, options) instead of printPdf(options.url).
  • Change download toolbar click handler to always resolve a filename from DOM attributes/text and then call async downloadPdf(options, fileName).
src/components/BootstrapBlazor.PdfReader/PdfReader.razor.js
Introduce shared PDF URL resolution to support both options.url and options.data (blob) for printing and downloading.
  • Add async getPdfUrl(options, callback) that either passes through options.url or creates/revokes an object URL from options.data.
  • Refactor downloadPdf to call getPdfUrl and trigger an element download using the resolved URL.
  • Refactor printPdf to call getPdfUrl and set iframe.src from the resolved URL before focusing/printing.
src/components/BootstrapBlazor.PdfReader/PdfReader.razor.js
Scope and clean up the print iframe per PdfReader instance to avoid leaking global iframes.
  • Change printPdf to search/create the .bb-view-print-iframe within the component root element and append it there instead of to document.body.
  • Ensure disposePdf removes any existing .bb-view-print-iframe when disposing a PdfReader instance.
src/components/BootstrapBlazor.PdfReader/PdfReader.razor.js

Assessment against linked issues

Issue Objective Addressed Explanation
#840 Enable the PdfReader print function to work when the PDF is provided as a stream/data source (not only via a URL).

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 70f8dff into master Dec 18, 2025
3 of 4 checks passed
@ArgoZhang ArgoZhang deleted the feat-pdf branch December 18, 2025 02:04
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 they look great!

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location> `src/components/BootstrapBlazor.PdfReader/PdfReader.razor.js:778-780` </location>
<code_context>
+}

-    document.body.appendChild(iframe);
+const getPdfUrl = async (options, callback) => {
+    if (options.url) {
+        callback(options.url);
+    }
+    else if (options.data) {
</code_context>

<issue_to_address>
**suggestion (bug_risk):** The `url` branch of `getPdfUrl` ignores any promise returned by `callback`, leading to asymmetric behavior.

In `getPdfUrl`, the `options.url` branch calls `callback(options.url)` without `await`, but the `options.data` branch uses `await callback(url)`. With promise-returning callbacks (as in current callers), this leads to inconsistent behavior and timing. Please either `return await callback(options.url);` in the URL branch, or remove the `await` in the data branch and make `getPdfUrl` non‑`async`, depending on whether the callback should be awaited or fire-and-forget.

Suggested implementation:

```javascript
const getPdfUrl = async (options, callback) => {
    if (options.url) {
        return await callback(options.url);
    }
    else if (options.data) {

```

Elsewhere in the same `getPdfUrl` function, update the `options.data` branch so that `await callback(url);` becomes `return await callback(url);`. This will ensure both branches return the awaited callback result, giving callers consistent behavior regardless of whether they pass `url` or `data`.
</issue_to_address>

### Comment 2
<location> `src/components/BootstrapBlazor.PdfReader/PdfReader.razor.js:571` </location>
<code_context>
 }

-const downloadPdf = (url, fileName) => {
+const downloadPdf = async (options, fileName) => {
     if (fileName === null) {
         fileName = "download.pdf";
</code_context>

<issue_to_address>
**issue (complexity):** Consider replacing the callback-based getPdfUrl and scattered iframe handling with simpler async-returning functions and small helpers to keep URL resolution and print iframe lifecycle linear and self-contained.

The new callback-based `getPdfUrl` and the way it’s used in `downloadPdf`/`printPdf` does add avoidable complexity without adding real value. You can keep all new functionality (support for `options.data`, iframe reuse under `el`) while simplifying the async flow and iframe lifecycle.

### 1. Simplify `getPdfUrl`, `downloadPdf`, and `printPdf` async flow

You don’t need a callback here; a plain `async` function that returns the URL is enough. That also removes the artificial `new Promise` wrappers.

```js
// Replace getPdfUrl(options, callback) with:
const getPdfUrl = async (options) => {
    if (options.url) {
        return options.url;
    }

    if (options.data) {
        const blob = new Blob([options.data], { type: "application/pdf" });
        const url = window.URL.createObjectURL(blob);
        return url;
    }

    return null; // or throw if neither url nor data is expected to be missing
};
```

Then simplify `downloadPdf`:

```js
const downloadPdf = async (options, fileName) => {
    if (fileName === null) {
        fileName = "download.pdf";
    }

    const url = await getPdfUrl(options);
    if (!url) return; // or handle error

    const anchorElement = document.createElement("a");
    anchorElement.href = url;
    anchorElement.download = fileName;
    document.body.appendChild(anchorElement);
    anchorElement.click();
    document.body.removeChild(anchorElement);

    if (options.data) {
        window.URL.revokeObjectURL(url);
    }
};
```

And `printPdf`:

```js
const printPdf = async (el, options) => {
    const iframe = getOrCreatePrintIframe(el);

    const url = await getPdfUrl(options);
    if (!url) return; // or handle error

    iframe.onload = () => {
        iframe.contentWindow.focus();
        iframe.contentWindow.print();

        if (options.data) {
            window.URL.revokeObjectURL(url);
        }
    };

    iframe.src = url;
};
```

This keeps `downloadPdf`/`printPdf` `async` only because they truly `await` something, and makes the control flow linear and easier to reason about.

### 2. Encapsulate iframe lifecycle

Right now iframe creation/reuse is embedded in `printPdf`, and removal happens in `disposePdf` via DOM queries. A tiny helper removes that mental overhead and keeps iframe logic in one place.

```js
const getOrCreatePrintIframe = (el) => {
    let iframe = el.querySelector(".bb-view-print-iframe");
    if (!iframe) {
        iframe = document.createElement("iframe");
        iframe.classList.add("bb-view-print-iframe");
        iframe.style.position = "fixed";
        iframe.style.right = "100%";
        iframe.style.bottom = "100%";
        el.appendChild(iframe);
    }
    return iframe;
};

const removePrintIframe = (el) => {
    const iframe = el.querySelector(".bb-view-print-iframe");
    if (iframe) {
        iframe.remove();
    }
};
```

Then use `removePrintIframe(el)` inside `disposePdf` instead of manually querying/removing the iframe there. This keeps all iframe lifecycle concerns self-contained and easier to maintain.
</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.

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 pull request enhances the PdfReader component to support printing PDFs from streams (data blobs) in addition to URLs. The changes refactor the print and download functionality to use a common helper function that handles both URL and data-based PDFs.

Key Changes

  • Refactored printPdf and downloadPdf functions to support both URL and data (stream) sources
  • Introduced a new getPdfUrl helper function to abstract URL vs. data handling
  • Updated iframe cleanup to be scoped to the component element instead of document-wide

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 6 comments.

File Description
PdfReader.razor.js Refactored print and download functions to support stream-based PDFs; added getPdfUrl helper; improved iframe lifecycle management
BootstrapBlazor.PdfReader.csproj Version bump from 10.0.20 to 10.0.21
Comments suppressed due to low confidence (9)

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

  • Unused variable title.
    const title = el.querySelector('.bb-view-pdf-dialog-title');

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

  • Unused variable author.
    const author = el.querySelector('.bb-view-pdf-dialog-author');

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

  • Unused variable subject.
    const subject = el.querySelector('.bb-view-pdf-dialog-subject');

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

  • Unused variable keywords.
    const keywords = el.querySelector('.bb-view-pdf-dialog-keywords');

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

  • Unused variable modified.
    const modified = el.querySelector('.bb-view-pdf-dialog-modified');

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

  • Unused variable webview.
    const webview = el.querySelector('.bb-view-pdf-dialog-view');

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

  • The initial value of v is unused, since it is always overwritten.
    let v = 100;

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

  • Avoid automated semicolon insertion (90% of all statements in the enclosing function have an explicit semicolon).
            })

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

  • Avoid automated semicolon insertion (91% of all statements in the enclosing function have an explicit semicolon).
    delete el.widths

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

Comment on lines +772 to +774
return new Promise((resolve, reject) => {
resolve();
});
Copy link

Copilot AI Dec 18, 2025

Choose a reason for hiding this comment

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

The Promise created here is unnecessary and doesn't serve any purpose. The promise is immediately resolved synchronously without waiting for any asynchronous operation. The callback should either return a meaningful promise (e.g., one that resolves when iframe.onload completes) or not return anything at all since the caller doesn't appear to need the return value.

Suggested change
return new Promise((resolve, reject) => {
resolve();
});

Copilot uses AI. Check for mistakes.
Comment on lines +583 to +586

return new Promise((resolve, reject) => {
resolve();
});
Copy link

Copilot AI Dec 18, 2025

Choose a reason for hiding this comment

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

The Promise created here is unnecessary and doesn't serve any purpose. The promise is immediately resolved synchronously without waiting for any asynchronous operation. The callback should either return a meaningful promise or not return anything at all since the caller doesn't appear to need the return value.

Suggested change
return new Promise((resolve, reject) => {
resolve();
});

Copilot uses AI. Check for mistakes.
const blob = new Blob([options.data], { type: 'application/pdf' });
var url = window.URL.createObjectURL(blob);
await callback(url);
window.URL.revokeObjectURL(url);
Copy link

Copilot AI Dec 18, 2025

Choose a reason for hiding this comment

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

The blob URL is revoked immediately after calling the callback, which may cause issues if the callback uses the URL asynchronously. For example, in printPdf, the URL is assigned to iframe.src, but the actual loading happens asynchronously via the onload event. Revoking the URL before the iframe finishes loading could result in a failed load. Consider revoking the URL only after the asynchronous operation completes, or adding a delay before revocation.

Copilot uses AI. Check for mistakes.
}
else if (options.data) {
const blob = new Blob([options.data], { type: 'application/pdf' });
var url = window.URL.createObjectURL(blob);
Copy link

Copilot AI Dec 18, 2025

Choose a reason for hiding this comment

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

Use 'const' or 'let' instead of 'var' to declare the url variable. The use of 'var' is inconsistent with modern JavaScript best practices and can lead to unexpected scoping issues.

Suggested change
var url = window.URL.createObjectURL(blob);
const url = window.URL.createObjectURL(blob);

Copilot uses AI. Check for mistakes.
document.body.appendChild(iframe);
const getPdfUrl = async (options, callback) => {
if (options.url) {
callback(options.url);
Copy link

Copilot AI Dec 18, 2025

Choose a reason for hiding this comment

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

When options.url is provided, the callback is invoked but its return value is not awaited. This is inconsistent with line 785 where the callback is awaited when options.data is used. This inconsistency could lead to race conditions or unexpected behavior. Either await the callback in both cases or remove the await in both cases, depending on whether the callback is expected to be asynchronous.

Suggested change
callback(options.url);
await callback(options.url);

Copilot uses AI. Check for mistakes.
printPdf(options.url);
await printPdf(el, options);
await invoke.invokeMethodAsync("Printing");
})
Copy link

Copilot AI Dec 18, 2025

Choose a reason for hiding this comment

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

Avoid automated semicolon insertion (95% of all statements in the enclosing function have an explicit semicolon).

Suggested change
})
});

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): print pdf function support stream

2 participants