In This Topic
    Add images
    In This Topic

    Introduction

    The following example demonstrates how to add images in a PDF document, using both a path & a stream.

    It also briefly covers how to create the document that will host the images, as well as how to add a title to said document.

    Add images in a PDF document (C#)
    Copy Code
    public static void AddImages()
    {
      Console.WriteLine( "=== ADD IMAGES ===" );
      var outputFileName = "AddImages.pdf";
      var outputPath = ImagesSample.ImagesSampleOutputDirectory + outputFileName;
    
      // Creates a PdfDocument.
      using( var pdfoutput = PdfDocument.Create( outputPath ) )
      {
        // Gets the first Page.
        var page1 = pdfoutput.Pages.First();
    
        // Adds a title.
        var textStyle = TextStyle.WithFont( pdfoutput.Fonts.GetStandardFont( StandardFontType.Helvetica ), 15d );
        page1.AddParagraph( "Add images", textStyle, new ParagraphStyle( ParagraphHorizontalAlignment.Center ) );
    
        // Creates image1 from a png path file.
        var image1 = Image.FromPath( ImagesSample.ImagesSampleResourcesDirectory + @"balloon.png" );
        // Draw image1 with its TopLeft corner at (50, 75).
        page1.Graphics.DrawImage( image1, new Point( 50, 75 ) );
    
        // Creates image2 from a png stream.
        var imageStream = File.OpenRead( ImagesSample.ImagesSampleResourcesDirectory + @"office.png" );
        var image2 = Image.FromStream( imageStream );
        // Draw image2 with its TopLeft corner at (50, 400), with a width of 500 and a height of 200.
        page1.Graphics.DrawImage( image2, new Rectangle( 50, 400, 500, 200 ) );
    
        // Saves the output document.
        pdfoutput.Save();
        Console.WriteLine( $"Info exported to path: {outputFileName}" );
      }
    }


    See Also