PDF слияние с четким - PullRequest
       34

PDF слияние с четким

1 голос
/ 03 апреля 2019

Я пытаюсь создать настольное приложение, объединяющее существующие файлы PDF в один.

Я нашел некоторый код, который помогает мне с моим дизайном, выбирая файлы и объединяя их, но мой код создает PDF-файлы, а затем отправляет новый файл на рабочий стол. Мне нужен мой код, чтобы собрать существующие файлы PDF и объединить их вместе, чтобы создать файл с этими файлами вместе и отправить его на мой рабочий стол. Прилагается мой код, пожалуйста, дайте мне знать, что мне нужно исправить. Я очень новичок в C #, я понимаю основы, но я не уверен, где что-то изменить и как в этой определенной области.

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

        private void btnMerge_Click(object sender, EventArgs e)
        {
            //Folder that we'll work from
            string workingFolder = 
            Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string pdf1 = Path.Combine(workingFolder, "pdf1.pdf");//PDF 
            with solid red background color
            string pdf2 = Path.Combine(workingFolder, "pdf2.pdf");//PDF 
            with text
            string pdf3 = Path.Combine(workingFolder, "pdf3.pdf"); 
            //Merged PDF

            //Create a basic PDF filled with red, nothing special
            using (FileStream fs = new FileStream(pdf1, FileMode.Create, 
            FileAccess.Write, FileShare.None))
            {
                using (Document doc = new Document(PageSize.LETTER))
                {
                    using (PdfWriter writer = PdfWriter.GetInstance(doc, 
                    fs))
                    {
                        doc.Open();
                        PdfContentByte cb = writer.DirectContent;
                        cb.SetColorFill(BaseColor.RED);
                        cb.Rectangle(0, 0, doc.PageSize.Width, 
                        doc.PageSize.Height);
                        cb.Fill();
                        doc.Close();
                    }
                }
            }

            //Create a basic PDF with a single line of text, nothing 
            special
            using (FileStream fs = new FileStream(pdf2, FileMode.Create, 
            FileAccess.Write, FileShare.None))
            {
                using (Document doc = new Document(PageSize.LETTER))
                {
                    using (PdfWriter writer = PdfWriter.GetInstance(doc, 
                    fs))
                    {
                        doc.Open();
                        doc.Add(new Paragraph("This is a test"));
                        doc.Close();
                    }
                }
            }

            //Create a basic PDF
            using (FileStream fs = new FileStream(pdf3, FileMode.Create, 
            FileAccess.Write, FileShare.None))
            {
                using (Document doc = new Document(PageSize.LETTER))
                {
                    using (PdfWriter writer = PdfWriter.GetInstance(doc, 
                    fs))
                    {
                        doc.Open();

                        //Get page 1 of the first file
                        PdfImportedPage imp1 = writer.GetImportedPage(new 
                        PdfReader(pdf1), 1);
                        //Get page 2 of the second file
                        PdfImportedPage imp2 = writer.GetImportedPage(new 
                        PdfReader(pdf2), 1);
                        //Add the first file to coordinates 0,0
                        writer.DirectContent.AddTemplate(imp1, 0, 0);
                        //Since we don't call NewPage the next call will 
                        operate on the same page
                        writer.DirectContent.AddTemplate(imp2, 0, 0);
                        doc.Close();

                    }
                }
            }

            this.Close();
        }

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

        }

        private void btnSelectFile1_Click(object sender, EventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();
            fd.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*";
            if (fd.ShowDialog() == DialogResult.OK)
            {
                textBoxPdfFile1Path.Text = fd.FileName;
            }
        }

        private void btnSelectFile2_Click(object sender, EventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();
            fd.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*";
            if (fd.ShowDialog() == DialogResult.OK)
            {
                textBoxPdfFile2Path.Text = fd.FileName;
            }
        }
    }
}

Я ожидаю, что вывод объединит существующие файлы в один файл, который будет отправлен на мой рабочий стол. Сейчас он создает два файла-примера PDF и объединяет их, но я не знаю, как выбрать из существующих.

1 Ответ

0 голосов
/ 03 апреля 2019

Использование приведенного ниже кода должно делать то, что вы хотите, насколько слияние документов. Чтобы получить список фактических путей к отдельным PDF-файлам, зависит от вас, как это сделать. После закрытия FileStream ваш документ должен быть создан по указанному пути 'newPdfPath'.

using (FileStream stream = new FileStream(newPdfPath, FileMode.Create))
                {
                    Document document = new Document();
                    PdfCopy pdf = new PdfCopy(document, stream);
                    PdfReader reader = null;
                    document.Open();
                    foreach (var item in listOfPathsToPDFs)
                    {                       
                        reader = new PdfReader(item);
                        pdf.AddDocument(reader);
                        reader.Close();                        
                    }
                    document.Close();
                }
...