当前位置: 首页 > news >正文

WPF/Net Core 简单显示PDF

使用自带的WebView2控件显示PDF文件

  • 第一种方式:WebView2库导入使用NuGet
  • 第二种方式:使用PDF第三方库显示

第一种方式:WebView2库导入使用NuGet

工具–>NuGet包管理器–>管理解决方案的NuGet程序包,搜索WebView2安装

xaml中加入

xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"

如下:

<Page x:Class="zAssist.PdfView"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"xmlns:local="clr-namespace:zAssist"mc:Ignorable="d" d:DesignHeight="600" d:DesignWidth="800"Title="PdfView"><Grid Background="White"><Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/></Grid.RowDefinitions><Button x:Name="btnBack"Background="Transparent"HorizontalAlignment="Left"VerticalAlignment="Top"Content="Sign in" FontSize="20"Width="150" Height="35"Click="btnBack_Click"><Button.Template><ControlTemplate TargetType="Button"><Grid><Grid.ColumnDefinitions><ColumnDefinition Width="Auto"/><ColumnDefinition Width="*"/></Grid.ColumnDefinitions><Image Grid.Column="0" x:Name="btnImage" Stretch="None"><Image.Style><Style TargetType="Image"><Setter Property="Source" Value="/Resources/back.png"/><Style.Triggers><DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource AncestorType=Button}}" Value="True"><Setter Property="Source" Value="/Resources/back.png"/></DataTrigger><DataTrigger Binding="{Binding IsPressed, RelativeSource={RelativeSource AncestorType=Button}}" Value="True"><Setter Property="Source" Value="/Resources/back.png"/></DataTrigger></Style.Triggers></Style></Image.Style></Image><TextBlock Grid.Column="1" Text="{TemplateBinding Content}"VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/></Grid></ControlTemplate></Button.Template></Button><!--用于显示Pdf 的 WebView2控件--><wv2:WebView2 Grid.Row="1" Name="webView" Loaded="WebView_Loaded"/>        </Grid>
</Page>

代码块:

using PdfViewer.Enums;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using System.Windows.Resources;
using System.Windows.Shapes;namespace zAssist;/// <summary>
/// PdfView.xaml 的交互逻辑
/// </summary>
public partial class PdfView : Page
{public PdfView (){InitializeComponent();this.DataContext = this;}private void btnBack_Click(object sender, RoutedEventArgs e){NavigationService.GetNavigationService(this).GoBack();//返回上一个界面,保持之前的操作}private void WebView_Loaded(object sender, RoutedEventArgs e){InitializeAsync();}private async void InitializeAsync(){await webView.EnsureCoreWebView2Async(null);//	webView.CoreWebView2.Navigate(Properties.Settings.Default.UrlForget);//必须绝对路径,下面两种方式都可以Uri pdfPath = new Uri(@"file:///E:/Tools/zSolution/Resources/files/test.pdf", UriKind.Absolute);//webView.CoreWebView2.Navigate(@"file:///E:/Tools/zSolution/Resources/files/test.pdf");webView.Source = pdfPath;}
}

第二种方式:使用PDF第三方库显示

使用NuGet 导入 PdfiumViewer.Native.x86.v8-xfa、PdfiumViewer.Native.x86_64-xfa、PropertyChanged.Fody(通知) 和第三方库 PdfiumViewer,在.Net Core工程种PdfiumViewer 库安装了但是不能使用,本人到github中把PdfiumViewer源码下载拿到测试代码移植到我的工程中的,PdfiumViewer github存放位置在NuGet中有
上代码:

<Page x:Class="zAssist.PdfView"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:zAssist"xmlns:pdfiumViewer="clr-namespace:PdfViewer;assembly=PdfViewer"xmlns:core="clr-namespace:PdfViewer.Core;assembly=PdfViewer"mc:Ignorable="d" d:DesignHeight="600" d:DesignWidth="800"Title="PdfView" Loaded="Page_Loaded"><Grid Background="White"><Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/></Grid.RowDefinitions><Button x:Name="btnBack" Background="Transparent"HorizontalAlignment="Left"VerticalAlignment="Top"Content="Register" FontSize="20"Width="120" Height="30" Click="btnBack_Click"><Button.Template><ControlTemplate TargetType="Button"><Grid><Grid.ColumnDefinitions><ColumnDefinition Width="Auto"/><ColumnDefinition Width="*"/></Grid.ColumnDefinitions><Image Grid.Column="0" x:Name="btnImage" Stretch="None"><Image.Style><Style TargetType="Image"><Setter Property="Source" Value="/Resources/back.png"/><Style.Triggers><DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource AncestorType=Button}}" Value="True"><Setter Property="Source" Value="/Resources/back.png"/></DataTrigger><DataTrigger Binding="{Binding IsPressed, RelativeSource={RelativeSource AncestorType=Button}}" Value="True"><Setter Property="Source" Value="/Resources/back.png"/></DataTrigger></Style.Triggers></Style></Image.Style></Image><TextBlock Grid.Column="1" Text="{TemplateBinding Content}"VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/></Grid></ControlTemplate></Button.Template></Button><pdfiumViewer:PdfRenderer Grid.Row="1" Name="Renderer" Padding="10"/><StackPanel Grid.Row="1"Background="Transparent"Orientation="Vertical"VerticalAlignment="Center"HorizontalAlignment="Right"Width="40"><Button ToolTip="Previous Page" Click="OnPrevPageClick"><Image Source="Resources/prev.png" /></Button><TextBlock VerticalAlignment="Center" FontSize="14"><Run Text="{Binding Page, Mode=OneWay}"/><Run Text="/"/><Run Text="{Binding ElementName=Renderer, Path=PageCount, Mode=OneWay}"/></TextBlock><Button ToolTip="Next Page" Click="OnNextPageClick"><Image Source="Resources/next.png" /></Button><Button ToolTip="Zoom in" Click="OnZoomInClick"><Image Source="Resources/zoom_in.png" /></Button><TextBlock VerticalAlignment="Center" FontSize="14"><Run Text="{Binding ZoomPercent, Mode=OneWay}"/><Run Text="%"/></TextBlock><Button ToolTip="Zoom out" Click="OnZoomOutClick"><Image Source="Resources/zoom_out.png" /></Button><Button ToolTip="Fit Width" Click="OnFitWidth"><Image Source="Resources/fit_width.png" /></Button><Button ToolTip="Fit Height" Click="OnFitHeight"><Image Source="Resources/fit_height.png" /></Button></StackPanel></Grid>
</Page>
using PdfViewer.Enums;
using System.ComponentModel;
using System.IO;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using System.Windows.Resources;namespace zAssist;/// <summary>/// PdfView.xaml 的交互逻辑/// </summary>
public partial class PdfView : Page, INotifyPropertyChanged
{public PrivacyNoticeView(){InitializeComponent();this.DataContext = this;Renderer.PropertyChanged += delegate{OnPropertyChanged(nameof(Page));OnPropertyChanged(nameof(ZoomPercent));};Renderer.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden;Renderer.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden;Renderer.MaxToFitWidth(true);}private void btnBack_Click(object sender, RoutedEventArgs e){OnClosePdf();NavigationService.GetNavigationService(this).GoBack();//返回上一个界面,保持之前的操作}public double ZoomPercent{get => (int)(Renderer.Zoom * 100);}public int Page{get => Renderer.PageNo + 1;set => Renderer.GotoPage(Math.Min(Math.Max(value - 1, 0), Renderer.PageCount - 1));}private void OpenPdf(){StreamResourceInfo info = App.GetResourceStream(new Uri(@"Resources\files\TermsAndConditions.pdf", uriKind: UriKind.Relative));using (var mem = new MemoryStream()){info.Stream.CopyTo(mem);Renderer.OpenPdf(mem);}}private void OnPrevPageClick(object sender, RoutedEventArgs e){Renderer.PreviousPage();}private void OnNextPageClick(object sender, RoutedEventArgs e){Renderer.NextPage();}private void OnFitWidth(object sender, RoutedEventArgs e){Renderer.SetZoomMode(PdfViewerZoomMode.FitWidth);}private void OnFitHeight(object sender, RoutedEventArgs e){Renderer.SetZoomMode(PdfViewerZoomMode.FitHeight);}private void OnZoomInClick(object sender, RoutedEventArgs e){Renderer.ZoomIn();}private void OnZoomOutClick(object sender, RoutedEventArgs e){if (Renderer.Zoom > 0.5){Renderer.ZoomOut();}}public event PropertyChangedEventHandler PropertyChanged;protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}private async void OnClosePdf(){try{Renderer.UnLoad();await Task.Delay(5000);}catch (Exception exception){Console.WriteLine(exception);}}private void Page_Loaded(object sender, RoutedEventArgs e){OpenPdf();}
}
http://www.lryc.cn/news/574604.html

相关文章:

  • WEB安全--Java安全--jsp webshell免杀1
  • 原子操作(CAS)
  • 【AI大模型】Spring AI 基于Redis实现对话持久存储详解
  • 打包上传到Linux部署并启动
  • 鸿蒙 FolderStack 组件全解析:折叠屏悬停布局开发指南
  • kvm console 的使用
  • linux网 络
  • 计算机基础和Java编程的练习题
  • 储能系统的离网,并网,构网,跟网 简介
  • 【HTTP】取消已发送的请求
  • Linux线程概念及常用接口(1)
  • OSS客户端签名直传实践:Web端安全上传TB级文件方案(含STS临时授权)
  • 从牛顿流体到弹性固体:旋转流变仪的高精度流变特性测定与工业应用
  • Unity_UI_NGUI_UI组件
  • 对人工智能的厌倦感是真实存在的,而且它给品牌带来的损失远不止是参与度的下降
  • 【Linux网络编程】多路转接I/O(一)select,poll
  • 51c嵌入式~电路~合集8
  • 一、永磁同步电机矢量控制——电机数学模型
  • 第十节 新特性与趋势-CSS层叠规则升级
  • AI智能化高效办公:WPS AI全场景深度应用指南
  • 设计模式系列(09):结构型模式 - 适配器模式
  • ffmpeg环境配置
  • HTTP响应头Content-Disposition解析
  • 【MV】编排8:基于时间线数据多层分段避免过度拟合特定歌曲
  • Verilog基础:编译指令`default_nettype
  • Windows搭建opencv cuda开发环境并验证是否成功
  • VO,DTO,BO,PO,DO
  • 7.5.3_2处理冲突的方法-开放定址法
  • Redis 分布式锁原理与实战-学习篇
  • 快速搭建系统原型,UI界面,有哪些高效的AI工具和方法