ASP.NET Core PDF 转图片

可以使用 DocNET: https://github.com/GowenGit/docnet



直接 Nuget:

Install-Package Docnet.Core



然后:

        public static bool Pdf2Image(string inputPath, string outputFolder)
        {
            bool result = false;
            try
            {
                using (var docReader = DocLib.Instance.GetDocReader(inputPath, new PageDimensions(1080, 1920)))
                {
                    //open pdf file
                    int num = docReader.GetPageCount();
                    for (int pageNumber = 0; pageNumber < num; pageNumber++)
                    {
                        using (var pageReader = docReader.GetPageReader(pageNumber))
                        {
                            //var rawBytes = pageReader.GetImage();
                            var rawBytes = pageReader.GetImage(new NaiveTransparencyRemover(255, 255, 255));


                            var width = pageReader.GetPageWidth();
                            var height = pageReader.GetPageHeight();
                            //var characters = pageReader.GetCharacters();

                            //using bitmap to create a png image
                            using (var bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb))
                            {
                                AddBytes(bmp, rawBytes);
                                //DrawRectangles(bmp, characters);
                                using (var stream = new MemoryStream())
                                {
                                    //saving and exporting
                                    bmp.Save(stream, ImageFormat.Png);
                                    System.IO.File.WriteAllBytes(Path.Combine(outputFolder, $"Page_{pageNumber + 1}.png"), stream.ToArray());
                                };
                            };
                        };
                    }
                };

                Console.WriteLine("All pages converted to images.");
                result = true;
            }
            catch (Exception e)
            {
                Console.WriteLine($"error:{e}");
            }

            return result;
        }

        private static void AddBytes(Bitmap bmp, byte[] rawBytes)
        {
            var rect = new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height);

            var bmpData = bmp.LockBits(rect, ImageLockMode.WriteOnly, bmp.PixelFormat);
            var pNative = bmpData.Scan0;

            Marshal.Copy(rawBytes, 0, pNative, rawBytes.Length);
            bmp.UnlockBits(bmpData);
        }



然后上控制器调用下看看效果:

        public IActionResult Index()
        {
            bool result = PdfHelper.Pdf2Image("E:\\pdf\\compressed.tracemonkey-pldi-09.pdf", "E:\\pdf\\images\\");
            return Content(result.ToString());
        }




查看效果:


屏幕截图 2024-03-23 111110

posted @ 2024-03-23 11:13  sun8134  阅读(296)  评论(0编辑  收藏  举报
分享按钮