ASP.NET Core 图片转 PDF

前几天用 DocNET PDF转图片,现在再用 DocNET 把图片合并回PDF…


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


Nuget:

Install-Package Docnet.Core


合并比拆分简单:

复制代码
        public static bool Images2Pdf(List<string> imageList, string outputPath)
        {
            bool result = false;
            try
            {
                using (var converter = DocLib.Instance)
                {
                    JpegImage[] files = new JpegImage[imageList.Count];
                    for (int i = 0; i < imageList.Count; i++)
                    {
                        using (Image image = Image.FromFile(imageList[i]))
                        {
                            files[i] = new JpegImage
                            {
                                Bytes = File.ReadAllBytes(imageList[i]),
                                Width = image.Width,
                                Height = image.Height
                            };
                        }
                    }
                    var bytes = converter.JpegToPdf(files);
                    File.WriteAllBytes(outputPath, bytes);
                }
                result = true;
            }
            catch (Exception e)
            {
                Console.WriteLine($"error:{e}");
            }
            return result;
        }
复制代码


在控制器里调用合并成新的 PDF 文件(注意:DocNET 只支持将 JPG 图片合并为 PDF ,如果图片是 PNG 格式,生成的 PDF图片会是空白,对于 PNG 图片合并成 PDF,请使用其他的包,比如 iText 7 )

复制代码
        public IActionResult Index()
        {
            List<string> imageList = new List<string>();
            for (int pageNumber = 1; pageNumber <= 14; pageNumber++)
            {
                imageList.Add($"F:\\pdf\\images\\Page_{pageNumber}.jpg");
            }
            bool result = PdfHelper.Images2Pdf(imageList, "F:\\pdf\\compressed.tracemonkey-pldi-13.pdf");
            return Content(result.ToString());
        }
复制代码
posted @   sun8134  阅读(89)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
分享按钮
点击右上角即可分享
微信分享提示