Enable Blazor-JS communication for PDF viewer zoom
Added `DotNetObjectReference` in `EnvelopeViewer.razor` to enable Blazor-JS communication. Updated `OnAfterRenderAsync` to pass the reference to `pdfViewer.initialize`. Introduced `[JSInvokable]` method `OnZoomChanged` to handle zoom updates from JavaScript. Enhanced `DisposeAsync` to clean up resources, including disposing of the `.NET reference` and invoking a JavaScript `dispose` method. In `pdf-viewer.js`, modified `initialize` to accept a `.NET reference` and added `attachWheelEvent` to handle zooming via mouse wheel with `Ctrl`/`Meta` key. Updated `dispose` to clean up event listeners and reset the `.NET reference`. Added `getScale` to retrieve the current zoom scale. Improved resource cleanup and event handling to prevent memory leaks and ensure stability.
This commit is contained in:
@@ -117,6 +117,7 @@
|
||||
int _currentPage = 1;
|
||||
int _totalPages = 0;
|
||||
int _currentZoom = 150;
|
||||
DotNetObjectReference<EnvelopeViewer>? _dotNetRef;
|
||||
|
||||
protected override async Task OnInitializedAsync() {
|
||||
if (string.IsNullOrWhiteSpace(EnvelopeKey)) {
|
||||
@@ -147,7 +148,8 @@
|
||||
await Task.Delay(500);
|
||||
|
||||
try {
|
||||
var success = await JSRuntime.InvokeAsync<bool>("pdfViewer.initialize", "pdf-canvas", _pdfDataUrl);
|
||||
_dotNetRef = DotNetObjectReference.Create(this);
|
||||
var success = await JSRuntime.InvokeAsync<bool>("pdfViewer.initialize", "pdf-canvas", _pdfDataUrl, _dotNetRef);
|
||||
|
||||
if (success) {
|
||||
_pdfLoaded = true;
|
||||
@@ -162,6 +164,13 @@
|
||||
}
|
||||
}
|
||||
|
||||
[JSInvokable]
|
||||
public async Task OnZoomChanged(double scale)
|
||||
{
|
||||
_currentZoom = (int)(scale * 100);
|
||||
await InvokeAsync(StateHasChanged);
|
||||
}
|
||||
|
||||
async Task NextPage() {
|
||||
if (await JSRuntime.InvokeAsync<bool>("pdfViewer.nextPage")) {
|
||||
_currentPage = await JSRuntime.InvokeAsync<int>("pdfViewer.getCurrentPage");
|
||||
@@ -187,6 +196,13 @@
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync() {
|
||||
// Cleanup if needed
|
||||
if (_pdfLoaded) {
|
||||
try {
|
||||
await JSRuntime.InvokeVoidAsync("pdfViewer.dispose");
|
||||
} catch {
|
||||
// Ignore errors during disposal
|
||||
}
|
||||
}
|
||||
_dotNetRef?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user