Graphics state

Docotic.Pdf Library Help > Samples > Graphics > Graphics state

This sample shows how to save and restore graphics state using PdfCanvas.SaveState and PdfCanvas.RestoreState methods.

PdfCanvas maintains a set of properties, such as pen, brush, current positions for text and graphics, font, e.t.c. This set of properties is called graphics state.

Current graphics state can be saved and previously saved state can be restored. Use PdfCanvas.SaveState() method to save current graphics state and PdfCanvas.RestoreState() method to restore last saved graphics state.

CopyC#
using System.Diagnostics;
using System.Drawing;

namespace BitMiracle.Docotic.Pdf.Samples
{
    public static class GraphicsState
    {
        public static void Main()
        {
            // NOTE: 
            // When used in trial mode, the library imposes some restrictions.
            // Please visit http://bitmiracle.com/pdf-library/trial-restrictions.aspx
            // for more information.

            PdfDocument pdf = new PdfDocument();

            PdfCanvas canvas = pdf.Pages[0].Canvas;
            canvas.SaveState();

            canvas.Pen.Width = 3;
            canvas.Pen.DashPattern = new PdfDashPattern(new double[] { 5, 3 }, 2);

            canvas.CurrentPosition = new PdfPoint(20, 60);
            canvas.DrawLineTo(150, 60);

            canvas.RestoreState();

            canvas.CurrentPosition = new PdfPoint(20, 80);
            canvas.DrawLineTo(150, 80);

            string pathToFile = "GraphicsState.pdf";
            pdf.Save(pathToFile);
            pdf.Dispose();

            Process.Start(pathToFile);
        }
    }
}
CopyVB.NET
Imports System.Diagnostics
Imports System.Drawing

Imports BitMiracle.Docotic.Pdf

Namespace BitMiracle.Docotic.Pdf.Samples
    Public NotInheritable Class GraphicsState
        Public Shared Sub Main()
            ' NOTE: 
            ' When used in trial mode, the library imposes some restrictions.
            ' Please visit http://bitmiracle.com/pdf-library/trial-restrictions.aspx
            ' for more information.


            Dim pdf As New PdfDocument()

            Dim canvas As PdfCanvas = pdf.Pages(0).Canvas
            canvas.SaveState()

            canvas.Pen.Width = 3
            canvas.Pen.DashPattern = New PdfDashPattern(New Single() {5, 3}, 2)

            canvas.CurrentPosition = New PdfPoint(20, 60)
            canvas.DrawLineTo(150, 60)

            canvas.RestoreState()

            canvas.CurrentPosition = New PdfPoint(20, 80)
            canvas.DrawLineTo(150, 80)

            Dim pathToFile As String = "GraphicsState.pdf"
            pdf.Save(pathToFile)
            pdf.Dispose()

            Process.Start(pathToFile)
        End Sub
    End Class
End Namespace