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. Now developers can easily add page layers by using class PdfPageLayer offered by Spire.PDF. This article will focus on showing how to add layers to a PDF file in C# with the help of Spire.PDF.
Note: Before Start, please download the latest version of Spire.PDF and add Spire.PDF.dll in the bin folder as the reference of Visual Studio.
Here comes to the details:
Step 1: Create a new PDF document
PdfDocument pdfdoc = new PdfDocument();
Step 2: Add a new page to the PDF document.
PdfPageBase page = pdfdoc.Pages.Add();
Step 3: Add a layer named "red line" to the PDF page.
PdfPageLayer layer = page.PageLayers.Add("red line");
Step 4: Draw a red line to the added layer.
layer.Graphics.DrawLine(new PdfPen(PdfBrushes.Red, 1), new PointF(0, 100), new PointF(300, 100));
Step 5: Use the same method above to add the other two layers to the PDF page.
layer = page.PageLayers.Add("blue line"); layer.Graphics.DrawLine(new PdfPen(PdfBrushes.Blue, 1), new PointF(0, 200), new PointF(300, 200)); layer = page.PageLayers.Add("green line"); layer.Graphics.DrawLine(new PdfPen(PdfBrushes.Green, 1), new PointF(0, 300), new PointF(300, 300));
Step 6: Save the document to file.
pdfdoc.SaveToFile("AddLayers.pdf", FileFormat.PDF);
Effective screenshot:
Full codes:
using Spire.Pdf; using Spire.Pdf.Graphics; using System.Drawing; namespace AddLayer { class Program { static void Main(string[] args) { PdfDocument pdfdoc = new PdfDocument(); PdfPageBase page = pdfdoc.Pages.Add(); PdfPageLayer layer = page.PageLayers.Add("red line"); layer.Graphics.DrawLine(new PdfPen(PdfBrushes.Red, 1), new PointF(0, 100), new PointF(300, 100)); layer = page.PageLayers.Add("blue line"); layer.Graphics.DrawLine(new PdfPen(PdfBrushes.Blue, 1), new PointF(0, 200), new PointF(300, 200)); layer = page.PageLayers.Add("green line"); layer.Graphics.DrawLine(new PdfPen(PdfBrushes.Green, 1), new PointF(0, 300), new PointF(300, 300)); pdfdoc.SaveToFile("AddLayers.pdf", FileFormat.PDF); } } }