C#将PDF文件转为图片

一:NuGet下载

Install-Package PdfiumViewer -Version 2.13.0

Install-Package ImageResizer.Plugins.PdfiumRenderer.Pdfium.Dll -Version 1.0.1

二:帮助类

 class PdfToPicture
    {
        /// 
        /// 将PDF转换为图片
        /// 
        /// pdf文件位置
        /// pdf文件张数
        /// pdf文件尺寸
        /// 输出图片位置与名称
        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:绝对路径只有IE浏览器可以拿到,所以我们一般拿到文件先转存我们项目文件夹里,然后就可以得到绝对路径进行转图片等操作

 

转载于:https://www.cnblogs.com/HansZimmer/p/10964156.html

你可能感兴趣的:(C#将PDF文件转为图片)