You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

WPF中能否用DocumentViewer控件打开PDF?如何设置文档路径?

WPF DocumentViewer 打开PDF的解决方案

嘿,我来帮你理清楚这个问题:WPF自带的DocumentViewer控件并不原生支持PDF文档,它主要是用来展示WPF专属的文档类型(比如FlowDocumentFixedDocument这类实现了IDocumentPaginatorSource接口的文档),所以你没法直接通过设置某个路径属性让它打开PDF。

不过别担心,有几种靠谱的方案可以实现你的需求,下面给你详细说明:

方案一:使用开源第三方库 PdfiumViewer.Wpf

这是一个轻量、开源的PDF查看库,专门支持WPF,使用起来很方便:

  1. 首先在你的项目中通过NuGet安装PdfiumViewer.Wpf包;
  2. 修改你的XAML代码,替换成Pdfium的WPF控件(或者添加到你的布局中):
<Window x:Class="YourNamespace.YourWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:pdf="clr-namespace:PdfiumViewer.Wpf;assembly=PdfiumViewer.Wpf">
    <Grid>
        <!-- 替换你原来的DocumentViewer为这个PDF查看控件 -->
        <pdf:PdfViewer x:Name="pdfViewer" HorizontalAlignment="Left" VerticalAlignment="Top" Width="792" Height="419" Grid.ColumnSpan="2"/>
    </Grid>
</Window>
  1. 在C#后台代码中加载PDF文件:
// 直接加载本地PDF文件路径
pdfViewer.Load(@"C:\YourFolder\YourFile.pdf");

// 或者从文件流加载(适合需要读取嵌入式资源或网络流的场景)
using (var stream = System.IO.File.OpenRead(@"C:\YourFolder\YourFile.pdf"))
{
    pdfViewer.Load(stream);
}

方案二:嵌入Windows Forms的WebBrowser控件(依赖系统PDF阅读器)

如果你不想引入第三方库,可以借助Windows Forms的WebBrowser控件,它会调用系统自带的PDF阅读器(比如Edge的PDF组件)来展示PDF:

  1. 先给项目添加两个引用:WindowsFormsIntegrationSystem.Windows.Forms
  2. 修改XAML代码,使用WindowsFormsHost嵌入WebBrowser:
<Window x:Class="YourNamespace.YourWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wfi="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
        xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms">
    <Grid>
        <wfi:WindowsFormsHost HorizontalAlignment="Left" VerticalAlignment="Top" Width="792" Height="419" Grid.ColumnSpan="2">
            <wf:WebBrowser x:Name="pdfWebBrowser"/>
        </wfi:WindowsFormsHost>
    </Grid>
</Window>
  1. 后台代码加载PDF:
// 导航到本地PDF文件路径
pdfWebBrowser.Navigate(@"C:\YourFolder\YourFile.pdf");

注意:这个方案依赖系统已安装的PDF阅读器,如果用户系统没有合适的阅读器,可能无法正常显示。

补充说明

你原来的DocumentViewer控件的Document属性只能接受实现了IDocumentPaginatorSource接口的对象,而PDF格式并不属于这个范畴,所以没法直接通过设置路径来打开PDF。上面的两种方案是目前WPF中实现PDF查看最常用的方式。

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

火山引擎 最新活动