当前位置:网站首页>利用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
边栏推荐
- Selenium - 改变窗口大小,不同机型呈现的宽高长度会不一样
- [system design] proximity service
- Printer related problem record
- YOLOV3学习笔记
- Creating postgre enterprise database by ArcGIS
- Time format record
- Cesium entity (entities) entity deletion method
- Cesium Click to obtain the longitude and latitude elevation coordinates (3D coordinates) of the model surface
- [set theory] relational closure (relational closure solution | relational graph closure | relational matrix closure | closure operation and relational properties | closure compound operation)
- 2022 CISP-PTE(三)命令执行
猜你喜欢
YOLOV1学习笔记
Numerical method for solving optimal control problem (I) -- gradient method
[system design] proximity service
輕松上手Fluentd,結合 Rainbond 插件市場,日志收集更快捷
使用conda创建自己的深度学习环境
ssh链接远程服务器 及 远程图形化界面的本地显示
Scroll view specifies the starting position of the scrolling element
Support vector machine for machine learning
Install VM tools
Selenium - 改变窗口大小,不同机型呈现的宽高长度会不一样
随机推荐
. Net program configuration file operation (INI, CFG, config)
Use selenium to climb the annual box office of Yien
IC_EDA_ALL虚拟机(丰富版):questasim、vivado、vcs、verdi、dc、pt、spyglass、icc2、synplify、INCISIVE、IC617、MMSIM、工艺库
When PHP uses env to obtain file parameters, it gets strings
Merge and migrate data from small data volume, sub database and sub table Mysql to tidb
The list of "I'm crazy about open source" was released in the first week, with 160 developers on the list
Mysql
Example of joint use of ros+pytoch (semantic segmentation)
Cesium Click to obtain the longitude and latitude elevation coordinates (3D coordinates) of the model surface
Opencv mouse and keyboard events
Project summary --01 (addition, deletion, modification and query of interfaces; use of multithreading)
Mysql database binlog log enable record
Kubesphere - build Nacos cluster
Zhiniu stock project -- 05
Heap sort and priority queue
Paper notes vsalm literature review "a comprehensive survey of visual slam algorithms"
The most classic 100 sentences in the world famous works
认识弹性盒子flex
Exportation et importation de tables de bibliothèque avec binaires MySQL
Various usages of MySQL backup database to create table select and how many days are left