Search code examples
c#printdocument

Print pages NOT in the List


I have a int list containing the pages I DON'T want to print.

Let's call it skipPages.

When I tried to put the actual printing part inside the if(skipPages.IndexOf(currentPage)<0) statement, it print me blank pages.

public void printPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    List<int> skipPages = new List<int> { 2, 5, 6 };
    if(currentPage<totalPage) e.HasMorePages = true;
    else e.HasMorePages = false;

    if(skipPages.IndexOf(currentPage)<0)
    {
        e.Graphics.DrawString(
            currentPage.ToString(),
            new Font("Times New Roman",12),
            new SolidBrush(Color.Black),
            new Point(10,10));
    }
    currentPage++;

}

And when I tried to put the e.HasMorePages = true inside it, it just stop everything after the first skip page.

public void printPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    List<int> skipPages = new List<int> { 2, 5, 6 };
    if(currentPage<totalPage && skipPages.IndexOf(currentPage)<0) e.HasMorePages = true;
    else e.HasMorePages = false;

    e.Graphics.DrawString(
        currentPage.ToString(),
        new Font("Times New Roman",12),
        new SolidBrush(Color.Black),
        new Point(10,10));
    currentPage++;

}

Could somebody please teach me how to correctly set it up, please!?

Much appreciated!!!


Solution

  • The PrintPage event is fired for every page, so all you have to do is to skip the currentPage which is in the List.

    You also need a mechanism to check if the last few pages are in the skip list, to avoid printing blank pages in the end.

    List<int> skipPages = new List<int> { 2, 5, 6 };
    
    private void printDocument1_BeginPrint(object sender, PrintEventArgs e)
    {
        currentPage = 0;
    }
    
    public void printPage(object sender,System.Drawing.Printing.PrintPageEventArgs e)
    {
        bool f = false;
        int c = currentPage + 1;
    
        //Mechanism to check for the last few pages.
        while(skipPages.IndexOf(c)>=0) c++;
        if(c>=totalPages) f=false;
        else f=true;
    
        while(skipPages.IndexOf(currentPage)>=0) currentPage++; //Actual skipping part.
        if(currentPage<totalPage-1) e.HasMorePages = f;
        else e.HasMorePages = false;
        e.Graphics.DrawString(
             currentPage.ToString(),
             new Font("Times New Roman",12),
             new SolidBrush(Color.Black),
             new Point(10,10));
        currentPage++;
    }