In this Article we will see about how to merge two pdf file in
asp.net using ItextSharp. Here I have given demo to merge pdf file in web
application.
Default.aspx:-
<div> <asp:FileUploadrunat="server"ID="file1"/> <asp:FileUploadrunat="server"ID="file2"/> <br/> <asp:Button runat="server" ID="btnMerge" Text="Merge PDF" OnClick="btnMerge_Click"/> </div>
Default.aspx.cs:-
protected void btnMerge_Click(object sender, EventArgs e) { if (file1.HasFile && file2.HasFile) { PdfReader pdfReader1 = newPdfReader(file1.PostedFile.InputStream); PdfReader pdfReader2 = newPdfReader(file2.PostedFile.InputStream); List<PdfReader>readerList = newList<PdfReader>(); readerList.Add(pdfReader1); readerList.Add(pdfReader2); //Define a new output document and its size, type Documentdocument = newDocument(PageSize.A4, 0, 0, 0, 0); //Get instance response output stream to write output file. PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream); document.Open(); foreach (PdfReader reader inreaderList) { for (int i = 1; i <= reader.NumberOfPages; i++) { PdfImportedPage page = writer.GetImportedPage(reader, i); document.Add(iTextSharp.text.Image.GetInstance(page)); } } document.Close(); Response.AppendHeader("content-disposition", "inline; filename=OutPut.pdf"); Response.ContentType = "application/pdf"; } }
private void MergePDFs(stringoutPutFilePath, paramsstring[] filesPath) { List<PdfReader>readerList = newList<PdfReader>(); foreach (stringfilePathinfilesPath) { PdfReaderpdfReader = newPdfReader(filePath); readerList.Add(pdfReader); } //Define a new output document and its size, type Documentdocument = newDocument(PageSize.A4, 0, 0, 0, 0); //Create blank output pdf file and get the stream to write on it. PdfWriter writer = PdfWriter.GetInstance(document, newFileStream(outPutFilePath, FileMode.Create)); document.Open(); foreach (PdfReader reader inreaderList) { for (int i = 1; i <= reader.NumberOfPages; i++) { PdfImportedPage page = writer.GetImportedPage(reader, i); document.Add(iTextSharp.text.Image.GetInstance(page)); } } document.Close(); }
Thanks for comments.....