How to Create a Modern Pages Programmatically in SharePoint Office 365 using Patterns and Practice (OfficeDevPNP)

Sathish Nadarajan
SharePoint MVP
Published On :   02 May 2018
Visit Count
Today :  2    Total :   2110

In the earlier article, we saw how to create the modern site programmatically. As a follow up, we need to create the pages and add the desired webparts based on the requirement.

The below piece of code, will create the pages and add the default webparts on it.

 static void Main(string[] args)
             string siteUrl = "https://*****";
             string userName = "sathish@****";
             string password = "***";
             OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
             #region O365
             using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
                 Web web = ctx.Web;
                 ctx.Load(web, w => w.SupportedUILanguageIds);
 //Create the Page
 var page2 = ctx.Web.AddClientSidePage("PageWithSections.aspx", true);
                 page2.AddSection(CanvasSectionTemplate.ThreeColumn, 5);
                 //page2.AddSection(CanvasSectionTemplate.TwoColumn, 10);
 // Initialize the WEbpart
                 ClientSideWebPart videoEmbedWp = page2.InstantiateDefaultWebPart(DefaultClientSideWebParts.VideoEmbed);
 //The below are the sample video webpart properties which I have given.  We can add any OOB webpart like this.
                 videoEmbedWp.Properties["videoSource"] = "";
                 videoEmbedWp.Properties["captionText"] = "My video";
                 videoEmbedWp.Properties["showInfo"] = false;
                 videoEmbedWp.Properties["embedCode"] = "<iframe width=853 height=480 src=';width=853&amp;height=480&amp;autoPlay=false&amp;showInfo=true' allowfullscreen></iframe>";
                 videoEmbedWp.Title = "Associated video";
 //Get the section
                 CanvasSection section = page2.Sections[1];
 //Add the webpart to the section
                 page2.AddControl(videoEmbedWp, section.Columns[1], 0);

Happy Coding,

Sathish Nadarajan.