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

2016-05-13 08:10:39 Written by  support iceblue
Rate this item
(0 votes)

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"); 
}

Additional Info

  • tutorial_title: Add Different Types of Layers to a PDF File in WPF
Last modified on Friday, 24 September 2021 09:55