I have 300-400 PDFs in a directory. They need to be merged into one PDF, sorted by name, and page numbers should be added according to their total count in the merged file. I read the contents of the directory, sort the array of file names, and merge them one by one in the following way:
foreach (var file in projectFiles)
{
PdfDocument projectPdf = new PdfDocument(new PdfReader(file));
merger.Merge(projectPdf, 1, projectPdf.GetNumberOfPages());
currentPage += projectPdf.GetNumberOfPages();
projectPdf.Close();
}
The PDF file is merged, and it displays correctly in the reader. I call a function that is supposed to add the page numbers:
public static void AddPageNumbers(PdfDocument pdfDoc, int totalPages)
{
Document doc = new Document(pdfDoc);
int currentPage = 1;
for (int i = 1; i <= pdfDoc.GetNumberOfPages(); i++)
{
var currentPagePara = new Paragraph((currentPage).ToString())
.SetFontSize(10);
var totalPagesPara = new Paragraph(totalPages.ToString())
.SetFontSize(10);
doc.ShowTextAligned(currentPagePara, 500, 20, i, TextAlignment.LEFT, VerticalAlignment.BOTTOM, 0);
doc.ShowTextAligned(totalPagesPara, 530, 20, i, TextAlignment.LEFT, VerticalAlignment.BOTTOM, 0);
currentPage++;
}
doc.Close();
}
Unfortunately, when I run this, I get this:
Now, if I run almost the same code with the newly created PDF document using this code:
string dest = "output.pdf";
PdfWriter writer = new PdfWriter(dest);
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf);
var para1 = new Paragraph("18");
var para2 = new Paragraph("1033");
document.ShowTextAligned(para1, 500, 20, 1, TextAlignment.LEFT, VerticalAlignment.TOP, 0);
document.ShowTextAligned(para2, 530, 20, 1, TextAlignment.LEFT, VerticalAlignment.TOP, 0);
document.Close();
Everything is fine – the page numbers appears in the bottom right section of the document correctly without any inversion.
Please advise how can it be fixed.
1