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 @ 2025-01-07 16:21  别动我的猫  阅读(1229)  评论(0)    收藏  举报