C# Method to Add an Image to a PDF

I had to write a method to put images onto PDFs generically, so I wrote this handy little method. Just get your PDF and your image into byte arrays and fire the method below. I used PDFSharp to append the image. This method could be used to do things like build a letterhead generator or any other kind of PDF document generation.

Here’s the method:

public static byte[] AppendImageToPdf(byte[] pdf, byte[] img, Point position, double scale)
    using (System.IO.MemoryStream msPdf = new System.IO.MemoryStream(pdf))
        using (System.IO.MemoryStream msImg = new System.IO.MemoryStream(img))
            System.Drawing.Image image = System.Drawing.Image.FromStream(msImg);
            PdfSharp.Pdf.PdfDocument document = PdfSharp.Pdf.IO.PdfReader.Open(msPdf);
            PdfSharp.Pdf.PdfPage page = document.Pages[0];
            PdfSharp.Drawing.XGraphics gfx = PdfSharp.Drawing.XGraphics.FromPdfPage(page);
            PdfSharp.Drawing.XImage ximg = PdfSharp.Drawing.XImage.FromGdiPlusImage(image);
                ximg.Width * scale, 
                ximg.Height * scale

            using (System.IO.MemoryStream msFinal = new System.IO.MemoryStream())
                return msFinal.ToArray();


One Comment

  1. Richard Chang says:


    Thanks for this example with PdfSharp !

    So, this can be used to add a bunch of images at the end of a PDF ?
    Not sure what you mean by a “Letterhead” generator.
    Isn’t a letterhead something at the beginning of each page of the document ?

    Any idea of putting some image description text ( above or below each image ) ?
    Regards, Rich

Leave a Reply