views:

436

answers:

1

I am trying to do something I thought would be quite simple, however it is not so straight forward and google has not helped.

I am using iTextSharp to merge PDF documents (letters) together so they can all be printed at once. If a letter has an odd number of pages I need to append a blank page, so we can print the letters double-sided.

Here is the basic code I have at the moment for merging all of the letters:

// initiaise
 MemoryStream pdfStreamOut = new MemoryStream();
    Document document = null;
    MemoryStream pdfStreamIn = null;
    PdfReader reader = null;
    int numPages = 0;
    PdfWriter writer = null;


for int(i = 0;i < letterList.Count; i++)
{
    byte[] myLetterData = ...;
    pdfStreamIn = new MemoryStream(myLetterData);
    reader = new PdfReader(pdfStreamIn);
    numPages = reader.NumberOfPages;

    // open the streams to use for the iteration
    if (i == 0)
    {
        document = new Document(reader.GetPageSizeWithRotation(1));
        writer = PdfWriter.GetInstance(document, pdfStreamOut);
        document.Open();
    }

    PdfContentByte cb = writer.DirectContent;
    PdfImportedPage page;

    int importedPageNumber = 0;
    while (importedPageNumber < numPages)
    {
        importedPageNumber++;
        document.SetPageSize(reader.GetPageSizeWithRotation(importedPageNumber));
        document.NewPage();
        page = writer.GetImportedPage(reader, importedPageNumber);
        cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
    }
}

I have tried using:

    document.SetPageSize(reader.GetPageSizeWithRotation(1));
    document.NewPage();

at the end of the for loop for an odd number of pages without success.

Any help would be much appreciated!

+4  A: 

Well I was almost there. The document won't actually create the page until you put something on it, so as soon as I added an empty table, bam! It worked!

Here is the code that will add a blank page if the document I am merging has an odd number of pages:

                    if (numPages > 0 && numPages % 2 == 1)
                    {
                        bool result = document.NewPage();
                        document.Add(new Table(1));
                    }
Russell