如何合并列表框中的多个pdf文件

时间:2019-04-05 17:44:49

标签: c# pdf merge itext windows-forms-designer

我有一个程序,该程序从两个路径中选择并将这些pdf文件合并到合并文件夹中的C:位置。我想改为合并列表框中的多个pdf文件。我将按钮更改为仅一个路径,因此我将多个文件添加到列表框中。我正在尝试找出如何使程序从列表框中读取而不是从文本框中读取的方法,以及合并多个pdf而不是两个pdf。

我将第二行移至要求第二个文件的位置,并创建了一个列表框,该列表框从选择文件按钮添加后将显示多个文件。

namespace mergePdf
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        protected void btnMerge_Click(object sender, EventArgs e)
        {


            if (!Directory.Exists(@"C:\Merge Folder\"))
                Directory.CreateDirectory(@"C:\Merge Folder\");
            string pdfFile1 = Path.GetFullPath(textBoxPdfFile1Path.Text);


            string[] filenames = { pdfFile1 };
            string outputFileName = "Merge.pdf";
            string outputPath = @"C:\Merge Folder\" + outputFileName;
            Document doc = new Document();
            PdfCopy writer = new PdfCopy(doc, new FileStream(outputPath, 
            FileMode.Create));
            if (writer == null)
            {
                return;
            }
            doc.Open();
            foreach (string filename in filenames)
            {
                PdfReader reader = new PdfReader(filename);
                reader.ConsolidateNamedDestinations();
                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    PdfImportedPage page = writer.GetImportedPage(reader, 
                    i);
                    writer.AddPage(page);
                }

                reader.Close();
            }

            writer.Close();
            doc.Close();
            System.Diagnostics.Process.Start(outputPath);
        }



        private void Form1_Load(object sender, EventArgs e)
        {
            textBoxPdfFile1Path.Text = 
            System.IO.Path.Combine(Application.StartupPath, 
            @"C:\Users\jesse\Downloads");


        }

        protected void btnSelectFile1_Click(object sender, EventArgs e)
        {

            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*";
            ofd.Multiselect = true;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                textBoxPdfFile1Path.Text = ofd.FileName;
                string[] files = ofd.FileNames;
                listBox1.Items.AddRange(files);
            }
        }


    }
}

0 个答案:

没有答案