public void DeletePDFPage(string sourcePath, string outputPath, int pageNumber)
{
using (PdfReader reader = new PdfReader(sourcePath))
{
int pageCount = reader.NumberOfPages;
if (pageNumber < 1 || pageNumber > pageCount)
{
throw new ArgumentException("Invalid page number");
}
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(outputPath, FileMode.Create)))
{
stamper.Writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_5);
for (int i = pageCount; i >= 1; i--)
{
if (i == pageNumber)
{
continue;
}
PdfDictionary pageDict = reader.GetPageN(i);
int rotate = pageDict.GetAsNumber(PdfName.ROTATE)?.IntValue ?? 0;
Rectangle pageSize = reader.GetPageSizeWithRotation(i);
PdfImportedPage importedPage = stamper.GetImportedPage(reader, i);
PdfContentByte content = stamper.GetUnderContent(i);
content.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0);
PdfCopy.PageStamp pageStamp = stamper.CreatePageStamp(importedPage);
pageStamp.AlterContents();
stamper.AddPage(importedPage, new Rectangle(pageSize.Width, pageSize.Height, rotate));
stamper.AlterContents(pageCount - i + 1, pageStamp.GetOverContent());
}
}
}
}