title: PDFsharp/MigraDoc Add background images to pages
body: <p><strong>GOAL</strong></p>
  <p>To open an existing PDF file with multiple pages and add background image to all pages. (Optionally the background image of the first page differs from the others)</p>
  <p>In my current implementation (I use .NET 6 and PDFsharp btw.) I add the image to each page, which increases the size of the file dependent on the number of pages.</p>
  <p><strong>QUESTION</strong></p>
  <p>Is there a way in PDFsharp/MigraDoc to embed a background image only once into the document and then reference it for each page?</p>
  <p><strong>CODE</strong></p>
  <p>Both PDF document and the image come from a database as byte arrays.</p>
  <pre><code>public byte[] AddBackgroundImgToDocument(byte[] doc, byte[] imgFirstPage, byte[]? imgOtherPages=null)
  {
      using var ms = new MemoryStream(doc);
      PdfDocument pdfDoc = PdfReader.Open(ms, PdfDocumentOpenMode.Modify);
      
      for (int i = 0; i &lt; pdfDoc.PageCount; i++)
      {
          if(i &gt; 0 &amp;&amp; imgOtherPages != null &amp;&amp; imgOtherPages.Length &gt; 0)
              AddBackgroundImageFromByteArray(pdfDoc.Pages[i], imgOtherPages);
          else
              AddBackgroundImageFromByteArray(pdfDoc.Pages[i], imgFirstPage);
  
          GC.Collect();
          GC.WaitForPendingFinalizers();
      }
      using var oms = new MemoryStream();
      pdfDoc.Save(oms);
      ms.Dispose();
      pdfDoc.Dispose();
      return oms.ToArray();
  }
  
  public void AddBackgroundImageFromByteArray(PdfPage page, byte[] imgfile)
  {
      XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
      MemoryStream ms = new System.IO.MemoryStream(imgfile);
      ms.Position = 0;
      XImage image = XImage.FromStream(() =&gt; ms);
      gfx.DrawImage(image, 0, 0, page.Width, page.Height);
      ms.Dispose();
  }
  </code></pre>
  <p><strong>SOLUTION</strong></p>
  <p>Rewriting the method above according to accepted answer, solved my problem:</p>
  <pre><code>public void AddBackgroundImageFromByteArray(PdfPage page, byte[] imgfile)
  {
      if(!ximageLoaded)
      {
          MemoryStream ms = new System.IO.MemoryStream(imgfile);
          ms.Position = 0;
          backimg = XImage.FromStream(() =&gt; ms);
          ms.Dispose();
          ximageLoaded = true;
      }
  
      XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
      gfx.DrawImage(backimg, 0, 0, page.Width, page.Height);
  }
  </code></pre>