当前位置:网站首页>利用C#实现Pdf转图片
利用C#实现Pdf转图片
2022-07-03 06:29:00 【zxy2847225301】
这周碰到一个需求,由于公司系统框架的原因,不能直接显示第三方回传回来的pdf(说明一下,第三方回传的pdf是带上了签章信息(即在pdf中加入了签名图片)),需要把pdf转成图片进行显示,但在做的过程中踩了不少雷。最后使用第三方插件PDFRender4NET
1 第三方的插件PdfiumViewer(缺点,丢失签章信息)
首先试了第三方的插件PdfiumViewer,代码很简单,网上也有很多demo,把代码拷贝过来修改一下,三两下就搞定了,试了一下,确实是可以实现pdf传图片,但当我把业务代码写完了,在业务系统上运行时,发现,妈的,大意了,转换完毕的图片丢失了签章信息。下面是我略作修改后的部分代码:
public class PdfToImageHelper
{
/// <summary>
/// pdf转图片(base64格式的字符串)
/// </summary>
/// <param name="pdfBase64String">pdf对应的base64字符串</param>
/// <returns>Pdf如果有多页,就返回多张图片(base64字符串集合)</returns>
public static List<string> GetBase64StringArray(string pdfBase64String)
{
if (pdfBase64String==null|| pdfBase64String.Length==0) return null;
List<string> base64StringList = new List<string>();
byte[] buffer=Convert.FromBase64String(pdfBase64String);
if (buffer == null || buffer.Length == 0) return base64StringList;
MemoryStream ms = new MemoryStream(buffer);
var pdfDocument = PdfiumViewer.PdfDocument.Load(ms);
for (int index = 0; index <pdfDocument.PageCount; index++)
{
Image image = pdfDocument.Render(index, (int)pdfDocument.PageSizes[index].Width, (int)pdfDocument.PageSizes[index].Height, 300, 300, false);
string base64Str=ImageToBase64String(image);
if (base64Str != null && base64Str.Length > 0)
{
base64StringList.Add(base64Str);
}
}
//释放流资源
return base64StringList;
}
/// <summary>
/// Image对象转base64字符串
/// </summary>
/// <param name="Picture"></param>
/// <returns></returns>
private static string ImageToBase64String(Image Picture)
{
MemoryStream ms = new MemoryStream();
if (Picture == null)
return null;
Picture.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] BPicture = new byte[ms.Length];
BPicture = ms.GetBuffer();
//释放流资源
return Convert.ToBase64String(BPicture);
}
}调用:List<string> imageBase64StringList=PdfToImageHelper.GetBase64StringArray("pdf对应的base64字符串");
2 第三方插件Spire.pdf (缺点:收费,有免费版的,但是pdf转换为图片有页数限制(最多3页) ,且转换后的图片很模糊)
使用PdfiumViewer不行后,开始使用Spire.pdf,通过vistual studio的nuget就可以拿到dll,如下图:

第一个Spire.PDF是收费的,转换后的图片左上角会带上如下图的水印信息

第二个FreeSpire.PDF是免费的,但是pdf如果超过3页,只能转前3页,后面的转换的都是空白页
代码就不贴了,网上有很多demo
3 第三方插件PDFRender4NET(O2S.Components.PDFRender4NET.dll,版本信息如下图)

下面贴出我略做修改后的代码:
using O2S.Components.PDFRender4NET;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
namespace iih.gdrmh.ca.PatientSign.bp
{
public class PdfToImageHelper
{
public static List<string> GetBase64StringArrayByPdfPath(string pdfPath)
{
if (pdfPath == null || pdfPath.Length == 0) return null;
List<string> base64StringList = new List<string>();
PDFFile pdfFile = PDFFile.Open(pdfPath);
for (int index =0; index <pdfFile.PageCount; index++)
{
Bitmap pageImage = pdfFile.GetPageImage(index, 56 * 10);
string base64Str = BitmapToBase64String(pageImage);
if (base64Str != null && base64Str.Length > 0)
{
base64StringList.Add(base64Str);
}
}
pdfFile.Dispose();
return base64StringList;
}
private static string ImageToBase64String(Image Picture)
{
MemoryStream ms = new MemoryStream();
if (Picture == null)
return null;
Picture.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] BPicture = new byte[ms.Length];
BPicture = ms.GetBuffer();
return Convert.ToBase64String(BPicture);
}
private static string BitmapToBase64String(Bitmap bitmap)
{
// 1.先将BitMap转成内存流
MemoryStream ms = new MemoryStream();
bitmap.Save(ms, ImageFormat.Png);
ms.Seek(0, SeekOrigin.Begin);
// 2.再将内存流转成byte[]并返回
byte[] bytes = new byte[ms.Length];
ms.Read(bytes, 0, bytes.Length);
ms.Flush();
ms.Close();
ms.Dispose();
return Convert.ToBase64String(bytes);
}
}
}
调用:List<string> imageBase64StringList=PdfToImageHelper.GetBase64StringArrayByPdfPath("pdf对应的文件路径");
最后发现,转换后的图片,签章信息还在,转换后的图片清晰度比FreeSpire.PDF还高
拓展:
去stack overflow搜索发现,pdf转换图片的方案有很多,但推荐最多的是Ghostscript.NET. github地址为:https://github.com/jhabjan/Ghostscript.NET demo代码:https://github.com/jhabjan/Ghostscript.NET/blob/master/Ghostscript.NET.Samples/Samples/RasterizerSample1.cs
stack overflow参考链接:
1 Convert Pdf to Image C# .NET - Stack Overflow
2 Converting pdf to image using c# and Ghostscript - Stack Overflow
3 asp.net - Convert PDF file to images using C# - Stack Overflow
边栏推荐
- Creating postgre enterprise database by ArcGIS
- The mechanical hard disk is connected to the computer through USB and cannot be displayed
- 技术管理进阶——你了解成长的全貌吗?
- Know flex box
- C2338 Cannot format an argument. To make type T formattable provide a formatter<T> specialization:
- Scripy learning
- Create your own deep learning environment with CONDA
- Pdf files can only print out the first page
- Mysql database table export and import with binary
- In depth learning
猜你喜欢

100000 bonus is divided up. Come and meet the "sister who braves the wind and waves" among the winners

Selenium - by changing the window size, the width, height and length of different models will be different

剖析虚幻渲染体系(16)- 图形驱动的秘密
![[5g NR] UE registration process](/img/e3/f881d51fba03010de8c45ea480f3f0.png)
[5g NR] UE registration process
![[open source project recommendation colugomum] this group of undergraduates open source retail industry solutions based on the domestic deep learning framework paddlepadddle](/img/f8/0e3fbfd13bf06291a73200552ff17a.png)
[open source project recommendation colugomum] this group of undergraduates open source retail industry solutions based on the domestic deep learning framework paddlepadddle

Interesting research on mouse pointer interaction

Advanced technology management - do you know the whole picture of growth?

Chapter 8. MapReduce production experience

有意思的鼠标指针交互探究

Cesium 点击获三维坐标(经纬度高程)
随机推荐
致即将毕业大学生的一封信
Fluentd facile à utiliser avec le marché des plug - ins rainbond pour une collecte de journaux plus rapide
SQL implementation merges multiple rows of records into one row
Page text acquisition
The difference between CONDA and pip
Some thoughts on machine learning
剖析虚幻渲染体系(16)- 图形驱动的秘密
远端rostopic的本地rviz调用及显示
Luogu problem list: [mathematics 1] basic mathematics problems
ROS+Pytorch的联合使用示例(语义分割)
Exportation et importation de tables de bibliothèque avec binaires MySQL
ruoyi接口权限校验
Migrate data from Mysql to tidb from a small amount of data
Merge and migrate data from small data volume, sub database and sub table Mysql to tidb
Scroll view specifies the starting position of the scrolling element
爬虫代码基础教学
Cesium entity(entities) 实体删除方法
Shell conditional statement
Naive Bayes in machine learning
Method of converting GPS coordinates to Baidu map coordinates