Vb.net 使用Webview2显示pdf文件

发布时间 2023-12-28 22:20:16作者: boy8199

使用webview2显示PDF文件

需要 wvliulanqi -- Webview2控件的 

Await Wv2.EnsureCoreWebView2Async 函数来启动 浏览器 否则会报错

注意 Div 的 宽度 高度

    Private Sub Button1_ClickAsync(sender As Object, e As EventArgs) Handles Button1.Click

        Dim strPath As String = Application.StartupPath & "\pdf\芦苇种类.pdf"
        If File.Exists(strPath) = True Then


            Dim myPdfBytes As Byte() = File.ReadAllBytes(strPath)
            Dim myPdfBase64 As String = Convert.ToBase64String(myPdfBytes)


            Dim htmlStr As String = "<!DOCTYPE html><html><head></head><body  height=""100%""  width=""100%""><div style=""height: 95vh"">" &
                "<iframe display=""block""  border=""none""  height=""100%""  width=""100%""  src=""data:Application/pdf;base64," &
                $"{myPdfBase64}"">" & "</iframe></div></body></html>"

            Dim unused = Liulan(htmlStr)
        End If
    End Sub


    Private Async Function Liulan(htmlstring As String) As Task
        Await Wvliulanqi.EnsureCoreWebView2Async
        Wvliulanqi.NavigateToString(htmlstring)
    End Function