Merge Multiple Word Files Into Single PDF

In this text, I'm able to display a way to merge more than one word files into one pdf with the use of ITextSharp.

What is Itextsharp library?

Itextsharp is a high level device library that is a free and open source that is utilized for making complex pdf reports and that assists to change over-page results or HTML content in a PDF document.

Thus, we should begin with a guide to a consolidated pdf, yet before that, you really want to download Itextsharp.dll document and include your project

You can do so by right-clicking the project node and select Add > Project Reference.

You can download Itextsharp.dll from the web

In the end, I will provide you the zip source code

cs code 

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text.pdf;
using System.IO;
using iTextSharp.text;

public partial class MergeWordFile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnmergrword_Click(object sender, EventArgs e)
    {
        try
        {
            String FILENAME1 = FileUpload1.FileName;
            String FILENAME2 = FileUpload2.FileName;
            if (FILENAME1.Length > 0 || FILENAME2.Length > 0)
            {
                string EXt = Path.GetExtension(FileUpload1.PostedFile.FileName);
                string EXt2 = Path.GetExtension(FileUpload2.PostedFile.FileName);
                if (EXt == ".docx")
                {
                    String PATH = Server.MapPath("~/uploads/Merge/"+FILENAME1);// Server.MapPath("~/uploads/Merge/word1.docx");
                    FileUpload1.SaveAs(PATH);
                }
                if (EXt2 == ".docx")
                {
                    String PATH = Server.MapPath("~/uploads/Merge/"+FILENAME2);
                    FileUpload2.SaveAs(PATH);
                }
                SetMergeWordFile(FILENAME1, FILENAME2);
            }
            else
            {
                Label1.Text = "";
            }
        }
        catch (Exception ex)
        {
        }
    }

    private void SetMergeWordFile(string FILENAME1, string FILENAME2)
    {

        String path = Server.MapPath("~/uploads/Merge/");
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        List<string> uploadedFiles = new List<string>();

        uploadedFiles.Add(Path.Combine(path, FILENAME1));
        uploadedFiles.Add(Path.Combine(path, FILENAME2));

        Random rnd = new Random();
        int num = rnd.Next(200);
        string newFilePath = Path.Combine(path, ("Merge" +num.ToString()+ DateTime.Now.ToString("MM-dd-yyyy") + ".docx").Replace("-",""));
        // Create blank document.
        using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(newFilePath, WordprocessingDocumentType.Document))
        {
            MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
            mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
            Body body = mainPart.Document.AppendChild(new Body());
            DocumentFormat.OpenXml.Wordprocessing.Paragraph para = body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph());
        }

        for (int i = 0; i < uploadedFiles.Count; i++)
        {
            using (WordprocessingDocument wpd = WordprocessingDocument.Open(newFilePath, true))
            {
                MainDocumentPart mdp = wpd.MainDocumentPart;
                AltChunk altChunk = new AltChunk();
                string altChunkId = "AltChunkId" + i;
                AlternativeFormatImportPart chunk = mdp.AddAlternativeFormatImportPart(
                    AlternativeFormatImportPartType.WordprocessingML, altChunkId);
                using (FileStream fileStream = System.IO.File.Open(uploadedFiles[i], FileMode.Open))
                {

                    chunk.FeedData(fileStream);                   
                    altChunk.Id = altChunkId;
                    mdp.Document.Body.InsertAfter(altChunk, mdp.Document.Body.Elements<DocumentFormat.OpenXml.Wordprocessing.Paragraph>().Last());
                    //  mdp.Document.Body.InsertAfter(altChunk, mdp.Document.Body.Elements<Paragraph>().Last());
                    mdp.Document.Save();
                    wpd.Close();
                }
               
            }          
        }

    }

    public static void MergeDocuments(params string[] filepaths)
    {
        //  K:\\abhishek\\Learninig\New folder
        //filepaths = new[] { "D:\\one.docx", "D:\\two.docx", "D:\\three.docx", "D:\\four.docx", "D:\\five.docx" };
        if (filepaths != null && filepaths.Length > 1)

            using (WordprocessingDocument myDoc = WordprocessingDocument.Open(@filepaths[0], true))
            {
                MainDocumentPart mainPart = myDoc.MainDocumentPart;

                for (int i = 1; i < filepaths.Length; i++)
                {
                    string altChunkId = "AltChunkId" + i;
                    AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(
                        AlternativeFormatImportPartType.WordprocessingML, altChunkId);
                    using (FileStream fileStream = File.Open(@filepaths[i], FileMode.Open))
                    {
                        chunk.FeedData(fileStream);
                    }
                    DocumentFormat.OpenXml.Wordprocessing.AltChunk altChunk = new DocumentFormat.OpenXml.Wordprocessing.AltChunk();
                    altChunk.Id = altChunkId;
                    //new page, if you like it...
                    mainPart.Document.Body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new Run(new Break() { Type = BreakValues.Page })));
                    //next document
                    mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements<DocumentFormat.OpenXml.Wordprocessing.Paragraph>().Last());
                }
                mainPart.Document.Save();
                myDoc.Close();
            }
    }

    #region PDF
    // pdf merge


    protected void btnpdf_Click(object sender, EventArgs e)
    {
        Merging();
    }
    protected void Merging()
    {
        List<PdfReader> pdfReaderList = new List<PdfReader>();
        foreach (string filePath in Directory.GetFiles(Server.MapPath("~/uploads/pdfmerge/")))
        {
            PdfReader pdfReader = new PdfReader(filePath);
            pdfReaderList.Add(pdfReader);
        }
        Response.ClearContent();
        Response.ClearHeaders();
        Response.Buffer = true;
        iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);
        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Server.MapPath("~/uploads/pdfmerge/") + "OutPut.pdf", FileMode.Create));
        document.Open();
        foreach (PdfReader reader in pdfReaderList)
        {
            for (int i = 1; i <= reader.NumberOfPages; i++)
            {
                PdfImportedPage page = writer.GetImportedPage(reader, i);
                document.Add(iTextSharp.text.Image.GetInstance(page));
            }
        }
        document.Close();
        Byte[] FileBuffer = File.ReadAllBytes(Server.MapPath("~/uploads/pdfmerge/") + "OutPut.pdf");
        if (FileBuffer != null)
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-length", FileBuffer.Length.ToString());
            Response.BinaryWrite(FileBuffer);
        }
    }
    #endregion
}

Front page (aspx)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MergeWordFile.aspx.cs" Inherits="MergeWordFile" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:FileUpload ID="FileUpload1" runat="server" />
        </div>
        <div>
            <asp:FileUpload ID="FileUpload2" runat="server" />
        </div>
        <div>
            <asp:Button ID="btnmergrword" runat="server" Text="Merge Word Document" OnClick="btnmergrword_Click" />
        </div>
        <br/>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        
          <div>
            <asp:FileUpload ID="FileUpload3" runat="server" />
        </div>
        <div>
            <asp:FileUpload ID="FileUpload4" runat="server" />
        </div>
        <div>
            <asp:Button ID="btnpdf" runat="server" Text="Merge Pdf Document" OnClick="btnpdf_Click" />
        </div>
    </form>

</body>
</html>

Summary

This article provides an explanation about how to merge multiple word files into one pdf by using Itextsharp in c# and sharing is caring hope you like it.


Similar Articles