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

在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 中获得类似的开发体验。
http://www.gsyq.cn/news/1370286.html

相关文章:

  • 【专业级】Draw.io ECE电路设计库:电子工程师的绘图效率革命
  • 3大架构重构:Betaflight开源飞控系统的性能突破与系统优化
  • 从零构建全球生活便利指数:基于因子分析与随机森林插补的数据工程实践
  • 工业AI质检如何通过标准化数据集实现技术跨越?
  • 2026年京东云OpenClaw/Hermes Agent配置Token Plan集成新手必看
  • Hotkey Detective:Windows热键冲突终极排查指南,3分钟解决快捷键失灵难题
  • Postman便携版终极指南:无需安装的Windows API开发利器
  • 基于SpringBoot的校园心理健康匿名互助社区毕设源码
  • 基于SpringBoot的技术博客与开源知识分享平台毕设
  • 利用Taotoken多模型广场为不同业务场景选择最优模型
  • DML交叉验证折数K选择:DML2优于DML1,K=10是高效折中方案
  • SpringBoot+Vue电影票购买系统源码+论文
  • 量子机器学习在电力系统隐蔽攻击检测中的应用
  • 微信小程序ECharts图表库终极指南:5分钟打造专业数据可视化应用
  • 别再乱删软连接了!深入理解Linux glibc:从/lib64/libc.so.6看动态链接库的版本管理与依赖陷阱
  • 2026 桂林房屋漏水不用愁!雨中匠人免费上门检测,本地专业防水公司常年TOP1!卫生间免砸砖防水,快速解决您的烦恼。权威!靠谱!稳定!售后无忧!!! - 防水百科
  • 2026广东五大代理记账及公司注册服务推荐:2026 最新排名出炉,广州瑞讯财务咨询有限公司以十五年深耕实力赢得口碑 - 十大品牌榜
  • CentOS停服后,我为什么选了Rocky Linux 8.9?手把手教你从下载到配置网卡(附避坑点)
  • 告别TeamViewer!在Ubuntu 22.04上安装向日葵远程控制的完整保姆级教程
  • 科学机器学习:从隐式动力学到时空算子学习的模型构建与实践
  • UABEA:Unity资源提取、编辑与重建的跨平台生产级工具
  • 终极窗口尺寸控制指南:如何突破Windows应用程序窗口限制
  • 常州闲置名牌包包怎么选?4 家变现渠道实测测评 - 李宏哲1
  • 广东代理记账/公司注册公司专题:广州瑞讯财务咨询有限公司深度问答 - 十大品牌榜
  • 2026 湖州房屋漏水不用愁!雨中匠人免费上门检测,本地专业防水公司常年TOP1!卫生间免砸砖防水,快速解决您的烦恼。权威!靠谱!稳定!售后无忧!!! - 防水百科
  • 机器学习能耗评估工具对比:芯片传感器与估算模型实战解析
  • 响应安全规程硬性要求,无感定位规范井下人员管理 ——矿山合规化人员智能管控技术方案
  • 【Sora 2时间轴精修终极指南】:从0.01秒关键帧微调到运动矢量对齐,Adobe Premiere Pro + DaVinci Resolve双平台实操手册
  • 海南靠谱财税公司代办 TOP4 推荐:2026 年封关前企业注册首选服务商全攻略 - 资讯纵览
  • 2026 泉州房屋漏水不用愁!雨中匠人免费上门检测,本地专业防水公司常年TOP1!卫生间免砸砖防水,快速解决您的烦恼。权威!靠谱!稳定!售后无忧!!! - 防水百科