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

在C# WPF項目中集成PDF查看器的兩種方法

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

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

1. 安裝 NuGet 包

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

或通過 NuGet 包管理器控制臺:

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

2. 在 XAML 中設置 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. 在代碼后臺創(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 實例
            pdfViewer = new PdfViewer();
            pdfViewer.Dock = System.Windows.Forms.DockStyle.Fill;
            
            // 將 PdfViewer 添加到 WindowsFormsHost
            pdfHost.Child = pdfViewer;
        }
        
        // 打開 PDF 文件
        private void OpenPdf(string filePath)
        {
            try
            {
                // 加載 PDF 文檔
                pdfViewer.Document = PdfDocument.Load(filePath);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打開 PDF 失敗: {ex.Message}");
            }
        }
        
        // 示例:在窗口加載時打開 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;
        }
        
        // 打開 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}");
            }
        }
        
        // 獲取當前頁面索引
        public int GetCurrentPage()
        {
            return pdfViewer?.Renderer?.Page ?? 0;
        }
        
        // 跳轉(zhuǎn)到指定頁面
        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="打開 PDF" Click="OpenPdfButton_Click" Margin="5"/>
            <Button Content="上一頁" Click="PrevPageButton_Click" Margin="5"/>
            <Button Content="下一頁" Click="NextPageButton_Click" Margin="5"/>
            <TextBlock Text="頁碼:" 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

如果你只需要簡單的 PDF 渲染(沒有工具欄),可以使用 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);
    }
}

解決常見問題

問題1:找不到 PdfiumViewer 控件

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

問題2:運行時異常(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" />

問題3:設計時看不到控件

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

完整示例項目結構

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

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

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

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

總結

在 WPF 中使用 PdfiumViewer 的關鍵步驟:

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

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

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

相關文章

最新評論

潜山县| 隆回县| 延边| 永泰县| 仁布县| 渝中区| 江华| 太原市| 桃源县| 明光市| 柘荣县| 郁南县| 翁源县| 招远市| 石楼县| 惠水县| 遵义县| 耒阳市| 盐城市| 吉木乃县| 视频| 谢通门县| 金塔县| 松阳县| 葫芦岛市| 萨迦县| 濉溪县| 古交市| 衡南县| 三江| 丹江口市| 林甸县| 张掖市| 古丈县| 紫云| 阳新县| 乌什县| 商水县| 肃北| 嵊泗县| 新丰县|