Hi Waghmare,
Refer the below code to Split each pdf into separate page and save with unique no into the specified folder.
C#
protected void Page_Load(object sender, EventArgs e)
{
string file = Server.MapPath("~/Files/Test.pdf");
SplitAndSave(file, Server.MapPath("~/Files/"));
}
public int SplitAndSave(string inputPath, string outputPath)
{
FileInfo file = new FileInfo(inputPath);
string name = file.Name.Substring(0, file.Name.LastIndexOf("."));
using (PdfReader pdfReader = new PdfReader(inputPath))
{
for (int pageNumber = 1; pageNumber <= pdfReader.NumberOfPages; pageNumber++)
{
// Get CGHS No.
ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, pageNumber, strategy);
// Get CGHS No from the pdf as per your pdf containt.
string CGHSNo = currentText.Split(new string[] { "CGHS No:" }, StringSplitOptions.None)[1].Split('\n')[0];
// Generate New pdf with CGHS No.
string filename = CGHSNo + ".pdf";
Document document = new Document();
PdfCopy pdfCopy = new PdfCopy(document, new FileStream(outputPath + "\\" + filename, FileMode.Create));
document.Open();
pdfCopy.AddPage(pdfCopy.GetImportedPage(pdfReader, pageNumber));
document.Close();
}
return pdfReader.NumberOfPages;
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim file As String = Server.MapPath("~/Files/Test.pdf")
SplitAndSave(file, Server.MapPath("~/Files/"))
End Sub
Public Function SplitAndSave(inputPath As String, outputPath As String) As Integer
Dim file As New FileInfo(inputPath)
Dim name As String = file.Name.Substring(0, file.Name.LastIndexOf("."))
Using pdfReader As New iTextSharp.text.pdf.PdfReader(inputPath)
For pageNumber As Integer = 1 To pdfReader.NumberOfPages
' Get CGHS No.
Dim strategy As ITextExtractionStrategy = New SimpleTextExtractionStrategy()
Dim currentText As String = PdfTextExtractor.GetTextFromPage(pdfReader, pageNumber, strategy)
' Get CGHS No from the pdf as per your pdf containt.
Dim CGHSNo As String = currentText.Split(New String() {"CGHS No:"}, StringSplitOptions.None)(1).Split(ControlChars.Lf)(0)
' Generate New pdf with CGHS No.
Dim filename As String = CGHSNo & Convert.ToString(".pdf")
Dim document As New iTextSharp.text.Document()
Dim pdfCopy As New iTextSharp.text.pdf.PdfCopy(document, New FileStream(Convert.ToString(outputPath & Convert.ToString("\")) & filename, FileMode.Create))
document.Open()
pdfCopy.AddPage(pdfCopy.GetImportedPage(pdfReader, pageNumber))
document.Close()
Next
Return pdfReader.NumberOfPages
End Using
End Function