C# 使用PdfiumViewer打开PDF

如题,在项目中需要打开一个操作文档。

1.创建WinForm窗体
2.引用 -> 管理NuGet程序包 -> 检索"pdfium" -> 安装以下3个包:

 3.代码
复制代码
using PdfiumViewer;
using Sunny.UI;
using System;
using System.IO;
using System.Windows.Forms;

namespace UpperMaterial.MDIChildForm
{
    public partial class PdfForm : UIForm
    {
        private PdfDocument pdfDocument;


        public PdfForm()
        {
            InitializeComponent();
            this.Load += PdfForm_Load; // 注册窗体加载事件处理程序
        }

        /// <summary>
        /// 窗体加载时自动加载并显示PDF文档。
        /// </summary>
        private void PdfForm_Load(object sender, EventArgs e)
        {
            LoadAndDisplayPdf();
        }

        /// <summary>
        /// 加载指定路径下的PDF文档,并设置到pdfRenderer1控件上。
        /// </summary>
        private void LoadAndDisplayPdf()
        {
            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "operationDocument", "CCD读码程序文档.pdf");

            if (!File.Exists(filePath))
            {
                UIMessageBox.ShowError("PDF文件未找到!");
                return;
            }

            try
            {
                // 如果之前已经加载了一个文档,则先释放资源
                if (pdfDocument != null)
                {
                    pdfDocument.Dispose();
                    pdfDocument = null;
                }

                this.pdfViewer1.Document = PdfDocument.Load(filePath);

            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载PDF文件时出错: {ex.Message}");
            }
        }

        
    }
}
复制代码
4.实现效果

 

posted @   别动我的猫  阅读(245)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2019-01-07 SQL语句实例集合
2019-01-07 MY服务器架设
2019-01-07 163邮箱SMTP设置
点击右上角即可分享
微信分享提示