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 @ 2024-03-25 15:35  sun8134  阅读(38)  评论(0编辑  收藏  举报
分享按钮