当前位置: 代码网 > it编程>编程语言>Asp.net > C#实现将批量图片转为PDF文件

C#实现将批量图片转为PDF文件

2024年10月30日 Asp.net 我要评论
功能实现功能实现主要使用 itextsharp 库实现,将指定目录下的有序的一组图片,组合生成指定文件名的pdf文件。范例运行环境操作系统: windows server 2019 datacente

功能实现

功能实现主要使用 itextsharp 库实现,将指定目录下的有序的一组图片,组合生成指定文件名的pdf文件。

范例运行环境

操作系统: windows server 2019 datacenter

.net版本: .netframework4.7.2 或以上

开发工具:vs2019  c#

关键代码

组件库引入

将批量图片转换为pdf

convertjpg2pdf 方法返回 bool 类型,即表示要求生成的目标 pdf 文件是否存在(生成成功),说明如下表:

序号参数名类型说明
1jpgfilepathstring指定存在图片的目录路径,搜索路径下的.jpg或.jpeg文件
2pdfstring生成的pdf文件名称(全路径)

实现代码如下:

public bool convertjpg2pdf(string jpgfilepath, string pdf)
{
            
            var document = new itextsharp.text.document(itextsharp.text.pagesize.a4, 25, 25, 25, 25);
            using (var stream = new filestream(pdf, filemode.create, fileaccess.write, fileshare.none))
            {
 
                itextsharp.text.pdf.pdfwriter.getinstance(document, stream);
                document.open();
                
                string[] allfs = directory.getfiles(jpgfilepath);
                for (int i = 0; i < allfs.length; i++)
                {
                    string jpgfile = allfs[i].tolower();
                    if (jpgfile.indexof(".jpg") == -1 && jpgfile.indexof(".jpeg")==-1){
                        continue;
                    }
                    using (var imagestream = new filestream(jpgfile, filemode.open, fileaccess.read, fileshare.readwrite))
                    {
                        var image = itextsharp.text.image.getinstance(imagestream);
                        if (image.height > itextsharp.text.pagesize.a4.height - 25)
                        {
                            image.scaletofit(itextsharp.text.pagesize.a4.width - 25, itextsharp.text.pagesize.a4.height - 25);
                        }
                        else if (image.width > itextsharp.text.pagesize.a4.width - 25)
                        {
                            image.scaletofit(itextsharp.text.pagesize.a4.width - 25, itextsharp.text.pagesize.a4.height - 25);
                        }
                        image.alignment = itextsharp.text.image.align_middle;
                        document.add(image);
                        imagestream.close();
                    }
                }
                document.close();
                stream.close();
                return file.exists(pdf);
            }
}

总结

输出的pdf文件页面尺寸默认为a4型,margin 边界为25,我们可以改变相应的参数来满足自己的实际需要。

到此这篇关于c#实现将批量图片转为pdf文件的文章就介绍到这了,更多相关c#图片转pdf内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com