Adding layers can help us to make the information that we don't want others to view become invisible in a pdf file. Spire.PDF, as a powerful and independent pdf library, enables us to add layers to pdf files without having Adobe Acrobat been installed on system.

This article will introduce how to add different types of layers to a pdf file in WPF using Spire.PDF for WPF.

Below is the effective screenshot after adding layers:

How to Add Different Types of Layers to a PDF File in WPF

Detail Steps and Code Snippets:

Use namespace:

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

Step 1: Create a new PDF file and add a new page to it.

PdfDocument doc = new PdfDocument();
PdfPageBase page = doc.Pages.Add();

Step 2: Add image layer.

Add a layer named Image Layer to the page, call DrawImage(PdfImage image, float x, float y, float width, float height) method to add an image to the layer.

PdfPageLayer layer = page.PageLayers.Add("Image Layer");
layer.Graphics.DrawImage(PdfImage.FromFile("image.jpg"), 0, 100, 300, 30);

Step 3: Add line layer.

Add a layer named Line Layer to the page, call DrawLine(PdfPen pen, PointF point1, PointF point2) method to draw a red line to the layer.

layer = page.PageLayers.Add("Line Layer");
layer.Graphics.DrawLine(new PdfPen(PdfBrushes.Red, 1), new PointF(0, 200), new PointF(300, 200));

Step 4: Add string layer.

Add a layer named String Layer to the page, call DrawString(string s, PdfFontBase font, PdfPen pen, float x, float y) method to draw some string to the layer.

layer = page.PageLayers.Add("String Layer");
layer.Graphics.DrawString("Add layer to pdf using Spire.PDF", new PdfFont(PdfFontFamily.Courier, 12), new PdfPen(PdfBrushes.Navy,1),0,300);

Step 5: Save and launch the file.

doc.SaveToFile("AddLayers.pdf", FileFormat.PDF);
System.Diagnostics.Process.Start("AddLayers.pdf");

Full codes:

private void button1_Click(object sender, RoutedEventArgs e)
{
    PdfDocument doc = new PdfDocument();
    PdfPageBase page = doc.Pages.Add();

    PdfPageLayer layer = page.PageLayers.Add("Image Layer");
    layer.Graphics.DrawImage(PdfImage.FromFile("image.jpg"), 0, 100, 300, 30);

    layer = page.PageLayers.Add("Line Layer");
    layer.Graphics.DrawLine(new PdfPen(PdfBrushes.Red, 1), new PointF(0, 200), new PointF(300, 200));
  
    layer = page.PageLayers.Add("String Layer");
    layer.Graphics.DrawString("Add layer to pdf using Spire.PDF", new PdfFont(PdfFontFamily.Courier, 12), new PdfPen(PdfBrushes.Navy,1),0,300);

    doc.SaveToFile("AddLayers.pdf", FileFormat.PDF);
    System.Diagnostics.Process.Start("AddLayers.pdf"); 
}
Published in Program Guide WPF

In some cases, we need to copy one or more pages of a pdf file, while copy pdf pages can be classified into two categories: copy pages within a pdf file and copy pages between pdf files. With the help of Spire.PDF, we can easily achieve this task programmatically instead of using Adobe Acrobat and dragging the page to copy it manually.

This article will demonstrate how to copy a page within a pdf file or between pdf files in WPF using Spire.PDF for WPF.

Before using the code, please add the following namespace first:

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

Copy Page within a PDF File

Step 1: Initialize a new instance of PdfDocument class and load the sample pdf file.

PdfDocument doc1 = new PdfDocument();
doc1.LoadFromFile("Stories.pdf");

Step 2: Get the first page of the pdf file, then get its page size and call CreateTemplate() method to create a new pdf template based on the first page.

PdfPageBase page = doc1.Pages[0];
SizeF size = page.Size;
PdfTemplate template = page.CreateTemplate();

Step 3: Copy the first page within the pdf file.

Add a new page that is the same size as the first page to the pdf file, draw the template to the new page by invoking DrawTemplate(PdfTemplate template, PointF location) method.

page = doc1.Pages.Add(size, new PdfMargins(0,0));
page.Canvas.DrawTemplate(template,new PointF(0,0));

Step 4: Save and launch the file.

doc1.SaveToFile("copyWithin.pdf");
System.Diagnostics.Process.Start("copyWithin.pdf");

Effective Screenshot:

How to Copy a Page within a PDF File or between PDF Files in WPF

Copy Page between PDF Files

Step 1: Initialize a new instance of PdfDocument class named doc1 and load the first pdf file.

PdfDocument doc1 = new PdfDocument();
doc1.LoadFromFile("Stories.pdf");

Step 2: Initialize a new instance of PdfDocument class named doc2 and load the second pdf file.

PdfDocument doc2 = new PdfDocument();
doc2.LoadFromFile("Instruction.pdf");

Step 3: Get the first page of doc1, then get its page size and create a new template based on the first page.

PdfPageBase page = doc1.Pages[0];
SizeF size = page.Size;
PdfTemplate template = page.CreateTemplate();

Step 4: Copy the first page from doc1 to doc2.

Invoking Insert(int index, SizeF size, PdfMargins margins) method to insert a new page that is the same size as the first page to the specified location of doc2, next draw the template to the new page.

doc2.Pages.Insert(1, size, new PdfMargins(0,0));          
doc2.Pages[1].Canvas.DrawTemplate(template,new PointF(0,0));

If you want to copy the page to doc2 as its last page, please use the following code to add a new page to the end of doc2, then draw the template to the new page.

doc2.Pages.Add(size, new PdfMargins(0, 0));

Step 5: Save and launch the file.

doc2.SaveToFile("copyBetween.pdf");
System.Diagnostics.Process.Start("copyBetween.pdf");

Effective Screenshot:

How to Copy a Page within a PDF File or between PDF Files in WPF

Full codes:

Copy page within a pdf file:

private void button1_Click(object sender, RoutedEventArgs e)
{
    PdfDocument doc1 = new PdfDocument();
    doc1.LoadFromFile("Stories.pdf");

    PdfPageBase page = doc1.Pages[0];
    SizeF size = page.Size;
    PdfTemplate template = page.CreateTemplate();
            
    page = doc1.Pages.Add(size, new PdfMargins(0,0));
    page.Canvas.DrawTemplate(template, new PointF(0,0));

    doc1.SaveToFile("copyWithin.pdf");
    System.Diagnostics.Process.Start("copyWithin.pdf");
}

Copy page between pdf files:

private void button1_Click(object sender, RoutedEventArgs e)
{
    PdfDocument doc1 = new PdfDocument();
    doc1.LoadFromFile("Stories.pdf");
            
    PdfDocument doc2 = new PdfDocument();
    doc2.LoadFromFile("Instruction.pdf");

    PdfPageBase page = doc1.Pages[0];
    SizeF size = page.Size;
    PdfTemplate template = page.CreateTemplate();
             
doc2.Pages.Insert(1, size, new PdfMargins(0,0));           
    doc2.Pages[1].Canvas.DrawTemplate(template, new PointF(0,0));

    doc2.SaveToFile("copyBetween.pdf");
    System.Diagnostics.Process.Start("copyBetween.pdf");
}
Published in Program Guide WPF

Nowadays, many files are saved as PDF format. PDF has many advantages and its Find and Highlight feature makes it easier for us to find important information inside a lengthy PDF document.

In the following sections, I will demonstrate how to highlight different searched texts with different colors in WPF.

The code snippets are as followed:

Step 1: Initialize a new instance of PdfDocument class and load the PDF document from the file.

PdfDocument pdf = new PdfDocument("ToHelen.pdf");

Step 2: Call FindText() method to search the string "thy" in the first page of the file, then return to Result1. Traverse result1 and call ApplyHighLight() method to highlight all elements in result1. Set the highlight color as yellow.

PdfTextFind[] result1 = null;
result1 = pdf.Pages[0].FindText("thy").Finds;
foreach (PdfTextFind find in result1)
{
    find.ApplyHighLight(System.Drawing.Color.Yellow);
}

Step 3: Repeat step 2 to highlight all the texts "to" on Page 1 with the color of DeepSkyBlue.

PdfTextFind[] result2 = null;
result2 = pdf.Pages[0].FindText("to").Finds;
foreach (PdfTextFind find in result2)
{
    find.ApplyHighLight(System.Drawing.Color.DeepSkyBlue);
}

Step 4: Save the PDF document and launch the file.

pdf.SaveToFile("HighlightedToHelen.pdf", Spire.Pdf.FileFormat.PDF);
System.Diagnostics.Process.Start("HighlightedToHelen.pdf");

Effective screenshot:

How to highlight different searched texts with different colors in WPF

Full Codes:

[C#]
//load the PDF document from the file
PdfDocument pdf = new PdfDocument("ToHelen.pdf");

//highlight searched text "thy" with Yellow
PdfTextFind[] result1 = null;
result1 = pdf.Pages[0].FindText("thy").Finds;
foreach (PdfTextFind find in result1)
{
    find.ApplyHighLight(System.Drawing.Color.Yellow);
}

//highlight searched text “to” with DeepSkyBlue
PdfTextFind[] result2 = null;
result2 = pdf.Pages[0].FindText("to").Finds;
foreach (PdfTextFind find in result2)
{
    find.ApplyHighLight(System.Drawing.Color.DeepSkyBlue);
}

//save and launch the file
pdf.SaveToFile("HighlightedToHelen.pdf", Spire.Pdf.FileFormat.PDF);
System.Diagnostics.Process.Start("HighlightedToHelen.pdf");
[VB.NET]
'load the PDF document from the file
Dim pdf As New PdfDocument("ToHelen.pdf")

'highlight searched text "thy" with Yellow
Dim result1 As PdfTextFind() = Nothing
result1 = pdf.Pages(0).FindText("thy").Finds
For Each find As PdfTextFind In result1
	 find.ApplyHighLight(System.Drawing.Color.Yellow)
Next

'highlight searched text "to" with DeepSkyBlue
Dim result2 As PdfTextFind() = Nothing
result2 = pdf.Pages(0).FindText("to").Finds
For Each find As PdfTextFind In result2
	 find.ApplyHighLight(System.Drawing.Color.DeepSkyBlue)
Next

'save and launch the file
pdf.SaveToFile("HighlightedToHelen.pdf", Spire.Pdf.FileFormat.PDF)
System.Diagnostics.Process.Start("HighlightedToHelen.pdf")
Published in Program Guide WPF

It seems very easy to rotate the PDF page. However, we often find that the rotation is applied to the whole PDF document when we try to rotate a particular page. Is there an easy and fast way to rotate a certain PDF page within the DPF document?

In the following sections, I will demonstrate how to rotate a certain PDF page within PDF document in WPF with several lines of codes.

The code snippets are as followed:

Step 1: Initialize a new instance of PdfDocument class and load the PDF document from the file.

PdfDocument doc = new PdfDocument();
doc.LoadFromFile("LeavesOfGrass.pdf");

Step 2: For rotation, Spire.PDF enables you to define 0, 90, 180 and 270 degrees. In this example, my PDF file has five pages. I want to rotate the fifth page by 270 degrees and make other pages remain the same.

PdfPageBase page = doc.Pages[4];
page.Rotation = PdfPageRotateAngle.RotateAngle270;

Step 3: Save the PDF document and launch the file.

doc.SaveToFile("RotatedLeavesOfGrass.pdf");
System.Diagnostics.Process.Start("RotatedLeavesOfGrass.pdf");

Effective screenshot:

How to rotate a certain page within PDF document in WPF

How to rotate a certain page within PDF document in WPF

Full Codes:

[C#]
using System.Windows;
using Spire.Pdf;

namespace Rotate_PDF_page
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile("LeavesOfGrass.pdf");
            PdfPageBase page = doc.Pages[4];
            page.Rotation = PdfPageRotateAngle.RotateAngle270;
            doc.SaveToFile("RotatedLeavesOfGrass.pdf");
            System.Diagnostics.Process.Start("RotatedLeavesOfGrass.pdf");
        }
    }
}
[VB.NET]
Imports System.Windows
Imports Spire.Pdf

Namespace Rotate_PDF_page
	''' 
	''' Interaction logic for MainWindow.xaml
	''' 
	Public Partial Class MainWindow
		Inherits Window
		Public Sub New()
			InitializeComponent()
		End Sub

		Private Sub button1_Click(sender As Object, e As RoutedEventArgs)
			Dim doc As New PdfDocument()
			doc.LoadFromFile("LeavesOfGrass.pdf")
			Dim page As PdfPageBase = doc.Pages(4)
			page.Rotation = PdfPageRotateAngle.RotateAngle270
			doc.SaveToFile("RotatedLeavesOfGrass.pdf")
			System.Diagnostics.Process.Start("RotatedLeavesOfGrass.pdf")
		End Sub
	End Class
End Namespace
Published in Program Guide WPF

Everyone knows how to open and save a PDF file. Sometimes you run into the situation that your PDF file has one or more blank pages. You want to get rid of the blank page to make you PDF file look more neat. Many people don't know how to do this.

In the following sections, I will demonstrate how to remove blank page from PDF file in WPF very easily and effortlessly.

Here is the original PDF document:

How to remove blank page from PDF file in WPF

The code snippets are as followed:

Step 1: Initialize a new instance of PdfDocument class and load the PDF document from the file.

PdfDocument document = new PdfDocument();
document.LoadFromFile("Tornado.pdf");

Step 2: Traverse the PDF file and detect the content. If the page is blank, then remove it.

for (int i = 0; i < document.Pages.Count; i++)
{
    PdfPageBase originalPage = document.Pages[i];
    if (originalPage.IsBlank())
    {
       document.Pages.Remove(originalPage); 
       i--;
     }
}

Step 3: Save the PDF and launch the file.

document.SaveToFile("Tornadowithoutblankpage.pdf", FileFormat.PDF);
System.Diagnostics.Process.Start("Tornadowithoutblankpage.pdf");

Effective screenshot:

How to remove blank page from PDF file in WPF

Full Codes:

[C#]
using System.Windows;
using Spire.Pdf;
using System.Drawing;

namespace Tornadoes
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            PdfDocument document = new PdfDocument();
            document.LoadFromFile("Tornado.pdf");
            for (int i = 0; i < document.Pages.Count; i++)
            {
                PdfPageBase originalPage = document.Pages[i];
                if (originalPage.IsBlank())
                {
                    document.Pages.Remove(originalPage);
                    i--;
                }
            }
            document.SaveToFile("Tornadoeswithtidypage.pdf", FileFormat.PDF);
            System.Diagnostics.Process.Start("Tornadoeswithtidypage.pdf");

        }
    }
}
[VB.NET]
Imports System.Windows
Imports Spire.Pdf
Imports System.Drawing

Namespace Tornadoes
	''' 
	''' Interaction logic for MainWindow.xaml
	''' 
	Public Partial Class MainWindow
		Inherits Window
		Public Sub New()
			InitializeComponent()
		End Sub

		Private Sub button1_Click(sender As Object, e As RoutedEventArgs)
			Dim document As New PdfDocument()
			document.LoadFromFile("Tornado.pdf")
			For i As Integer = 0 To document.Pages.Count - 1
				Dim originalPage As PdfPageBase = document.Pages(i)
				If originalPage.IsBlank() Then
					document.Pages.Remove(originalPage)
					i -= 1
				End If
			Next
			document.SaveToFile("Tornadoeswithtidypage.pdf", FileFormat.PDF)
			System.Diagnostics.Process.Start("Tornadoeswithtidypage.pdf")

		End Sub
	End Class
End Namespace
Published in Program Guide WPF
Friday, 01 April 2016 08:16

How to Add Attachments to PDF in WPF

In PDF, an attachment is an additional file that is attached to a PDF document. There are many kinds of attachments, such as a document, an image file or other supported file types.

Spire.PDF, as a professional library, enables us to add various attachments as per our needs without having Adobe Acrobat been installed on system. This article demonstrates how to add attachments - a word document and an image to PDF in WPF applications using Spire.PDF for WPF.

Please see the following effective screenshot after adding attachments:

How to Add Attachments to PDF in WPF

Double click the attachment icon, the attached file will be open automatically.

Detail steps:

Use following namespace:

using System;
using System.Drawing;
using System.IO;
using System.Windows;
using Spire.Pdf;
using Spire.Pdf.Annotations;
using Spire.Pdf.Graphics;

Step 1: Load the original PDF document and add a new page to it.

PdfDocument doc = new PdfDocument("Sales Report.pdf");
PdfPageBase page = section.Pages.Add();

Step 2: In the new page, draw a title for the attachments.

float y = 10;
PdfBrush brush1 = PdfBrushes.CornflowerBlue;
PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 16f, System.Drawing.FontStyle.Bold));
PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);
page.Canvas.DrawString("Attachments", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);

Step 3: Load the file that needs to be attached using the File.ReadAllBytes(string path) method, then add the file to the specified page of the PDF document as attachment.

Add Word document attachment with attachment annotation:

PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 12f, System.Drawing.FontStyle.Bold));
PointF location = new PointF(50, y);
String label = "Sales Report";
byte[] data = File.ReadAllBytes("Sales Report.docx");
SizeF size = font2.MeasureString(label);
RectangleF bounds = new RectangleF(location, size);
page.Canvas.DrawString(label, font2, PdfBrushes.MediumPurple, bounds);
bounds = new RectangleF(bounds.Right + 3, bounds.Top, font2.Height / 2, font2.Height);
PdfAttachmentAnnotation annotation1 = new PdfAttachmentAnnotation(bounds, "Sales Report.docx", data);
annotation1.Color = Color.Teal;
annotation1.Flags = PdfAnnotationFlags.NoZoom;
annotation1.Icon = PdfAttachmentIcon.Graph;
annotation1.Text = "Sales Report.docx";
(page as PdfNewPage).Annotations.Add(annotation1);

Add image attachment is similar with adding Word attachment, refer to following codes:

location = new PointF(50, y);
label = "Vendors Info";
data = File.ReadAllBytes("Vendors Info.png");
size = font2.MeasureString(label);
bounds = new RectangleF(location, size);
page.Canvas.DrawString(label, font2, PdfBrushes.DarkOrange, bounds);
bounds = new RectangleF(bounds.Right + 3, bounds.Top, font2.Height / 2, font2.Height);
PdfAttachmentAnnotation annotation2 = new PdfAttachmentAnnotation(bounds, "Vendors Info.png", data);
annotation2.Color = Color.Orange;
annotation2.Flags = PdfAnnotationFlags.ReadOnly;
annotation2.Icon = PdfAttachmentIcon.PushPin;
annotation2.Text = "Vendors info image";
(page as PdfNewPage).Annotations.Add(annotation2);

Step 4: Save and launch the file.

doc.SaveToFile("Attachment.pdf");
System.Diagnostics.Process.Start("Attachment.pdf");

Full codes:

private void button1_Click(object sender, RoutedEventArgs e)
{
    //Load the original PDF document.
    PdfDocument doc = new PdfDocument("Sales Report.pdf");
    //Add a new page
    PdfPageBase page = doc.Pages.Add();

    float y = 10;
    //Set title text
    PdfBrush brush1 = PdfBrushes.CornflowerBlue;
    PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 16f,   System.Drawing.FontStyle.Bold));
    PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);
    page.Canvas.DrawString("Attachments", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);
    y = y + font1.MeasureString("Attachments", format1).Height;
    y = y + 5;

    //Add Word document attachment
    PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 12f, System.Drawing.FontStyle.Bold));
    PointF location = new PointF(50, y);
    String label = "Sales Report";
    byte[] data = File.ReadAllBytes("Sales Report.docx");
    SizeF size = font2.MeasureString(label);
    RectangleF bounds = new RectangleF(location, size);
    page.Canvas.DrawString(label, font2, PdfBrushes.MediumPurple, bounds);
    bounds = new RectangleF(bounds.Right + 3, bounds.Top, font2.Height / 2, font2.Height);
    PdfAttachmentAnnotation annotation1 = new PdfAttachmentAnnotation(bounds, "Sales  Report.docx", data);
    annotation1.Color = Color.Teal;
    annotation1.Flags = PdfAnnotationFlags.NoZoom;
    annotation1.Icon = PdfAttachmentIcon.Graph;
    annotation1.Text = "Sales Report.docx";
    (page as PdfNewPage).Annotations.Add(annotation1);
    y = y + size.Height + 2;

    //Add image attachment
    location = new PointF(50, y);
    label = "Vendors Info";
    data = File.ReadAllBytes("Vendors Info.png");
    size = font2.MeasureString(label);
    bounds = new RectangleF(location, size);
    page.Canvas.DrawString(label, font2, PdfBrushes.DarkOrange, bounds);
    bounds = new RectangleF(bounds.Right + 3, bounds.Top, font2.Height / 2, font2.Height);
    PdfAttachmentAnnotation annotation2 = new PdfAttachmentAnnotation(bounds, "Vendors  Info.png", data);
    annotation2.Color = Color.Orange;
    annotation2.Flags = PdfAnnotationFlags.ReadOnly;
    annotation2.Icon = PdfAttachmentIcon.PushPin;
    annotation2.Text = "Vendors info image";
    (page as PdfNewPage).Annotations.Add(annotation2);

    //Save and launch the file.
    doc.SaveToFile("Attachment.pdf");
    System.Diagnostics.Process.Start("Attachment.pdf");
}
Published in Program Guide WPF

Usually, when you open a PDF document, the blank background looks a little drab. You might want to create background for your PDF document to make them more visually appealing through the using of a background image.

In the following sections, I will demonstrate how to insert PDF background image in WPF.

Here is the original PDF document without background image.

Insert a background image to PDF file in WPF

The code snippets are as followed:

Step 1: Initialize a new instance of PdfDocument class and load the PDF document from the file.

PdfDocument doc = new PdfDocument();
doc.LoadFromFile("To a Skylark.pdf");

Step 2: In this example, we choose the first page of PDF file to insert the background image.

PdfPageBase page = doc.Pages[0];

Step 3: Load the image from file and set it as background image.

System.Drawing.Image backgroundImage = System.Drawing.Image.FromFile("Sky.jpg");
page.BackgroundImage = backgroundImage;

Step 4: Save the PDF document and launch the file.

doc.SaveToFile("With Background Image.pdf");
System.Diagnostics.Process.Start("With Background Image.pdf");

Effective screenshot:

Insert a background image to PDF file in WPF

Full Codes:

[C#]
using System.Windows;
using Spire.Pdf;

namespace Poetic_Works
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile("To a Skylark.pdf");
            PdfPageBase page = doc.Pages[0];
            System.Drawing.Image backgroundImage = System.Drawing.Image.FromFile("Sky.jpg");
            page.BackgroundImage = backgroundImage;
            doc.SaveToFile("With Background Image.pdf");
            System.Diagnostics.Process.Start("With Background Image.pdf");
        }
    }
}
[VB.NET]
Imports System.Windows
Imports Spire.Pdf

Namespace Poetic_Works
	''' 
	''' Interaction logic for MainWindow.xaml
	''' 
	Public Partial Class MainWindow
		Inherits Window
		Public Sub New()
			InitializeComponent()
		End Sub

		Private Sub button2_Click(sender As Object, e As RoutedEventArgs)
			Dim doc As New PdfDocument()
			doc.LoadFromFile("To a Skylark.pdf")
			Dim page As PdfPageBase = doc.Pages(0)

			Dim backgroundImage As System.Drawing.Image = System.Drawing.Image.FromFile("Sky.jpg")
			page.BackgroundImage = backgroundImage
			doc.SaveToFile("With Background Image.pdf")
			System.Diagnostics.Process.Start("With Background Image.pdf")
		End Sub
	End Class
End Namespace
Published in Program Guide WPF
Friday, 25 March 2016 09:09

How to Add Annotation to PDF in WPF

An annotation is a note or comment added to a pdf file, it can be an explanation or a reference to the specific part of the original data. Add annotations can make the file becomes easier to understand for readers.

Spire.PDF enables us to add, edit and delete annotation from a PDF document. This section will demonstrate how to add text annotation and edit annotation in pdf from WPF Applications using Spire.PDF for WPF.

This is the effective screenshot after adding and editing annotation:

Add Annotation to PDF in WPF

After editing, the text content of the annotation changed from “Demo” to “This is an annotation”.

At first, use the following namespace:

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

Then refer to the detail steps below:

Step 1: Create a new PDF document and add a new page to it.

PdfDocument doc = new PdfDocument();
PdfPageBase page = doc.Pages.Add();

Step 2: Draw text in the page and set text font, font size, color and location.

PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 15);
string text = "Spire.PDF";
PdfSolidBrush brush = new PdfSolidBrush(Color.DeepSkyBlue);
PointF point = new PointF(50, 100);
page.Canvas.DrawString(text, font, brush, point);

Step 3: Add annotation.

First, create a text annotation using the PdfTextMarkupAnnotation class:

PdfTextMarkupAnnotation annotation = new PdfTextMarkupAnnotation("Author", "Demo", text, new PointF(0, 0), font);

There are four parameters of the annotation:

“Author”: the author of annotation.
“Demo”: text content of annotation.
text: the text which will be marked.
new PointF(0, 0): not supported at present.
font: the font of the text which will be marked.

Second, Set Border, TextMarkupColor and location of the annotation:

annotation.Border = new PdfAnnotationBorder(0.50f);
annotation.TextMarkupColor = Color.LemonChiffon;
annotation.Location = new PointF(point.X + doc.PageSettings.Margins.Left, point.Y + doc.PageSettings.Margins.Left);

Third, add the annotation to the specified page:

(page as PdfNewPage).Annotations.Add(annotation);

If you need to edit the text of the annotation, then you can use following code:

(page as PdfNewPage).Annotations[0].Text = "This is an annotation";

Step 4: Save and launch the file.

doc.SaveToFile("Annotation.pdf");
System.Diagnostics.Process.Start("Annotation.pdf");

Full codes:

private void button1_Click(object sender, RoutedEventArgs e)
{
    PdfDocument doc = new PdfDocument();
    PdfPageBase page = doc.Pages.Add();
    PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 15);
    string text = "Spire.PDF";
    PdfSolidBrush brush = new PdfSolidBrush(Color.DeepSkyBlue);
    PointF point = new PointF(50, 100);
    page.Canvas.DrawString(text, font, brush, point);
    
    //Add annotation
    PdfTextMarkupAnnotation annotation = new PdfTextMarkupAnnotation("Author", "Demo", text, new PointF(0, 0), font);
    annotation.Border = new PdfAnnotationBorder(0.50f);
    annotation.TextMarkupColor = Color.LemonChiffon;

    annotation.Location = new PointF(point.X + doc.PageSettings.Margins.Left, point.Y + doc.PageSettings.Margins.Left);
(page as PdfNewPage).Annotations.Add(annotation);

    //Edit the text of the annotation
    (page as PdfNewPage).Annotations[0].Text = "This is an annotation";

    doc.SaveToFile("Annotation.pdf");
System.Diagnostics.Process.Start("Annotation.pdf");
}
Published in Program Guide WPF

We often use header to the PDF file to give additional information to the PDF file. With Spire.PDF for WPF, developers can easily use the method SetDocumentTemplate() to create a PDF template that only contains header text and header image. By invoking this method, the template will be applied to all pages in your PDF document. This article will demonstrate how to add a header to PDF in C# on WPF applications.

Note: Before Start, please download the latest version of Spire.PDF and add Spire.Pdf.Wpf.dll in the bin folder as the reference of Visual Studio.

Step 1: Create a new PDF document, set its margin and load from file.

PdfDocument doc = new PdfDocument();
doc.PageSettings.Margins.All = 0;
PdfPageBase page = null;
PdfDocument original = new PdfDocument();
original.LoadFromFile("Test.pdf");

Step 2: Create a SetDocumentTemplate() method to add header text.

SetDocumentTemplate(doc, PdfPageSize.A4, original.PageSettings.Margins);

Step 3: Traverse every page of the original PDF document and create a new page with the original contents.

foreach (PdfPageBase origianlPage in original.Pages)
{
    page = doc.Pages.Add(new SizeF(origianlPage.Size.Width, origianlPage.Size.Height));
    origianlPage.CreateTemplate().Draw(page, 0, -(original.PageSettings.Margins.Top));
}

Step 4: Save the document to file and launch to preview it.

doc.SaveToFile("output.pdf");
System.Diagnostics.Process.Start("output.pdf");

Step 5: Details of how to add the header text to the PDF.

private static void SetDocumentTemplate(PdfDocument doc, SizeF pageSize, PdfMargins margin)
{
    PdfPageTemplateElement topSpace = new PdfPageTemplateElement(pageSize.Width, margin.Top);
    topSpace.Foreground = true;
    doc.Template.Top = topSpace;
    PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Trebuchet MS", 14f, System.Drawing.FontStyle.Italic));
    String label = "This is a PDF text header";
    SizeF size = font1.MeasureString(label);
    float y = 0;
    float x = 0;
    topSpace.Graphics.DrawString(label, font1, PdfBrushes.PaleVioletRed, x, y);
}

Effective screenshot:

How to add header to PDF on WPF applications

Full codes:

private void button1_Click(object sender, RoutedEventArgs e)
 {
     // Create a pdf document.
     PdfDocument doc = new PdfDocument();
     doc.PageSettings.Margins.All = 0;
     PdfPageBase page = null;
     PdfDocument original = new PdfDocument();

     original.LoadFromFile("Test.pdf");

     SetDocumentTemplate(doc, PdfPageSize.A4, original.PageSettings.Margins);
     foreach (PdfPageBase origianlPage in original.Pages)
     {
         page = doc.Pages.Add(new SizeF(origianlPage.Size.Width, origianlPage.Size.Height));
         origianlPage.CreateTemplate().Draw(page, 0, -(original.PageSettings.Margins.Top));

     }

     doc.SaveToFile("output.pdf");
     System.Diagnostics.Process.Start("output.pdf");

 }
 private static void SetDocumentTemplate(PdfDocument doc, SizeF pageSize, PdfMargins margin)
 {
     PdfPageTemplateElement topSpace = new PdfPageTemplateElement(pageSize.Width, margin.Top);
     topSpace.Foreground = true;
     doc.Template.Top = topSpace;
     PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Trebuchet MS", 14f, System.Drawing.FontStyle.Italic));
     String label = "This is a PDF text header";
     SizeF size = font1.MeasureString(label);
     float y = 0;
     float x = 0;
     topSpace.Graphics.DrawString(label, font1, PdfBrushes.PaleVioletRed, x, y);
 }
Published in Program Guide WPF

We often use shape to the PDF file to make it obvious and show the data clearly. With Spire.PDF for WPF, developers can easily use the object Spire.Pdf.PdfPageBase.Canvas to add different kind of shapes, such as rectangle, circle and Ellipse, etc. This article will demonstrate how to add shapes to PDF in C# on WPF applications.

Note: Before Start, please download the latest version of Spire.PDF and add Spire.Pdf.Wpf.dll in the bin folder as the reference of Visual Studio.

Here comes to the steps of how to add shapes to PDF file in C#:

Step 1: Create a new PDF document and add a page to it.

PdfDocument pdfDoc = new PdfDocument();
PdfPageBase page = pdfDoc.Pages.Add();

Step 2: Save graphics state.

PdfGraphicsState state = page.Canvas.Save();

Step 3: Set the color for the shapes.

PdfPen pen = new PdfPen(System.Drawing.Color.ForestGreen, 0.1f);
PdfPen pen1 = new PdfPen(System.Drawing.Color.Red, 3f);
PdfBrush brush = new PdfSolidBrush(System.Drawing.Color.DeepSkyBlue);

Step 4: Draw shapes and set the position for them.

page.Canvas.DrawRectangle(pen, new System.Drawing.Rectangle(new System.Drawing.Point(2, 22), new System.Drawing.Size(120, 120)));
page.Canvas.DrawPie(pen1, 150, 30, 100, 90, 360, 360);
page.Canvas.DrawEllipse(brush, 350, 40, 20, 60);

Step 5: Restore graphics.

page.Canvas.Restore(state);

Step 6: Save the PDF document to file.

pdfDoc.SaveToFile("Shapes.pdf");

Effective screenshots of the adding shapes to PDF file:

How to add shapes to PDF on WPF applications

Full codes:

private void button1_Click(object sender, RoutedEventArgs e)
{
    PdfDocument pdfDoc = new PdfDocument();
    PdfPageBase page = pdfDoc.Pages.Add();
    PdfGraphicsState state = page.Canvas.Save();
    PdfPen pen = new PdfPen(System.Drawing.Color.ForestGreen, 0.1f);
    PdfPen pen1 = new PdfPen(System.Drawing.Color.Red, 3f);
    PdfBrush brush = new PdfSolidBrush(System.Drawing.Color.DeepSkyBlue);

    //draw rectangle
    page.Canvas.DrawRectangle(pen, new System.Drawing.Rectangle(new System.Drawing.Point(2, 22), new System.Drawing.Size(120, 120)));
    //draw circle
    page.Canvas.DrawPie(pen1, 150, 30, 100, 90, 360, 360);
    //draw ellipse
    page.Canvas.DrawEllipse(brush, 350, 40, 20, 60);
    
    page.Canvas.Restore(state);
    pdfDoc.SaveToFile("Shapes.pdf");
}
Published in Program Guide WPF
Page 1 of 3