How to add and delete layer in PDF

Developers can use PDF layer to set some content to be visible and others to be invisible in the same PDF file. It makes the PDF Layer widely be used to deal with related contents within the same PDF. With Spire.PDF, we can add several kinds of layers such as line, image, string, ellipse, rectangle and pie to any page of a new or an existing pdf document. At the same time, it also supports us to delete specific layer from a pdf document.

This article will show you how to use Spire.PDF (from version 3.9.360 or above) to add and remove the layers and set the visibility of the layer in C#. If you use the version older than 3.9.360, please refer to the articles of how to add PDF layer, delete layer and toggle the visibility of PDF layer in C#.

Add PDF Layer and toggle the visibility

How to add and delete layer in PDF

//create a new PDF document
PdfDocument doc = new PdfDocument();

//add a new page to the PDF document.
PdfPageBase page = doc.Pages.Add();

//add a layer named "red line"
PdfLayer layer = doc.Layers.AddLayer("red line");
PdfCanvas pcA = layer.CreateGraphics(doc.Pages[0].Canvas);
pcA.DrawLine(new PdfPen(PdfBrushes.Red, 1), new PointF(0, 100), new PointF(100, 100));

//add a layer named "Ellipse" and toggle the visibility as On
layer = doc.Layers.AddLayer("Ellipse", PdfVisibility.On);
PdfCanvas pcB = layer.CreateGraphics(doc.Pages[0].Canvas);
PdfPen pen = new PdfPen(Color.Green, 1f);
PdfBrush brush = new PdfSolidBrush(Color.Green);
pcB.DrawEllipse(pen,brush, 100,120,200,60 );
//add a layer named "Blue line" and toggle the visibility as OFF
layer = doc.Layers.AddLayer("Blue line",PdfVisibility.Off);
PdfCanvas pcC = layer.CreateGraphics(doc.Pages[0].Canvas);
pcC.DrawLine(new PdfPen(PdfBrushes.Blue, 1), new PointF(0, 200), new PointF(100, 200));

//save the document to file
doc.SaveToFile("AddLayers.pdf", FileFormat.PDF)

Delete PDF Layer

How to add and delete layer in PDF

//create a new PDF document and load the document from file
PdfDocument doc = new PdfDocument();

//Delete the layer named “red line”
doc.Layers.RemoveLayer(("red line"));

//save the document to file
doc.SaveToFile("DeleteLayer.pdf", FileFormat.PDF);