Hi rani,
Check this example. Now please take its reference and correct your code.
Install itextSharp from nuget.
Namespaces
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using iTextSharp.text.pdf;
using iTextSharp.text;
Controller
public class HomeController : Controller
{
private IHostingEnvironment Environment;
public HomeController(IHostingEnvironment _environment)
{
Environment = _environment;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(List<IFormFile> postedFiles)
{
string path = Path.Combine(this.Environment.WebRootPath, "Uploads");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
List<string> uploadedFiles = new List<string>();
List<PdfReader> pdfReaderList = new List<PdfReader>();
foreach (IFormFile postedFile in postedFiles)
{
string fileName = Path.GetFileName(postedFile.FileName);
using (FileStream stream = new FileStream(Path.Combine(path, fileName), FileMode.Create))
{
postedFile.CopyTo(stream);
uploadedFiles.Add(Path.Combine(path, fileName));
}
}
foreach (string pdfFile in uploadedFiles)
{
PdfReader pdfReader = new PdfReader(Path.Combine(path, pdfFile));
pdfReaderList.Add(pdfReader);
}
Document document = new Document(PageSize.A4, 0, 0, 0, 0);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Path.Combine(path, "Merge.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(Image.GetInstance(page));
}
}
document.Close();
return View();
}
}
View
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Index">
<input type="file" name="postedFiles" multiple />
<input type="submit" value="Upload" />
</form>
</body>
</html>