开发者

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

开发者 https://www.devze.com 2022-12-24 09:40 出处:网络
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 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开发者_Python百科 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.


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));
}

If this doesn't work in newer versions, try this instead:

document.Add(new Chunk());


Another alternative that works successfully.

if (numPaginas % 2 != 0)
            {
                documentoPdfUnico.SetPageSize(leitorPdf.GetPageSizeWithRotation(1));
                documentoPdfUnico.NewPage();
                conteudoPdf.AddTemplate(PdfTemplate.CreateTemplate(escritorPdf, 2480, 3508), 1f, 0, 0, 1f, 0, 0);
            }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号