C# Method to Add an Image to a PDF Posted by Dave under Code Samples.

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

            gfx.DrawImage(
                ximg,
                position.X,
                position.Y,
                ximg.Width * scale,
                ximg.Height * scale
            );

            using (System.IO.MemoryStream msFinal = new System.IO.MemoryStream())
            {
                document.Save(msFinal);
                return msFinal.ToArray();
            }

        }
    }
}

Leave a Reply


©2010 www.geekscrapbook.com