WPF display and host pdf via WebBrowser

//xaml
<Window x:Class="WpfApp206.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp206"
        mc:Ignorable="d" WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <ToolBar Grid.Row="0">
            <Button Content="Open" Click="OpenClick"/>
        </ToolBar>
        <WebBrowser Grid.Row="1" x:Name="webBrowser"/>
    </Grid>
</Window>


//cs
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;

namespace WpfApp206
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent(); 
        } 

        private void OpenClick(object sender, RoutedEventArgs e)
        { 
            OpenFileDialog dialog=new OpenFileDialog();
            dialog.Filter = "PDF Files|*.pdf|All Files|*.*";
            if(dialog.ShowDialog()==true)
            { 
                try
                {
                    string pdfPath = dialog.FileName;
                    if (File.Exists(pdfPath))
                    {
                        Uri uri = new Uri(pdfPath, UriKind.RelativeOrAbsolute);
                        webBrowser.Navigate(uri);
                    }
                }
                catch (Exception ex)
                { 
                    MessageBox.Show(ex.Message);
                } 
            }
        }
    }
}

 

 

posted @ 2024-07-12 11:52  FredGrit  阅读(4)  评论(0编辑  收藏  举报