Programmatically Create publishing page sharepoint 2010

The code below will add a new publishing page and will check it in so that gets visible to the users. To do this you will need to reference Microsoft.SharePoint.Publishing in your project.

Code snippet :

using(PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(web))
{

PageLayout myLayout = pWeb.GetAvailablePageLayouts()["Page Layout Name"];

PublishingPage newPage = pWeb.GetPublishingPages().Add("NewPage.aspx", myLayout);

newPage.Update(); // commit to the database

}

// apply the HTML properties

SPFile file = web.GetFile(newPage.Url);

SPListItem item = file.Item;

item["Title"] = "New Page Title";

item["Page Content"] = "

Some Text in the new page

";

item.Update(); // save changes

//Check in the Page
file.CheckIn("Created programmatically");


If you want to auto-approve and publish the page, then you could use the following in addition

file.Approve("Approved programmatically");

file.Publish("Published programmatically");

4 comments:

  1. you wrote:
    ___
    PageLayout myLayout = pWeb.GetAvailablePageLayouts()["Page Layout Name"];
    ___

    GetAvailablePageLayouts returns array, and i can't access to item of it via Page Layout Name, but only by integer number.

    Is it your mistake or mine?

    ReplyDelete
  2. where do you write this code to make it work? could you please explain in more detail ?

    ReplyDelete
  3. Use System.Linq and try:
    PageLayout myLayout = pWeb.GetAvailablePageLayouts.First(l => l.Title == "Page Layout Title");

    Afterwards check myLayout == null.

    ReplyDelete
  4. Ups, use pWeb.GetAvailablePageLayouts.FirstOrDefault() or you'll not get null if not available ;-)

    ReplyDelete

Disclaimer

This is a personal weblog. The opinions expressed here represent my own and not those of my employer or anyone else. Should you have any questions or concerns please e-mail me at sharepointprogrammingblogger@gmail.com .

Copyright (c) 2010 @ myshaepointwork.blogspot.com. All rights are reserved.Do Not Copy.

@ Learning SharePoint.com