I’m working with a client who needs to migrate content from MCMS2002 to MOSS by NOT using the out-of-box migration tools.  While that’s a story worthy of a whole new blog, one of the problems I came across was the need to create publishing pages from scratch using the object model.  It’s really not that hard at all – you just need to use some of the features of the new Microsoft.SharePoint.Publishing assembly. 

Here’s the code to get it done…

//get the current top level site as publishing web so you can get the available page layouts for the known content type
PublishingSite pubSite = new PublishingSite(SPContext.Current.Site);

//get the site content type that contains the page layout you want to use
SPContentType contentType = pubSite.ContentTypes[“Custom Page Layout Content Type”];           

//get the page layouts for the content type
PageLayoutCollection pageLayouts = pubSite.GetPageLayouts(contentType, true);           

//I like refering to the page layouts by title, so I shove them into a generic dictionary           
Dictionary<string, PageLayout> dPageLayouts = new Dictionary<string, PageLayout>();
foreach (PageLayout pageLayout in pageLayouts)
    dPageLayouts.Add(pageLayout.Title, pageLayout);           

//get the page layout you want to use
PageLayout pageLayoutToUse = dPageLayouts[“layoutName”];

//get the current publishing web
PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(SPContext.Current.Web);

//create a new publishing page in the web
PublishingPage newPubPage = pubWeb.GetPublishingPages().Add(“newPageName.aspx”, pageLayoutToUse);

//set properties and placeholder content just like you would if you were adding a new file to a document library
SPListItem newPage = newPubPage.ListItem;
newPage[“Title”] = “New Page Title”;
newPage[“content”] = “<span><b>here’s some new content</b></span>”;

//check the file in and publish it
newPage.File.CheckIn(“Checked in on creation”);
newPage.File.Publish(“Published on creation”);

    //this is a hack that ensures if the site has workflow turned on, the new page will get approved
    newPage.File.Approve(“Approved on creation”);
    //approval is not enabled