最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

在C# WPF項(xiàng)目中集成PDF查看器的兩種方法

 更新時(shí)間:2025年12月29日 09:40:09   作者:????風(fēng)、凌???  
文章介紹了在WPF中使用PdfiumViewer控件的兩種方法:通過(guò)NuGet包安裝并手動(dòng)創(chuàng)建控件,創(chuàng)建自定義WPF控件,文章還解決了在WPF中使用PdfiumViewer時(shí)可能出現(xiàn)的常見(jiàn)問(wèn)題,需要的朋友可以參考下

方法1:通過(guò) NuGet 包安裝并手動(dòng)創(chuàng)建控件(推薦)

1. 安裝 NuGet 包

<!-- 在你的 WPF 項(xiàng)目的 .csproj 文件中添加 -->
<PackageReference Include="PdfiumViewer" Version="2.11.0" />
<PackageReference Include="PdfiumViewer.Native.x86_64.v8-xfa" Version="2023.6.12.1" />

或通過(guò) NuGet 包管理器控制臺(tái):

Install-Package PdfiumViewer
Install-Package PdfiumViewer.Native.x86_64.v8-xfa

2. 在 XAML 中設(shè)置 WindowsFormsHost

由于 PdfiumViewer 是 WinForms 控件,需要在 WPF 中使用 WindowsFormsHost

<!-- 在 MainWindow.xaml 中 -->
<Window x:Class="YourNamespace.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:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
        mc:Ignorable="d"
        Title="PDF Viewer" Height="600" Width="800">
    
    <Grid>
        <WindowsFormsHost x:Name="pdfHost" Margin="10"/>
    </Grid>
</Window>

3. 在代碼后臺(tái)創(chuàng)建和使用 PdfViewer

using System;
using System.Windows;
using PdfiumViewer;
using System.Windows.Forms.Integration;

namespace YourNamespace
{
    public partial class MainWindow : Window
    {
        private PdfViewer pdfViewer;
        
        public MainWindow()
        {
            InitializeComponent();
            InitializePdfViewer();
        }
        
        private void InitializePdfViewer()
        {
            // 創(chuàng)建 PdfViewer 實(shí)例
            pdfViewer = new PdfViewer();
            pdfViewer.Dock = System.Windows.Forms.DockStyle.Fill;
            
            // 將 PdfViewer 添加到 WindowsFormsHost
            pdfHost.Child = pdfViewer;
        }
        
        // 打開(kāi) PDF 文件
        private void OpenPdf(string filePath)
        {
            try
            {
                // 加載 PDF 文檔
                pdfViewer.Document = PdfDocument.Load(filePath);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打開(kāi) PDF 失敗: {ex.Message}");
            }
        }
        
        // 示例:在窗口加載時(shí)打開(kāi) PDF
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            OpenPdf(@"C:\path\to\your\document.pdf");
        }
    }
}

方法2:創(chuàng)建自定義 WPF 控件(更優(yōu)雅)

1. 創(chuàng)建 PdfViewerWrapper 用戶控件

<!-- PdfViewerWrapper.xaml -->
<UserControl x:Class="YourNamespace.Controls.PdfViewerWrapper"
             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" 
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <WindowsFormsHost x:Name="host"/>
    </Grid>
</UserControl>
// PdfViewerWrapper.xaml.cs
using System;
using System.Windows;
using System.Windows.Controls;
using PdfiumViewer;
using System.Windows.Forms.Integration;

namespace YourNamespace.Controls
{
    public partial class PdfViewerWrapper : UserControl
    {
        private PdfViewer pdfViewer;
        
        public PdfViewerWrapper()
        {
            InitializeComponent();
            InitializePdfViewer();
        }
        
        private void InitializePdfViewer()
        {
            pdfViewer = new PdfViewer
            {
                Dock = System.Windows.Forms.DockStyle.Fill
            };
            host.Child = pdfViewer;
        }
        
        // 打開(kāi) PDF 文件
        public void LoadPdf(string filePath)
        {
            try
            {
                pdfViewer.Document = PdfDocument.Load(filePath);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加載 PDF 失敗: {ex.Message}");
            }
        }
        
        // 從字節(jié)數(shù)組加載
        public void LoadPdf(byte[] pdfData)
        {
            try
            {
                pdfViewer.Document = PdfDocument.Load(pdfData);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加載 PDF 失敗: {ex.Message}");
            }
        }
        
        // 從流加載
        public void LoadPdf(System.IO.Stream stream)
        {
            try
            {
                pdfViewer.Document = PdfDocument.Load(stream);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加載 PDF 失敗: {ex.Message}");
            }
        }
        
        // 獲取當(dāng)前頁(yè)面索引
        public int GetCurrentPage()
        {
            return pdfViewer?.Renderer?.Page ?? 0;
        }
        
        // 跳轉(zhuǎn)到指定頁(yè)面
        public void GoToPage(int page)
        {
            if (pdfViewer?.Renderer != null && page >= 0 && page < pdfViewer.Document.PageCount)
            {
                pdfViewer.Renderer.Page = page;
            }
        }
    }
}

2. 在主窗口中使用自定義控件

<!-- MainWindow.xaml -->
<Window x:Class="YourNamespace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:controls="clr-namespace:YourNamespace.Controls"
        Title="PDF Viewer" Height="600" Width="800">
    
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        
        <!-- 工具欄 -->
        <StackPanel Grid.Row="0" Orientation="Horizontal" Margin="10">
            <Button Content="打開(kāi) PDF" Click="OpenPdfButton_Click" Margin="5"/>
            <Button Content="上一頁(yè)" Click="PrevPageButton_Click" Margin="5"/>
            <Button Content="下一頁(yè)" Click="NextPageButton_Click" Margin="5"/>
            <TextBlock Text="頁(yè)碼:" VerticalAlignment="Center" Margin="10,0,5,0"/>
            <TextBlock x:Name="pageInfo" VerticalAlignment="Center"/>
        </StackPanel>
        
        <!-- PDF 查看器 -->
        <controls:PdfViewerWrapper x:Name="pdfViewerControl" Grid.Row="1"/>
    </Grid>
</Window>
// MainWindow.xaml.cs
using Microsoft.Win32;
using System.Windows;

namespace YourNamespace
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        
        private void OpenPdfButton_Click(object sender, RoutedEventArgs e)
        {
            var openFileDialog = new OpenFileDialog
            {
                Filter = "PDF 文件|*.pdf|所有文件|*.*",
                Title = "選擇 PDF 文件"
            };
            
            if (openFileDialog.ShowDialog() == true)
            {
                pdfViewerControl.LoadPdf(openFileDialog.FileName);
            }
        }
        
        private void PrevPageButton_Click(object sender, RoutedEventArgs e)
        {
            int currentPage = pdfViewerControl.GetCurrentPage();
            if (currentPage > 0)
            {
                pdfViewerControl.GoToPage(currentPage - 1);
            }
        }
        
        private void NextPageButton_Click(object sender, RoutedEventArgs e)
        {
            int currentPage = pdfViewerControl.GetCurrentPage();
            pdfViewerControl.GoToPage(currentPage + 1);
        }
    }
}

方法3:使用 PdfRenderer 而不是 PdfViewer

如果你只需要簡(jiǎn)單的 PDF 渲染(沒(méi)有工具欄),可以使用 PdfRenderer

using System.Windows;
using System.Windows.Forms.Integration;
using PdfiumViewer;

public partial class MainWindow : Window
{
    private PdfRenderer pdfRenderer;
    
    public MainWindow()
    {
        InitializeComponent();
        InitializePdfRenderer();
    }
    
    private void InitializePdfRenderer()
    {
        pdfRenderer = new PdfRenderer();
        pdfRenderer.Dock = System.Windows.Forms.DockStyle.Fill;
        pdfRenderer.ZoomMode = PdfViewerZoomMode.FitWidth;
        
        // 添加到 WindowsFormsHost
        var host = new WindowsFormsHost();
        host.Child = pdfRenderer;
        
        // 添加到 WPF 容器
        contentContainer.Children.Add(host);
    }
    
    private void LoadPdf(string filePath)
    {
        var document = PdfDocument.Load(filePath);
        pdfRenderer.Load(document);
    }
}

解決常見(jiàn)問(wèn)題

問(wèn)題1:找不到 PdfiumViewer 控件

  • 原因:PdfiumViewer 是 WinForms 控件,不會(huì)自動(dòng)出現(xiàn)在 WPF 工具箱中
  • 解決方案:手動(dòng)創(chuàng)建控件實(shí)例,如上所示

問(wèn)題2:運(yùn)行時(shí)異常(DLL 未找到)

<!-- 在 .csproj 中確保包含 Native 包 -->
<PackageReference Include="PdfiumViewer.Native.x86_64.v8-xfa" Version="2023.6.12.1" />
<!-- 或 x86 版本 -->
<PackageReference Include="PdfiumViewer.Native.x86.v8-xfa" Version="2023.6.12.1" />

問(wèn)題3:設(shè)計(jì)時(shí)看不到控件

  • 原因:WinForms 控件在 WPF 設(shè)計(jì)器中不可見(jiàn)
  • 解決方案:在設(shè)計(jì)時(shí)顯示占位符,運(yùn)行時(shí)加載真實(shí)控件
<!-- 在設(shè)計(jì)時(shí)顯示標(biāo)簽,運(yùn)行時(shí)替換 -->
<UserControl>
    <Grid>
        <TextBlock x:Name="designText" 
                   Text="PDF Viewer (設(shè)計(jì)時(shí))"
                   Visibility="{Binding IsInDesignMode, Converter={StaticResource BoolToVisibilityConverter}}"/>
        <WindowsFormsHost x:Name="host" 
                          Visibility="{Binding IsInDesignMode, Converter={StaticResource BoolToVisibilityInverseConverter}}"/>
    </Grid>
</UserControl>

完整示例項(xiàng)目結(jié)構(gòu)

YourSolution/
├── YourWpfProject/
│   ├── Controls/
│   │   ├── PdfViewerWrapper.xaml
│   │   └── PdfViewerWrapper.xaml.cs
│   ├── MainWindow.xaml
│   ├── MainWindow.xaml.cs
│   └── YourWpfProject.csproj
└── YourWpfProject.sln

在工具箱中手動(dòng)添加控件(可選)

雖然不能直接拖拽,但你可以:

  1. 創(chuàng)建自定義控件庫(kù):將 PdfViewerWrapper 控件編譯為獨(dú)立的 DLL
  2. 添加到工具箱
    • 右鍵點(diǎn)擊工具箱 → “選擇項(xiàng)”
    • 瀏覽并選擇你的控件 DLL
    • 控件將出現(xiàn)在工具箱中

總結(jié)

在 WPF 中使用 PdfiumViewer 的關(guān)鍵步驟:

  1. 安裝 NuGet 包:PdfiumViewer 及其 Native 包
  2. 使用 WindowsFormsHost:承載 WinForms 控件
  3. 代碼創(chuàng)建控件:在代碼后臺(tái)或自定義用戶控件中實(shí)例化 PdfViewer
  4. 加載 PDF:使用 PdfDocument.Load() 方法

雖然不能像 WinForms 那樣直接在工具箱中拖拽,但通過(guò)創(chuàng)建自定義用戶控件,你可以在 WPF 中獲得類似的開(kāi)發(fā)體驗(yàn)。

以上就是在C# WPF項(xiàng)目中集成PDF查看器的兩種方法的詳細(xì)內(nèi)容,更多關(guān)于C# WPF集成PDF查看器的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論

两当县| 定远县| 湖口县| 定襄县| 若尔盖县| 齐河县| 吉首市| 奉贤区| 科技| 南漳县| 抚州市| 安阳市| 玉树县| 灯塔市| 仲巴县| 华容县| 新和县| 垣曲县| 濉溪县| 尉氏县| 集贤县| 灵宝市| 芜湖县| 晋中市| 赣州市| 高清| 卓尼县| 建宁县| 库伦旗| 彭水| 都江堰市| 曲周县| 南宫市| 高陵县| 香港| 雷波县| 修水县| 吉安市| 苗栗县| 广昌县| 古田县|