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 PNG images", textStyle, new ParagraphStyle( ParagraphHorizontalAlignment.Center ) ); // Creates a reusable imageDefinition1 from a png path file and rotate it by 45 degrees. var imageSource1 = ImageSource.FromPath( ImagesSample.ImagesSampleResourcesDirectory + @"balloon.png" ); var imageDefinition1 = new ImageDefinition( imageSource1 ) { RotationAngle = 45d }; // Draw imageDefinition1 with its TopLeft corner at (50, 75). var image1 = page1.Graphics.DrawImage( imageDefinition1, new Point( 50, 75 ) ); // Creates image2 from a png stream. using( var imageStream = File.OpenRead( ImagesSample.ImagesSampleResourcesDirectory + @"office.png" ) ) { var imageSource2 = ImageSource.FromStream( imageStream ); // Draw imageSource2 with its TopLeft corner at (50, 400), with a width of 500 and a height of 200. page1.Graphics.DrawImage( imageSource2, new Rectangle( 50, 400, 500, 200 ) ); } // Gets the second Page. var page2 = pdfoutput.Pages.Add(); // Adds a title. page2.AddParagraph( "Add JPEG images", textStyle, new ParagraphStyle( ParagraphHorizontalAlignment.Center ) ); // Draw a third image with the reusabe imageDefinition1 with its TopLeft corner at (50, 75). page2.Graphics.DrawImage( imageDefinition1, new Point( 50, 75 ) ); // Creates image4 from a jpg stream. using( var imageStream = File.OpenRead( ImagesSample.ImagesSampleResourcesDirectory + @"office.jpg" ) ) { var imageSource4 = ImageSource.FromStream( imageStream ); // Draw imageSource4 with its TopLeft corner at (50, 400), with a width of 500 and a height of 200. page2.Graphics.DrawImage( imageSource4, new Rectangle( 50, 400, 500, 200 ) ); } // Saves the output document. pdfoutput.Save(); Console.WriteLine( $"Info exported to path: {outputFileName}" ); } } | |