Category Archives: PDF Generation

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.

Create PDF Documents in C# on the Fly with PdfSharp

Recently I was doing a freelance project and had to find a way to create PDF documents on the fly in a C# application. I figured the best approach would be to create PDF files that could be printed, then archived for retrieval at a later date. There are definitely libraries out there that you can pay for to help with this, but I really wanted something that was OpenSource. Luckily, I found PdfSharp!

You can pretty much draw anything for your PDF document using PdfSharp, shapes, text, images, etc. and you have full control over the fonts and the font weight. This gives you a lot of flexibility in creating your custom PDF documents. I highly recommend checking it out if you’re looking for a cheap (free is the best!) solution for your document creation.