Adding an Image to a PDF Document Using C# and PdfSharp

A while back I wrote about generating PDF documents using PdfSharp. It worked really well for us to generate invoices and purchase orders on the fly to ship orders and receive product. One must on our invoices was showing our corporate logo on our invoices that went out to our customers. We also wanted to do the same on the documents we generated for our purchase orders so that our vendors could easily identify our company when processing the order. This turned out to be a snap using PdfSharp.

void AddLogo(XGraphics gfx, PdfPage page, string imagePath, int xPosition, int yPosition)
{
    if (!File.Exists(imagePath))
    {
	throw new FileNotFoundException(String.Format("Could not find image {0}.", imagePath));
    }

    XImage xImage = XImage.FromFile(imagePath);
    gfx.DrawImage(xImage, xPosition, yPosition, xImage.PixelWidth, xImage.PixelWidth);
}


try
{
    PdfDocument doc = new PdfDocument();
    PdfPage page = doc.AddPage();
    
    XGraphics gfx = XGraphics.FromPdfPage(page);
    
    AddLogo(gfx, invoice, "pathtoimage", 0, 0);
}
catch (Exception)
{
    // Handle exception
}

The arguments to DrawImage on the XGraphics object specify an XImage object, the starting position of the image (0, 0 in this case), and the dimensions of the image. You can get the dimensions easily from the PixelWidth and PixelHeight properties (the Width and Height properties can be used, but are deprecated) of the XImage object.

Then call the AddLogo() method above to draw your image in the document. Positioning and image dimensions are important to get correct otherwise the image won’t draw properly in your document. Keep track of where you place your logo when drawing text or additional images on your document as well. If you don’t keep track of positioning from element to element, you’ll actually draw over previous elements.

6 thoughts on “Adding an Image to a PDF Document Using C# and PdfSharp

  1. bill Post author

    Could it be that the library has been updated and my post is out of date? I haven’t worked with that code in a very long time so I wouldn’t be surprised if its no longer applicable in a current version of that PDF library. Thanks!

  2. salahuddin

    I want to add image on existing pdf page how can do that
    currently my code is
    var filename=”D://sample.pdf”;
    PdfDocument doc = new PdfDocument(filename);
    PdfPage page = document.Pages[0];
    XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append);
    XImage image = XImage.FromFile(“D://sample.png”);
    gfx.DrawImage(image, 0, 0, 50, 50);

    but not able to draw image on existing pdf
    thanks in advance.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.