最近接到一个任务,需要把用户上传上来的pdf文件转图片,然后对转出来的 图片加水印,最后整个pdf文件拼接成一张长图存储在服务器中。winform和wpf相关的pdf转换类库还是很多的,但我这个项目是基于.netcore写的一个跨平台api。很多pdf转换类库在windows下可以完美运行,但是部署到docker容器中以后就不行了。最后还是找到了一个能够在centos下跑的类库。那么c#中有哪些方式可以把pdf转成图片呢?下面我就把我找的觉得还不错的c# pdf转换类库写个示例方便大家参考。

PdfiumViewer

PdfiumViewer网上资料还是挺多的,但是貌似这个类库在github上以及停止维护了。虽然有.netcore的分支实现,但是真正迁移到centos中运行的时候还是不能正常运行起来,但在windows上性能还是很不错的。

首先我们通过nuget包管理器安装PdfiumViewerPdfiumViewer.Native.x86.v8-xfa
c# nuget安装PdfiumViewer
运行的时候遇到无法加载 DLL“pdfium.dll”: 找不到指定的模块异常时不要慌张,把程序bin目录x86目录里的pdfium.dll复制到bin目录就可以了。
c# 无法加载dll pdfium.dll 找不到指定模块

/// <summary>
    /// 根据传入参数直接转换
    /// </summary>
    /// <param name="pdfFilePath">
    public void Pdf2Images(string pdfFilePath)
        {
            var outImgPath = $"{AppDomain.CurrentDomain.BaseDirectory}\\{DateTime.Now.ToString("yyyyMMdd")}";
            using (var document = PdfDocument.Load(pdfFilePath))
            {
                var pageCount = document.PageCount;
                for (int i = 0; i < pageCount; i++)
                {
                    string outFile = $"{outImgPath}({i + 1}).jpg";
                    var dpi = 300;
                    using (var image = document.Render(i, dpi, dpi, PdfRenderFlags.CorrectFromDpi))
                    {
                        var encoder = ImageCodecInfo.GetImageEncoders()
                            .First(c => c.FormatID == ImageFormat.Jpeg.Guid);
                        var encParams = new EncoderParameters(1);
                        encParams.Param[0] = new EncoderParameter(
                            System.Drawing.Imaging.Encoder.Quality, 10L);

                        image.Save(outFile, encoder, encParams);
                    }
                }
            }
        }

PdfLibCore

上面PdfiumViewer经实测在linux下不能正常运行,所以后面又找了pdflibcore这个类库。这个类库完美支持linux系统下运行,但是性能上要比PdfiumViewer差一些。

c# nuget安装pdflibcore

public  void Pdf2Images(string pdfFilePath)
 {
     //定义图片宽300dpi
     var dpiX = 300D;
     //定义图片高300dpi
     var dpiY = 300D;
     var index = 0;

     var pdfDocument = new PdfDocument(File.Open(pdfFilePath, FileMode.Open));
     foreach (var page in pdfDocument.Pages)
     {
         index++;
         using (var pdfPage = page)
         {
             var pageWidth = (int)(dpiX * pdfPage.Size.Width / 72);
             var pageHeight = (int)(dpiY * pdfPage.Size.Height / 72);

             using (var bitmap = new PdfiumBitmap(pageWidth, pageHeight, true))
             {
                 pdfPage.Render(bitmap, PageOrientations.Normal, RenderingFlags.LcdText);
                 var stream = bitmap.AsBmpStream(dpiX, dpiY);
                 var s1 = System.Drawing.Bitmap.FromStream(stream);
                 s1.Save($"{index}_images.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
             }
         }
     }
 }
最后修改:2022 年 10 月 05 日
如果觉得我的文章对你有用,请随意赞赏