功能实现
功能实现主要使用 itextsharp 库实现,将指定目录下的有序的一组图片,组合生成指定文件名的pdf文件。
范例运行环境
操作系统: windows server 2019 datacenter
.net版本: .netframework4.7.2 或以上
开发工具:vs2019 c#
关键代码
组件库引入
将批量图片转换为pdf
convertjpg2pdf 方法返回 bool 类型,即表示要求生成的目标 pdf 文件是否存在(生成成功),说明如下表:
序号 | 参数名 | 类型 | 说明 |
---|---|---|---|
1 | jpgfilepath | string | 指定存在图片的目录路径,搜索路径下的.jpg或.jpeg文件 |
2 | string | 生成的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内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论