Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save documentprocessing/42777d8d6541704ca77b20158801f8c1 to your computer and use it in GitHub Desktop.
Save documentprocessing/42777d8d6541704ca77b20158801f8c1 to your computer and use it in GitHub Desktop.
Add image to PDF using PDFSharp API
using System;
using PdfSharp.Pdf;
using PdfSharp.Drawing;
class Program
{
static void Main(string[] args)
{
// Create a new PDF document
PdfDocument document = new PdfDocument();
document.Info.Title = "Add Image to PDF";
// Add a new page to the document
PdfPage page = document.AddPage();
// Create an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
// Load the image from a file
string imagePath = "example.jpg"; // Provide the path to your image file
XImage image = XImage.FromFile(imagePath);
// Define the position and size of the image on the PDF page
double xPosition = 50;
double yPosition = 100;
double imageWidth = 200;
double imageHeight = 150;
// Draw the image on the PDF page
gfx.DrawImage(image, xPosition, yPosition, imageWidth, imageHeight);
// Save the document
string filename = "ImageInPDF.pdf";
document.Save(filename);
// Inform the user
Console.WriteLine($"PDF file '{filename}' created with the image!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment