首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >C# 将批量图片转为PDF文件

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

作者头像
初九之潜龙勿用
发布2024-11-24 08:54:39
发布2024-11-24 08:54:39
38000
代码可运行
举报
文章被收录于专栏:技术文章技术文章
运行总次数:0
代码可运行

功能实现

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

范例运行环境

操作系统: Windows Server 2019 DataCenter

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

开发工具:VS2019 C#

关键代码

组件库引入
将批量图片转换为PDF

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

序号

参数名

类型

说明

1

jpgfilepath

string

指定存在图片的目录路径,搜索路径下的.jpg或.jpeg文件

2

pdf

string

生成的PDF文件名称(全路径)

实现代码如下:

代码语言:javascript
代码运行次数:0
运行
复制
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,我们可以改变相应的参数来满足自己的实际需要。

iTextSharp 库的下载链接可下载我的资源:

https://download.csdn.net/download/michaelline/89934615

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-11-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 功能实现
  • 范例运行环境
  • 关键代码
    • 组件库引入
    • 将批量图片转换为PDF
  • 总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档