You are hereBlogs / Niral's blog / Create a SharePoint 2007 publishing page programmatically

Create a SharePoint 2007 publishing page programmatically


This is a simple code to create a SharePoint (MOSS) 2007 Publishing page with code. Hope this helps  
// Get the SPSite - getting the current site for examples sake
SPSite cursite = SPContext.Current.Site;

using (SPWeb curweb = cursite.OpenWeb())

{
    // Get the Pages library of the web
    SPList pagelist = curweb.Lists["Pages"];

    //content type assigned to the pages library
    SPContentType contentType = pubSite.ContentTypes["ContentType Name"];
 
    //page layouts for the content type
    PageLayoutCollection pageLayouts = pubSite.GetPageLayouts(contentType, true);

    Dictionary<string, PageLayout> dPageLayouts = new Dictionary<string, PageLayout>();

    foreach (PageLayout pageLayout in pageLayouts)
    {
        dPageLayouts.Add(pageLayout.Title, pageLayout);
    } 

    //page layout that is required for the new page
    PageLayout pageLayoutToUse = dPageLayouts["layoutName"];

    //publishing web from the currently open web
    PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(curweb);

    //add a new page
    PublishingPage newPubPage = pubWeb.GetPublishingPages().Add("newPageName.aspx", pageLayoutToUse);

    //put what ever content you want in the page.
    SPListItem newPage = newPubPage.ListItem;
    newPage["Title"] = "New Page Title";
    newPage["content"] = "<span><b>here's some new content</b></span>";
    newPage.Update();

    //check the file in and publish it
    newPage.File.CheckIn("Autocreated");
    newPage.File.Publish("Autocreated");

    try
    {
        //This will throw an exception if Approval is not enabled on the pages library
        newPage.File.Approve("Autocreated");
    }
    catch

    {       
    }
}
 Was looking for something like this. Thanks, Alvin
Great Article, It actually helped me programmatically migrate current area SPS2003 area to Publishing pages in MOSS... particulary the File.CheckIn and CheckOut issues. Cheers Sal