在C# WPF项目中集成PDF查看器的两种方法

发布时间:2026/5/24 17:01:45

在C# WPF项目中集成PDF查看器的两种方法 方法1通过 NuGet 包安装并手动创建控件推荐1. 安装 NuGet 包123!-- 在你的 WPF 项目的 .csproj 文件中添加 --PackageReferenceIncludePdfiumViewerVersion2.11.0/PackageReferenceIncludePdfiumViewer.Native.x86_64.v8-xfaVersion2023.6.12.1/或通过 NuGet 包管理器控制台12Install-Package PdfiumViewerInstall-Package PdfiumViewer.Native.x86_64.v8-xfa2. 在 XAML 中设置 WindowsFormsHost由于 PdfiumViewer 是 WinForms 控件需要在 WPF 中使用WindowsFormsHost1234567891011121314!-- 在 MainWindow.xaml 中 --Windowx:ClassYourNamespace.MainWindowxmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlxmlns:dhttp://schemas.microsoft.com/expression/blend/2008xmlns:mchttp://schemas.openxmlformats.org/markup-compatibility/2006xmlns:wfclr-namespace:System.Windows.Forms;assemblySystem.Windows.Formsmc:IgnorabledTitlePDF ViewerHeight600Width800GridWindowsFormsHostx:NamepdfHostMargin10//Grid/Window3. 在代码后台创建和使用 PdfViewer123456789101112131415161718192021222324252627282930313233343536373839404142434445464748usingSystem;usingSystem.Windows;usingPdfiumViewer;usingSystem.Windows.Forms.Integration;namespaceYourNamespace{publicpartialclassMainWindow : Window{privatePdfViewer pdfViewer;publicMainWindow(){InitializeComponent();InitializePdfViewer();}privatevoidInitializePdfViewer(){// 创建 PdfViewer 实例pdfViewer newPdfViewer();pdfViewer.Dock System.Windows.Forms.DockStyle.Fill;// 将 PdfViewer 添加到 WindowsFormsHostpdfHost.Child pdfViewer;}// 打开 PDF 文件privatevoidOpenPdf(stringfilePath){try{// 加载 PDF 文档pdfViewer.Document PdfDocument.Load(filePath);}catch(Exception ex){MessageBox.Show($打开 PDF 失败: {ex.Message});}}// 示例在窗口加载时打开 PDFprivatevoidWindow_Loaded(objectsender, RoutedEventArgs e){OpenPdf(C:\path\to\your\document.pdf);}}}方法2创建自定义 WPF 控件更优雅1. 创建 PdfViewerWrapper 用户控件123456789101112!-- PdfViewerWrapper.xaml --UserControlx:ClassYourNamespace.Controls.PdfViewerWrapperxmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlxmlns:mchttp://schemas.openxmlformats.org/markup-compatibility/2006xmlns:dhttp://schemas.microsoft.com/expression/blend/2008mc:Ignorabledd:DesignHeight450d:DesignWidth800GridWindowsFormsHostx:Namehost//Grid/UserControl1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283// PdfViewerWrapper.xaml.csusingSystem;usingSystem.Windows;usingSystem.Windows.Controls;usingPdfiumViewer;usingSystem.Windows.Forms.Integration;namespaceYourNamespace.Controls{publicpartialclassPdfViewerWrapper : UserControl{privatePdfViewer pdfViewer;publicPdfViewerWrapper(){InitializeComponent();InitializePdfViewer();}privatevoidInitializePdfViewer(){pdfViewer newPdfViewer{Dock System.Windows.Forms.DockStyle.Fill};host.Child pdfViewer;}// 打开 PDF 文件publicvoidLoadPdf(stringfilePath){try{pdfViewer.Document PdfDocument.Load(filePath);}catch(Exception ex){MessageBox.Show($加载 PDF 失败: {ex.Message});}}// 从字节数组加载publicvoidLoadPdf(byte[] pdfData){try{pdfViewer.Document PdfDocument.Load(pdfData);}catch(Exception ex){MessageBox.Show($加载 PDF 失败: {ex.Message});}}// 从流加载publicvoidLoadPdf(System.IO.Stream stream){try{pdfViewer.Document PdfDocument.Load(stream);}catch(Exception ex){MessageBox.Show($加载 PDF 失败: {ex.Message});}}// 获取当前页面索引publicintGetCurrentPage(){returnpdfViewer?.Renderer?.Page ?? 0;}// 跳转到指定页面publicvoidGoToPage(intpage){if(pdfViewer?.Renderer !null page 0 page pdfViewer.Document.PageCount){pdfViewer.Renderer.Page page;}}}}2. 在主窗口中使用自定义控件1234567891011121314151617181920212223242526!-- MainWindow.xaml --Windowx:ClassYourNamespace.MainWindowxmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlxmlns:controlsclr-namespace:YourNamespace.ControlsTitlePDF ViewerHeight600Width800GridGrid.RowDefinitionsRowDefinitionHeightAuto/RowDefinitionHeight*//Grid.RowDefinitions!-- 工具栏 --StackPanelGrid.Row0OrientationHorizontalMargin10ButtonContent打开 PDFClickOpenPdfButton_ClickMargin5/ButtonContent上一页ClickPrevPageButton_ClickMargin5/ButtonContent下一页ClickNextPageButton_ClickMargin5/TextBlockText页码VerticalAlignmentCenterMargin10,0,5,0/TextBlockx:NamepageInfoVerticalAlignmentCenter//StackPanel!-- PDF 查看器 --controls:PdfViewerWrapperx:NamepdfViewerControlGrid.Row1//Grid/Window12345678910111213141516171819202122232425262728293031323334353637383940414243// MainWindow.xaml.csusingMicrosoft.Win32;usingSystem.Windows;namespaceYourNamespace{publicpartialclassMainWindow : Window{publicMainWindow(){InitializeComponent();}privatevoidOpenPdfButton_Click(objectsender, RoutedEventArgs e){var openFileDialog newOpenFileDialog{Filter PDF 文件|*.pdf|所有文件|*.*,Title 选择 PDF 文件};if(openFileDialog.ShowDialog() true){pdfViewerControl.LoadPdf(openFileDialog.FileName);}}privatevoidPrevPageButton_Click(objectsender, RoutedEventArgs e){intcurrentPage pdfViewerControl.GetCurrentPage();if(currentPage 0){pdfViewerControl.GoToPage(currentPage - 1);}}privatevoidNextPageButton_Click(objectsender, RoutedEventArgs e){intcurrentPage pdfViewerControl.GetCurrentPage();pdfViewerControl.GoToPage(currentPage 1);}}}方法3使用 PdfRenderer 而不是 PdfViewer如果你只需要简单的 PDF 渲染没有工具栏可以使用PdfRenderer12345678910111213141516171819202122232425262728293031323334usingSystem.Windows;usingSystem.Windows.Forms.Integration;usingPdfiumViewer;publicpartialclassMainWindow : Window{privatePdfRenderer pdfRenderer;publicMainWindow(){InitializeComponent();InitializePdfRenderer();}privatevoidInitializePdfRenderer(){pdfRenderer newPdfRenderer();pdfRenderer.Dock System.Windows.Forms.DockStyle.Fill;pdfRenderer.ZoomMode PdfViewerZoomMode.FitWidth;// 添加到 WindowsFormsHostvar host newWindowsFormsHost();host.Child pdfRenderer;// 添加到 WPF 容器contentContainer.Children.Add(host);}privatevoidLoadPdf(stringfilePath){var document PdfDocument.Load(filePath);pdfRenderer.Load(document);}}解决常见问题问题1找不到 PdfiumViewer 控件原因PdfiumViewer 是 WinForms 控件不会自动出现在 WPF 工具箱中解决方案手动创建控件实例如上所示问题2运行时异常DLL 未找到1234!-- 在 .csproj 中确保包含 Native 包 --PackageReferenceIncludePdfiumViewer.Native.x86_64.v8-xfaVersion2023.6.12.1/!-- 或 x86 版本 --PackageReferenceIncludePdfiumViewer.Native.x86.v8-xfaVersion2023.6.12.1/问题3设计时看不到控件原因WinForms 控件在 WPF 设计器中不可见解决方案在设计时显示占位符运行时加载真实控件12345678910!-- 在设计时显示标签运行时替换 --UserControlGridTextBlockx:NamedesignTextTextPDF Viewer (设计时)Visibility{Binding IsInDesignMode, Converter{StaticResource BoolToVisibilityConverter}}/WindowsFormsHostx:NamehostVisibility{Binding IsInDesignMode, Converter{StaticResource BoolToVisibilityInverseConverter}}//Grid/UserControl完整示例项目结构123456789YourSolution/├── YourWpfProject/│ ├── Controls/│ │ ├── PdfViewerWrapper.xaml│ │ └── PdfViewerWrapper.xaml.cs│ ├── MainWindow.xaml│ ├── MainWindow.xaml.cs│ └── YourWpfProject.csproj└── YourWpfProject.sln在工具箱中手动添加控件可选虽然不能直接拖拽但你可以创建自定义控件库将 PdfViewerWrapper 控件编译为独立的 DLL添加到工具箱右键点击工具箱 → “选择项”浏览并选择你的控件 DLL控件将出现在工具箱中总结在 WPF 中使用 PdfiumViewer 的关键步骤安装 NuGet 包PdfiumViewer 及其 Native 包使用 WindowsFormsHost承载 WinForms 控件代码创建控件在代码后台或自定义用户控件中实例化 PdfViewer加载 PDF使用PdfDocument.Load()方法虽然不能像 WinForms 那样直接在工具箱中拖拽但通过创建自定义用户控件你可以在 WPF 中获得类似的开发体验。

相关新闻