Thursday, May 30, 2024

Merging PDF Files Based on Name Segments in C#

Merging PDF Files Based on Name Segments in C#

In this blog post, we will explore how to merge multiple PDF files using C#. The merging process will be based on a specific segment of each file's filename.

Scenario Overview

Assume you have a folder containing several PDF files named in a format that includes underscore-separated segments. The goal is to combine these PDFs into larger files based on the second segment of their filenames.

Step-by-Step Solution

  1. Setup and Initialization
  2. We start by defining the paths to our input and output folders:

    string folderPath = "C:\\Users\\ersan\\Downloads\\Form10BE_AAPAM3947A_2023_238914720240524_1";
    string outputFolder = "C:\\Users\\ersan\\Downloads\\output2\\";
  3. Sorting Files
  4. We retrieve all files from the input folder and sort them based on their filenames:

    var files = Directory.GetFiles(folderPath);
    Array.Sort(files, (a, b) => string.Compare(Path.GetFileName(a), Path.GetFileName(b)));
  5. Iterating and Merging
  6. We iterate through the sorted list of files, extracting the second segment of each filename. If the segment changes, we merge the current list of files into a single PDF:

    string lastName = "";
    var file2 = outputFolder + Path.GetFileName(files[0]);
    List list = new List();
    
    foreach (var file in files)
    {
        var fileName = Path.GetFileNameWithoutExtension(file);
        var splitName = fileName.Split('_');
        var name = splitName[1];
    
        if (!string.IsNullOrEmpty(lastName) && lastName.ToLower() != name.ToLower())
        {
            CombineMultiplePDFs(list.ToArray(), file2);
            file2 = outputFolder + Path.GetFileName(file);
            list = new List();
        }
    
        list.Add(file);
        lastName = name;
    }
  7. PDF Merging Method
  8. The CombineMultiplePDFs method takes an array of filenames and merges them into a single PDF:

    public static void CombineMultiplePDFs(string[] fileNames, string outFile)
    {
        if (File.Exists(outFile))
            throw new Exception("File already exists.");
    
        Document document = new Document();
        using (FileStream newFileStream = new FileStream(outFile, FileMode.Create))
        {
            PdfCopy writer = new PdfCopy(document, newFileStream);
            document.Open();
    
            foreach (string fileName in fileNames)
            {
                PdfReader reader = new PdfReader(fileName);
                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    PdfImportedPage page = writer.GetImportedPage(reader, i);
                    writer.AddPage(page);
                }
                reader.Close();
            }
    
            writer.Close();
            document.Close();
        }
    }
    
  9. Conclusion
  10. After processing all files, the merged PDFs are saved in the output folder. A success message is printed in the console upon completion.

Complete Code

using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;

namespace PDFMerger
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string folderPath = "C:\\Users\\ersan\\Downloads\\Form10BE_AAPAM3947A_2023_238914720240524_1";
            string outputFolder = "C:\\Users\\ersan\\Downloads\\output2\\";
            var files = Directory.GetFiles(folderPath);
            Array.Sort(files, (a, b) => string.Compare(Path.GetFileName(a), Path.GetFileName(b)));

            string lastName = "";
            // Create a new PDF document with a 50-point margin

            var file2 = outputFolder + Path.GetFileName(files[0]);

            List list = new List();

            foreach (var file in files)
            {
                var fileName = Path.GetFileNameWithoutExtension(file);
                var splitName = fileName.Split('_');
                var name = splitName[1];
                if (!string.IsNullOrEmpty(lastName) && lastName.ToLower() != name.ToLower())
                {
                    CombineMultiplePDFs(list.ToArray(), file2);
                    file2 = outputFolder + Path.GetFileName(file);
                    list = new List();
                }
                list.Add(file);
                lastName = name;
            }

            // Print the success message
            Console.WriteLine("PDF files merged successfully!");
        }

        public static void CombineMultiplePDFs(string[] fileNames, string outFile)
        {
            if (File.Exists(outFile))
                throw new Exception("122");
            // step 1: creation of a document-object
            Document document = new Document();
            //create newFileStream object which will be disposed at the end
            using (FileStream newFileStream = new FileStream(outFile, FileMode.Create))
            {
                // step 2: we create a writer that listens to the document
                PdfCopy writer = new PdfCopy(document, newFileStream);

                // step 3: we open the document
                document.Open();

                foreach (string fileName in fileNames)
                {
                    // we create a reader for a certain document
                    PdfReader reader = new PdfReader(fileName);
                    reader.ConsolidateNamedDestinations();

                    // step 4: we add content
                    for (int i = 1; i <= reader.NumberOfPages; i++)
                    {
                        PdfImportedPage page = writer.GetImportedPage(reader, i);
                        writer.AddPage(page);
                    }

                    reader.Close();
                }
                writer.Close();
                document.Close();
        }

    }

}
      
Final Thoughts

This solution provides a straightforward approach to programmatically merge PDF files based on a specific naming convention using C#. By leveraging libraries like iTextSharp (via PdfCopy), you can efficiently handle and consolidate PDF documents based on your application's requirements.

This approach can be extended or customized further to meet additional criteria or integrate with other functionalities as needed.

For more details, you can refer to the complete code and explanation above.

Automating Email with VBA in Excel Macro

Automating Email with VBA

In this blog post, I will walk you through a VBA script that automates the process of sending emails using Outlook. Below is the script and an explanation of how it works:

                
Sub SendEmail()
    Dim OutApp As Object
    Dim OutMail As Object
    Dim ws As Worksheet
    Dim rng As Range
    Dim toEmail() As String
    Dim ccEmail() As String
    Dim subject As String
    Dim body As String
    Dim filePath As String
    Dim i As Long
    
    Set OutApp = CreateObject("Outlook.Application")
    Set ws = ThisWorkbook.Sheets("Sheet1")
    
    For Each rng In ws.Range("A2:A" & ws.Cells(ws.Rows.Count, "A").End(xlUp).Row)
        toEmail = Split(rng.Value, ";")
        ccEmail = Split(rng.Offset(0, 1).Value, ";")
        subject = rng.Offset(0, 2).Value
        body = rng.Offset(0, 3).Value
        filePath = rng.Offset(0, 4).Value
        
        Set OutMail = OutApp.CreateItem(0)
        With OutMail
            ' Add To recipients
            For i = LBound(toEmail) To UBound(toEmail)
                .Recipients.Add toEmail(i)
            Next i
            
            ' Add CC recipients
            For i = LBound(ccEmail) To UBound(ccEmail)
                .Recipients.Add ccEmail(i)
            Next i
            
            .subject = subject
            .body = body
              
            ' Attach file if path is provided
            If filePath <> "" Then
                .Attachments.Add filePath
            End If
                  
            .Send
        End With
        
        Set OutMail = Nothing
    Next rng
    
    Set OutApp = Nothing
End Sub

                
            

Explanation:

  • OutApp and OutMail: These objects are used to interface with Outlook.
  • ws: Refers to the worksheet containing the email data.
  • rng: Loops through each row of data to extract email details.
  • toEmail, ccEmail, subject, body, filePath: Variables to store email details from the worksheet.
  • The script sets the necessary fields for each email and sends it using Outlook.

Wednesday, May 1, 2024

Exploring My Passions: Music, Movies, Family, and More

Exploring My Passions: Music, Movies, Family, and More

Hello! I’m excited to share a bit about myself and the things I’m passionate about. From music to movies, and spending quality time with family and friends, here’s a glimpse into my world.

The Soundtrack of My Life: Indian Melody Songs

Music has always been a significant part of my life. I have a deep appreciation for Indian melody songs. The rich and diverse musical heritage of India offers a plethora of melodious tunes that can uplift the spirit and soothe the soul. Whether it’s classical, folk, or contemporary, Indian music has a unique way of connecting with the heart.

A Cinematic Favorite: 3 Idiots

When it comes to movies, "3 Idiots" stands out as my all-time favorite. This film is not just entertaining but also thought-provoking, offering valuable life lessons wrapped in humor and emotion. The story of friendship, the importance of pursuing one’s passion, and the critique of the traditional education system resonate deeply with me. It's a film that I can watch over and over again.

Family Life in Delhi NCR

I live in Delhi NCR with my family, and spending time with them is something I cherish immensely. The bustling city life, combined with the comfort of family, makes every moment special. Whether it’s enjoying a meal together, going for a walk, or just having a heartfelt conversation, these moments are priceless.

The Joy of Traveling

Traveling is another passion of mine. Exploring new places, experiencing different cultures, and meeting new people bring a sense of adventure and joy. Whether it’s a weekend getaway or a long vacation, traveling helps me unwind and gain a fresh perspective on life.

Friends: The Chosen Family

Apart from my family, I also love spending time with my friends. They are my chosen family, and our time together is filled with laughter, support, and countless memories. Whether we’re hanging out at our favorite spots in Delhi NCR or planning trips together, the bond we share is invaluable.

A Passion for Table Tennis

I am a big fan of table tennis and love watching the game. The speed, skill, and strategy involved make it incredibly exciting. Whether it’s watching international tournaments or local matches, table tennis never fails to captivate me. It’s not just about the competition but also the sportsmanship and the sheer joy of the game.

Conclusion

In conclusion, my life is enriched by a mix of music, movies, travel, and cherished moments with family and friends. Each of these passions adds a unique flavor to my life, making it vibrant and fulfilling. Thank you for taking the time to read about my interests. I hope this post gives you a glimpse into the things that make my life special.

Featured Post

Construction Result Summary Jun-2019