Split PDF into multiple PDFs using iTextsharp in ASP.Net Core MVC

Last Reply 4 days ago By dharmendr

Posted 4 days ago

HI All,

I want split one pdf file into multiple pdf file and save the details in asp.net core mvc5

Pls share refence code in .Net core mvc core 3.1 

Posted 4 days ago

Hi venkatg,

Check this example. Now please take its reference and correct your code.

Install iTextShap from Nuget Packages.

Controller 

public class HomeController : Controller
{
    private Microsoft.AspNetCore.Hosting.IHostingEnvironment Environment;

    public HomeController(Microsoft.AspNetCore.Hosting.IHostingEnvironment _environment)
    {
        Environment = _environment;
    }

    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public IActionResult Index(Microsoft.AspNetCore.Http.IFormFile postedFile)
    {
        string inputPath = System.IO.Path.Combine(this.Environment.WebRootPath, "Files");
        if (!System.IO.Directory.Exists(inputPath))
        {
            System.IO.Directory.CreateDirectory(inputPath);
        }

        string outputPath = System.IO.Path.Combine(this.Environment.WebRootPath, "SplitedFiles");
        if (!System.IO.Directory.Exists(outputPath))
        {
            System.IO.Directory.CreateDirectory(outputPath);
        }

        string inputFileName = System.IO.Path.GetFileName(postedFile.FileName);
        using (System.IO.FileStream stream = new System.IO.FileStream(System.IO.Path.Combine(inputPath, inputFileName), System.IO.FileMode.Create))
        {
            postedFile.CopyTo(stream);
        }

        using (iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(System.IO.Path.Combine(inputPath, inputFileName)))
        {
            for (int pageNumber = 1; pageNumber <= pdfReader.NumberOfPages; pageNumber++)
            {
                string outputFileName = string.Format("{0}_{1}.pdf", System.IO.Path.GetFileNameWithoutExtension(inputFileName), pageNumber);
                iTextSharp.text.Document document = new iTextSharp.text.Document();
                iTextSharp.text.pdf.PdfCopy pdfCopy =
                    new iTextSharp.text.pdf.PdfCopy(document, new System.IO.FileStream(System.IO.Path.Combine(outputPath, outputFileName), System.IO.FileMode.Create));
                document.Open();
                pdfCopy.AddPage(pdfCopy.GetImportedPage(pdfReader, pageNumber));
                document.Close();
            }
        }

        System.IO.Directory.Delete(inputPath, true);

        return View();
    }
}

View

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <form method="post" asp-controller="Home" asp-action="Index" enctype="multipart/form-data">
        <input type="file" name="postedFile" />
        <input type="submit" value="Split" />
    </form>
</body>
</html>