PDF Image in C#, VB.NET

  • Demo
  • C# source
  • VB.Net source

The sample demonstrates how to insert an image to a PDF document.

Download Image.pdf

using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;

namespace Image
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

            // Create one page
            PdfPageBase page = doc.Pages.Add();

            //Draw the text
            page.Canvas.DrawString("Hello, World!",
                                   new PdfFont(PdfFontFamily.Helvetica, 30f),
                                   new PdfSolidBrush(Color.Black),
                                   10, 10);
            //Draw the image
            PdfImage image = PdfImage.FromFile(@"SalesReportChart.png");
            float width = image.Width * 0.75f;
            float height = image.Height * 0.75f;
            float x = (page.Canvas.ClientSize.Width - width) / 2;

            page.Canvas.DrawImage(image, x, 60, width, height);

            //Save pdf file.
            doc.SaveToFile("Image.pdf");
            doc.Close();

            //Launching the Pdf file.
            System.Diagnostics.Process.Start("Image.pdf");
        }
    }
}

Imports System.Drawing
Imports Spire.Pdf
Imports Spire.Pdf.Graphics

Namespace Image
    Friend Class Program
        Shared Sub Main(ByVal args() As String)
            'Create a pdf document.
            Dim doc As New PdfDocument()

            ' Create one page
            Dim page As PdfPageBase = doc.Pages.Add()

            'Draw the text
            page.Canvas.DrawString("Hello, World!", _
                                   New PdfFont(PdfFontFamily.Helvetica, 30.0F), _
                                   New PdfSolidBrush(Color.Black), 10, 10)
            'Draw the image
            Dim image As PdfImage = PdfImage.FromFile("SalesReportChart.png")
            Dim width As Single = image.Width * 0.75F
            Dim height As Single = image.Height * 0.75F
            Dim x As Single = (page.Canvas.ClientSize.Width - width) / 2

            page.Canvas.DrawImage(image, x, 60, width, height)

            'Save pdf file.
            doc.SaveToFile("Image.pdf")
            doc.Close()

            'Launching the Pdf file.
            Process.Start("Image.pdf")
        End Sub
    End Class
End Namespace