C#将PDF文件转为图片(注意:32位系统不支持)
一:NuGet下载
Install-Package PdfiumViewer -Version 2.13.0
Install-Package ImageResizer.Plugins.PdfiumRenderer.Pdfium.Dll -Version 1.0.1
二:帮助类
class PdfToPicture { /// <summary> /// 将PDF转换为图片 /// </summary> /// <param name="pdfPath">pdf文件位置</param> /// <param name="pageNumber">pdf文件张数</param> /// <param name="size">pdf文件尺寸</param> /// <param name="outputPath">输出图片位置与名称</param> public void RenderPage(string pdfPath, int pageNumber, System.Drawing.Size size, string outputPath, int dpi = 300) { using (var document = PdfiumViewer.PdfDocument.Load(pdfPath)) using (var stream = new FileStream(outputPath, FileMode.Create)) using (var image = GetPageImage(pageNumber, size, document, dpi)) { image.Save(stream, ImageFormat.Jpeg); } } private static Image GetPageImage(int pageNumber, Size size, PdfiumViewer.PdfDocument document, int dpi) { return document.Render(pageNumber - 1, size.Width, size.Height, dpi, dpi, PdfRenderFlags.Annotations); } }
三:调用范例
static void Main(string[] args) { var pdf = PdfDocument.Load(@"E:\BBBBBPDF\sample.pdf"); var pdfpage = pdf.PageCount; var pagesizes = pdf.PageSizes; PdfToPicture p2p = new PdfToPicture(); for (int i = 1; i <= pdfpage; i++) { Size size = new Size(); size.Height = (int)pagesizes[(i - 1)].Height; size.Width = (int)pagesizes[(i - 1)].Width; p2p.RenderPage(@"E:\BBBBBPDF\sample.pdf", i, size, @"E:\BBBBBPDF\sample" + i + @".jpg"); } Console.WriteLine("Success"); Console.Read(); }
PS:1.绝对路径只有IE浏览器可以拿到,所以我们一般拿到文件先转存我们项目文件夹里,然后就可以得到绝对路径进行转图片等操作。
2.能在前端解决最好不要像本篇博客中放在后台处理