Share via


How to add a Publishing Page in SharePoint 2013 using Client Object Model

This blog post explains how to create/add publishing pages to a Publishing Site in SharePoint 2013 using the managed Client Object Model (CSOM) . We will be using the Microsoft.SharePoint.Client.Publishing DLL to achieve this. The Microsoft.SharePoint.Client.Publishing namespace will be used in the below sample.

 

Code Sample:

 

The below method takes the ClientContext object and the name of the page to be created as parameters. It gets the reference of publishing web from the current web and creates a publishing page in the web.

 

public void AddPublishingPage(ClientContext context, string pageName)

{

// Get current web

Web webSite = context.Web;

context.Load(webSite);

PublishingWeb web = PublishingWeb.GetPublishingWeb(context, webSite);

context.Load(web);

 

if (web != null)

{

// Get Pages Library

List pages = context.Site.RootWeb.Lists.GetByTitle("Pages");

ListItemCollection existingPages = pages.GetItems(CamlQuery.CreateAllItemsQuery());

context.Load(existingPages, items => items.Include(item => item.DisplayName).Where(obj => obj.DisplayName == pageName));

context.ExecuteQuery();

// Check if page already exists

if (existingPages != null && existingPages.Count > 0)

{

// Page already exists

}

else

{

// Get Publishing Page Layouts

List publishingLayouts = context.Site.RootWeb.Lists.GetByTitle("Master Page Gallery");

ListItemCollection allItems = publishingLayouts.GetItems(CamlQuery.CreateAllItemsQuery());

context.Load(allItems, items => items.Include(item => item.DisplayName).Where(obj => obj.DisplayName == "BlankWebPartPage"));

context.ExecuteQuery();

ListItem layout = allItems.Where(x => x.DisplayName == "BlankWebPartPage").FirstOrDefault();

context.Load(layout);

// Create a publishing page

PublishingPageInformation publishingPageInfo = newPublishingPageInformation();

publishingPageInfo.Name = pageName;

publishingPageInfo.PageLayoutListItem = layout;

PublishingPage publishingPage = web.AddPublishingPage(publishingPageInfo);

publishingPage.ListItem.File.CheckIn(string.Empty, CheckinType.MajorCheckIn);

publishingPage.ListItem.File.Publish(string.Empty);

publishingPage.ListItem.File.Approve(string.Empty);

context.Load(publishingPage);

context.Load(publishingPage.ListItem.File, obj => obj.ServerRelativeUrl);

context.ExecuteQuery();

}

}

}