Global Header and Footer for Printing in C# (rather than copying and pasting same info several times)

StackOverflow https://stackoverflow.com/questions/21674042

Question

In my application, users can preview and print documents - let's say Doc A, Doc B and Doc C, each displaying the same header and footer. Currently the code is copied across but for efficiency reasons, could I simply create another method which holds the consistent info and simply call and create text and images (or something else)? The following example is similar to my application:

private void Doc_A_Preview_Click(object sender, EventArgs e)
{
     PrintDocument Print_Document = new PrintDocument();
     Print_Document.PrintPage += new PrintPageEventHandler(Doc_A);
     PrintPreviewDialog Print_Preview = new PrintPreviewDialog();
     Print_Preview.Document = Print_Document;
     Print_Preview.ShowDialog(this);
}

private void Doc_A_Print_Click(object sender, EventArgs e)
{
      PrintDocument Print_Document = new PrintDocument();
      Print_Document.PrintPage += new PrintPageEventHandler(Doc_A);
      PrintDialog Print_Dialog = new PrintDialog();
      Print_Dialog.Document = Print_Document;
      Print_Dialog.ShowDialog(this);

      if (Print_Dialog.ShowDialog() == DialogResult.OK)
      {
          Print_Document.Print();
      }
}

I thought perhaps creating a method for the header/footer and the page body (different for all pages) would make sense like the following:

Consistent Header/Footer

private void HeaderFooter(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    // Title
    // Info
    // Logo
    // Application name
    // Copyright
    // Current date and time
}

Inconsistent Page Body

private void Doc_A(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    // Doc A (heading)
    // Body text
    // Images
}

I am aware that the top two methods (Doc_A_Preview_Click and Doc_A_Print_Click) only call Doc_A method that just displays the body text and heading, I'm not sure how to call the header/footer as well.

So, How do I merge both Doc_A and HeaderFooter together?

Était-ce utile?

La solution

If I understand question right, then you can do it like this

private void Doc_A(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    Header(sender, e);
    // Body text
    // Images
    Footer(sender, e);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top