ASP.NET Core PNG 图片转 PDF

上一篇 https://www.cnblogs.com/sun8134/p/18094489 用的 DocNET 可以将 JPG 图片转 PDF

但 PNG 图片会变成空白,如果 PNG 图片,就需要用 itext-dotnet :https://github.com/itext/itext-dotnet


继续 Nuget:


Install-Package itext

Install-Package itext.bouncy-castle-adapter

注意:如果不安装 itext.bouncy-castle-adapter,在 new PdfWriter() 的时候可能会报错:

Either com.itextpdf:bouncy-castle-adapter or com.itextpdf:bouncy-castle-fips-adapter dependency must be added in order to use BouncyCastleFactoryCreator


合并 PDF:


        public static bool Png2Pdf(List<string> imageList, string outputPath)
        {
            bool result = false;
            try
            {
                using (FileStream pdfStream = new FileStream(outputPath, FileMode.Create))
                {
                    using (PdfWriter pdfWriter = new PdfWriter(pdfStream))
                    {
                        using (PdfDocument pdfDocument = new PdfDocument(pdfWriter))
                        {
                            using (Document document = new Document(pdfDocument))
                            {
                                foreach (string imagePath in imageList)
                                {
                                    ImageData imageData = ImageDataFactory.Create(imagePath);
                                    iText.Layout.Element.Image img = new iText.Layout.Element.Image(imageData);
                                    PdfPage page = pdfDocument.AddNewPage(new iText.Kernel.Geom.PageSize(img.GetImageWidth(), img.GetImageHeight()));
                                    document.Add(img);
                                }
                            }
                        }
                    }
                }

                result = true;
            }
            catch (Exception e)
            {
                Console.WriteLine($"error:{e}");
            }
            return result;
        }



在控制器种调用:

        public IActionResult Index()
        {
            List<string> imageList = new List<string>();
            for (int pageNumber = 1; pageNumber <= 14; pageNumber++)
            {
                imageList.Add($"F:\\pdf\\images\\Page_{pageNumber}.png");
            }
            bool result = PdfHelper.Png2Pdf(imageList, "F:\\pdf\\compressed.tracemonkey-pldi-14.pdf");
            return Content(result.ToString());
        }


看下对比效果:

左边是jpg右边是png

image

posted @ 2024-03-29 14:49  sun8134  阅读(84)  评论(0编辑  收藏  举报
分享按钮