【图片批量转换合并PDF】多个文件夹的图片以文件夹为单位批量合并成一个PDF,基于wpf的实现方案

项目背景:

多个图片分布在不同文件夹,如何以文件夹为单位批量合并成一个PDF,还要保证文件夹里面图片大小和顺序

实现功能:

1、单张图片的转换PDF:一张图临时转一下
2、多张图片转换成PDF:多张图单独转成PDF
3、多级目录多张图转换成PDF:多级目录多张图单独转成多个PDF
4、多张图合并成PDF:多张图合并成一个PDF
5、多级目录多张图合并成PDF:多级目录多张图合并成一个PDF
6、以上1-5种PDF转换后,保存在原目录,还可以支持保存在其他目录,并且保留目录结构

实现思路

  1. 界面设计:创建一个 WPF 窗口,包含选择文件夹的按钮、开始合并的按钮以及显示操作进度的文本框。
  2. 文件夹选择:使用 System.Windows.Forms.FolderBrowserDialog 让用户选择包含多个图片文件夹的根文件夹。
  3. 图片收集:遍历根文件夹下的每个子文件夹,收集其中的图片文件。
  4. PDF 合并:使用 iTextSharp 库将每个子文件夹中的图片合并成一个 PDF 文件。
  5. 进度显示:在操作过程中,将进度信息显示在文本框中。

代码实现

1. 创建 WPF 项目

首先,创建一个新的 WPF 应用程序项目。

2. 设计界面(MainWindow.xaml

<Window x:Class="ImageToPdfMerger.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="图片批量合并成 PDF" Height="450" Width="800">
    <Grid>
        <Button Content="选择文件夹" HorizontalAlignment="Left" Margin="20,20,0,0" VerticalAlignment="Top" Width="100" Click="SelectFolderButton_Click"/>
        <Button Content="开始合并" HorizontalAlignment="Left" Margin="140,20,0,0" VerticalAlignment="Top" Width="100" Click="MergeButton_Click" IsEnabled="False"/>
        <TextBox x:Name="LogTextBox" HorizontalAlignment="Left" Height="380" Margin="20,60,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="740" IsReadOnly="True"/>
    </Grid>
</Window>

3. 实现逻辑(MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace ImageToPdfMerger
{
    public partial class MainWindow : Window
    {
        private string selectedFolder;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void SelectFolderButton_Click(object sender, RoutedEventArgs e)
        {
            using (FolderBrowserDialog dialog = new FolderBrowserDialog())
            {
                DialogResult result = dialog.ShowDialog();
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    selectedFolder = dialog.SelectedPath;
                    LogTextBox.Text += $"已选择文件夹: {selectedFolder}\n";
                    MergeButton.IsEnabled = true;
                }
            }
        }

        private void MergeButton_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(selectedFolder))
            {
                MessageBox.Show("请先选择文件夹。");
                return;
            }

            try
            {
                // 获取所有子文件夹
                string[] subFolders = Directory.GetDirectories(selectedFolder);
                foreach (string subFolder in subFolders)
                {
                    string folderName = new DirectoryInfo(subFolder).Name;
                    LogTextBox.Text += $"正在处理文件夹: {folderName}\n";

                    // 获取文件夹中的所有图片文件
                    string[] imageFiles = Directory.GetFiles(subFolder, "*.jpg", SearchOption.TopDirectoryOnly)
                                                   .Concat(Directory.GetFiles(subFolder, "*.png", SearchOption.TopDirectoryOnly))
                                                   .ToArray();

                    if (imageFiles.Length > 0)
                    {
                        // 生成 PDF 文件路径
                        string pdfFilePath = Path.Combine(selectedFolder, $"{folderName}.pdf");

                        // 创建 PDF 文档
                        using (Document document = new Document())
                        {
                            using (PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(pdfFilePath, FileMode.Create)))
                            {
                                document.Open();

                                // 遍历图片文件并添加到 PDF 中
                                foreach (string imageFile in imageFiles)
                                {
                                    try
                                    {
                                        iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageFile);
                                        // 调整图片大小以适应页面
                                        image.ScaleToFit(document.PageSize.Width - document.LeftMargin - document.RightMargin,
                                                         document.PageSize.Height - document.TopMargin - document.BottomMargin);
                                        document.Add(image);
                                        document.NewPage();
                                    }
                                    catch (Exception ex)
                                    {
                                        LogTextBox.Text += $"处理图片 {imageFile} 时出错: {ex.Message}\n";
                                    }
                                }

                                document.Close();
                            }
                        }

                        LogTextBox.Text += $"已生成 PDF 文件: {pdfFilePath}\n";
                    }
                    else
                    {
                        LogTextBox.Text += $"文件夹 {folderName} 中没有图片文件。\n";
                    }
                }

                MessageBox.Show("合并完成。");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"合并过程中出现错误: {ex.Message}");
            }
        }
    }
}

4. 安装 iTextSharp 库

在 Visual Studio 中,右键单击项目,选择 “管理 NuGet 包”,搜索 iTextSharp 并安装。

运行程序

运行程序后,点击 “选择文件夹” 按钮选择包含多个图片文件夹的根文件夹,然后点击 “开始合并” 按钮,程序将自动将每个子文件夹中的图片合并成一个 PDF 文件,并将进度信息显示在文本框中。

注意事项

  • 确保所选文件夹下的子文件夹中只包含图片文件(.jpg 或 .png),否则可能会出现错误。
  • iTextSharp 库在处理大尺寸图片时可能会占用较多内存,建议处理的图片不要过大。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值