How to add a blank page to a pdf using iTextSharp?

Posted by Russell on Stack Overflow See other posts from Stack Overflow or by Russell
Published on 2010-03-24T22:10:42Z Indexed on 2010/03/24 22:13 UTC
Read the original article Hit count: 1379

Filed under:
|
|

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!

© Stack Overflow or respective owner

Related posts about c#

Related posts about itextsharp