How to Create a PDF Document and Insert an Image

As a PDF document creation component, Spire.PDF can help users create PDF documents. Users can easily use C#/VB.NET to design text content at will. In addition, by using Spire.PDF, we can also insert image into the PDF document.

Create a PDF Document

Step 1: Prepare

Download Spire.PDF (Spire.Office) and install on system. Then, create a project in visual studio and add Spire.PDF DLL as reference.

Step 2: Create a PDF Document

The code below can help us create a PDF document and generate a PDF page.

//Create a pdf document.
PdfDocument doc = new PdfDocument();

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

Step 3: Write Text Content

Now, use the following code to design text content. We can also design the text font.
page.Canvas.DrawString("Hello, World!",new PdfFont(PdfFontFamily.Helvetica, 30f),new PdfSolidBrush(Color.Black),10, 10);

Step 4: Save and Preview

We can use the code below to save the designed PDF document and launch to preview.
//Save pdf file.

//Launching the Pdf file.

Insert an Image into PDF Document

Step 1, 2, 3 are the same as above.

Step 4: Insert Image

Choose an image which we need insert into the PDF document and put it in the Project folder as the image shows below:
Create PDF File and Insert an Image
Following the code below to insert and design image. We can set the image width and height.
//Draw the image
PdfImage image = PdfImage.FromFile(@"..\..\Sample.jpg");
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);

Step 5: Save and Preview

It's the same as the Step 4 of "How to Create a PDF Document via Spire.PDF" above.

Effective Screenshot:

Create PDF File and Insert an Image