C#测试调用Ghostscript.NET浏览PDF文件

Ghostscript.NET是针对Ghostscript的C#封装库,支持解析PostScript语言、操作PDF文件等。使用Ghostscript.NET的GhostscriptViewer 模块可以以图片形式查看PDF文档。本文学习并测试调用Ghostscript.NET模块打开及浏览PDF文件的基本用法。
  Ghostscript.NET目前主要支持.net framework,使用VS2022创建基于.net framework 4.8的Winform项目,在Nuget包管理器中搜索并安装Ghostscript.NET包。同时还需在参考文献4中下载相应32位或者64位的依赖包,否则程序运行过程中会报下面截图错误,提示需下载依赖安装包。


  Ghostscript.NET的GitHub官网中提供了GhostscriptViewer的使用案例(参考文献3),主要是配合PictureBox控件使用,调用GhostscriptViewer的Open函数打开PDF文件,然后处理GhostscriptViewer的DisplayPag、DisplaySize、DisplayUpdate事件,更新PictureBox控件的显示图片。同时,调用GhostscriptViewer的ShowFirstPage、ShowLastPage、ShowPreviousPage、ShowNextPage函数切换当前显示图片。
  主要代码包括(从参考文献3的示例中简化而来):

csharp 复制代码
private GhostscriptViewer _viewer;

public Form1()
{
	...
	...
    _viewer = new GhostscriptViewer();
    _viewer.DisplaySize += new GhostscriptViewerViewEventHandler(_viewer_DisplaySize);
    _viewer.DisplayUpdate += new GhostscriptViewerViewEventHandler(_viewer_DisplayUpdate);
    _viewer.DisplayPage += new GhostscriptViewerViewEventHandler(_viewer_DisplayPage);
}
 void _viewer_DisplaySize(object sender, GhostscriptViewerViewEventArgs e)
 {
     pbPage.Image = e.Image;
 }

 void _viewer_DisplayUpdate(object sender, GhostscriptViewerViewEventArgs e)
 {
     pbPage.Invalidate();
     pbPage.Update();
 }

 void _viewer_DisplayPage(object sender, GhostscriptViewerViewEventArgs e)
 {
     pbPage.Invalidate();
     pbPage.Update();
 }
private void btnFirst_Click(object sender, EventArgs e)
{
    _viewer.ShowFirstPage();
}

private void btnLast_Click(object sender, EventArgs e)
{
    _viewer.ShowLastPage();
}

private void btnPre_Click(object sender, EventArgs e)
{
    _viewer.ShowPreviousPage();
}

private void btnNext_Click(object sender, EventArgs e)
{
    _viewer.ShowNextPage();
}

下图为程序运行效果。Ghostscript.NET与PdfiumViewer相比,两者的Nuget包安装及依赖包安装类似,但后者提供有简单的浏览控件,且支持.net core。因此两者相比,PdfiumViewer使用相对更方便。

参考文献:

1\]https://github.com/ArtifexSoftware/Ghostscript.NET \[2\]https://blog.csdn.net/gitblog_00044/article/details/138558845 \[3\]https://github.com/ArtifexSoftware/Ghostscript.NET/blob/master/Ghostscript.NET.Viewer/FMain.cs \[4\]https://ghostscript.com/releases/gsdnld.html

相关推荐
开开心心就好7 小时前
免费卸载工具,可清理残留批量管理启动项
linux·运维·服务器·windows·随机森林·pdf·1024程序员节
mysusheng8 小时前
2025年12月Z-Library电子书下载工具
pdf
vfvfb14 小时前
pdf转图片 每一页转成图片 pdf转jpg
pdf·pdf每一页转成图片
YJlio15 小时前
Python 一键拆分 PDF:按“目录/章节”建文件夹 + 每页单独导出(支持书签识别&正文识别)
开发语言·python·pdf
热河暖男17 小时前
使用 Flying-Saucer-Pdf + velocity 模板引擎生成 PDF(解决中文和图片问题)
java·pdf·html·springboot
maogewang1 天前
清朝条约全集 PDF 电子版(三册合集):从尼布楚到辛丑,历史文献速存
pdf
maogewang1 天前
清朝条约全集 PDF 电子版(三册合集):从尼布楚到辛丑条约的完整史料集
pdf
木泽八1 天前
python实现pdf拆分与合并
服务器·python·pdf
江上清风山间明月2 天前
使用python将markdown文件生成pdf文件
开发语言·python·pdf
这儿有一堆花2 天前
确保 PDF 真实性:数字签名与文档加固技术深度解析
pdf