You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor Server中如何让iframe内PDF定位到指定CNC参数行(无需定义目标)

实现方案

核心思路是借助浏览器内置PDF阅读器的文本搜索功能,通过Blazor组件传参+JavaScript交互,实现打开页面时自动定位到目标参数行,无需预先给PDF添加锚点。

步骤1:传递选中的参数到PDF弹窗

修改参数选择页面的代码,将选中的CNC参数作为参数传递给弹窗组件:

@page "/Par_selection"
@inject DialogService DialogService

<select @bind="@Cnc_Par_selected" @onchange="Open_PDF">
    @for (int r = 0; r < Sys_Var_Data.BAG_area.Count; r++)
    {
        <option>@Parameter_List[r]</option>                       
    }
</select>

@code {
    private string Cnc_Par_selected { get; set; }

    private async Task Open_PDF()
    {           
        await DialogService.OpenAsync<Cnc_Par_PDF>("CNC Parameters", 
            new DialogParameters { { "TargetParam", Cnc_Par_selected } },
            new DialogOptions { CloseDialogOnOverlayClick = true, ShowTitle = true, Width = "1500px", Height = "800px", Style = "left:200px; padding:0px" });
    }
}

步骤2:在PDF页面接收参数并触发自动搜索

修改PDF展示页面,通过IJSRuntime调用JavaScript脚本,在PDF加载完成后触发文本搜索:

@page "/Cnc_Par_PDF"
@inject IJSRuntime JSRuntime
@implements IDisposable

<iframe @ref="pdfIframe" src="/files/Cnc_Par.pdf" width="1500" height="800" frameborder="0"></iframe>

@code {
    [Parameter]
    public string TargetParam { get; set; }

    private ElementReference pdfIframe;
    private IJSObjectReference _jsModule;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender && !string.IsNullOrEmpty(TargetParam))
        {
            _jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./pdf-search.js");
            await _jsModule.InvokeVoidAsync("searchAndScroll", pdfIframe, TargetParam);
        }
    }

    public void Dispose()
    {
        _jsModule?.DisposeAsync();
    }
}

步骤3:创建JavaScript搜索脚本

在项目的wwwroot目录下新建pdf-search.js文件,实现PDF的搜索定位逻辑:

export function searchAndScroll(iframe, searchText) {
    if (!iframe.contentWindow || !searchText) return;

    // 等待PDF加载完成
    iframe.contentWindow.addEventListener('load', () => {
        setTimeout(() => {
            // 优先尝试通过postMessage触发PDF阅读器的静默搜索(针对Chrome/Firefox内置阅读器)
            const pdfEmbed = iframe.contentWindow.document.querySelector('embed');
            if (pdfEmbed?.contentWindow) {
                pdfEmbed.contentWindow.postMessage({ type: 'find', query: searchText }, '*');
            } else {
                // 备选方案:调用浏览器原生查找功能(兼容性更好,会显示查找框)
                iframe.contentWindow.focus();
                iframe.contentWindow.document.execCommand('Find', false, searchText);
            }
        }, 500); // 延迟时间可根据PDF大小调整
    });
}

注意事项

  • 浏览器兼容性:不同浏览器的内置PDF阅读器对postMessage的支持有差异,备选的原生查找功能兼容性更强,但会显示查找框。
  • 参数唯一性:确保传递的参数全名在PDF中唯一,避免定位到错误行。
  • 延迟调整:如果PDF文件较大,可适当增加setTimeout的延迟时间,确保PDF完全渲染后再执行搜索。

内容的提问来源于stack exchange,提问作者Mdarende

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 16:27:37