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使用相对更方便。

参考文献:

1https://github.com/ArtifexSoftware/Ghostscript.NET

2https://blog.csdn.net/gitblog_00044/article/details/138558845

3https://github.com/ArtifexSoftware/Ghostscript.NET/blob/master/Ghostscript.NET.Viewer/FMain.cs

4https://ghostscript.com/releases/gsdnld.html

相关推荐
ComPDFKit7 小时前
用 ComPDF DocSlight 提取 PDF 表格:三种样本实测与 Python 接入
开发语言·python·pdf·pdf表格提取
yiyideda10 小时前
保单OCR工程实践:PDF/扫描件/纸质拍照三种输入下的字段结构化方案
计算机视觉·pdf·ocr·车险保单识别·保单ocr识别
Lhan.zzZ10 小时前
Qt/QML:业务记录单展示、签名确认与 PDF 导出开发
c++·qt·pdf
万祥Python1 天前
2026年6月英语六级真题及答案解析(第一、二、三套全PDF)
pdf
Latchh1 天前
PDF打开不要密码却显示已加密,前端怎么判断
前端·图像处理·人工智能·计算机视觉·pdf
原子延迟1 天前
PDF权限密码和打开密码差在哪?我拿7份文件试了
图像处理·人工智能·计算机视觉·pdf
zxanz11 天前
Gotenberg PDF 转换服务曝出高危 RCE 安全漏洞
pdf
dotnet全栈开发2 天前
火爆全网的《高性价比人生指南》,613条建议最新完整版PDF来了!
pdf
零基础1232 天前
PDF 处理工具全攻略:pdf24、PDFgear、Adobe Acrobat DC 与 Stirling-PDF 深度对比
java·开发语言·pdf
南风微微吹2 天前
考研数学一、二、三历年真题及答案解析PDF(1987-2026年)
考研·pdf