2

I am using this code to merge a pdf file to the start of pdf but want to set it to the 2nd page of existing pdf.

How do I do that ? How to go with this?

I have spent days on it but no luck.

public static string MergeFiles(string destinationFile, string[] sourceFiles)
{
    try
    {
        string NewFileName = "InspectionReport" + DateTime.Now.ToString("ddMMMyyyy HHmmss").Replace(" ", "");
        destinationFile = HostingEnvironment.MapPath(@"/Downloads/Files/" + NewFileName + ".pdf");

        int f = 0;

        PdfReader reader = new PdfReader(sourceFiles[f]);

        int n = reader.NumberOfPages;

        Document document = new Document(reader.GetPageSizeWithRotation(1));

        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));

        document.Open();
        PdfContentByte cb = writer.DirectContent;
        PdfImportedPage page;
        int rotation;

        while (f < sourceFiles.Length)
        {
            int i = 0;
            while (i < n)
            {
                i++;
                document.SetPageSize(reader.GetPageSizeWithRotation(i));
                document.NewPage();
                page = writer.GetImportedPage(reader, i);
                rotation = reader.GetPageRotation(i);
                if (rotation == 90 || rotation == 270)
                {
                    cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                }
                else
                {
                    cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                }

            }
            f++;
            if (f < sourceFiles.Length)
            {
                reader = new PdfReader(sourceFiles[f]);

                n = reader.NumberOfPages;

            }
        }

        document.Close();
    }
    catch (Exception e)
    {
        string strOb = e.Message;
    }

    return destinationFile;
}

Now, it only appends at the top and I can think of no way of adding to the 2nd page of the existing pdf.

Stacky
  • 57
  • 1
  • 8
  • Is there a specific reason why you use the `PdfWriter` class and not the `PdfCopy` class (also iText) for merging? – mkl Jul 22 '19 at 14:11

0 Answers0