从sharepoint读取的word文档中删除内容控件

时间:2012-09-11 08:06:22

标签: c# sharepoint openxml xmldocument contentcontrol

我在word文档中有一个带有文本草稿的contentcontrol。 在sharepoint中有一个应用程序页面可以从word文档生成pdf文档,但是我必须删除该草稿文本。 草案文本也在一个名为draft的内容控件中。我不能使用office API,它必须使用OpenXML,我已经阅读过关于OpenXMLHelper和方法RemoveContentCOntrolANdKeepContents但该代码非常令人困惑,所以我不确定该怎么做。

我需要完成以下代码,

protected void Page_Load(object sender, EventArgs e)
        {
            Logger.LogDebug("ConvertToPdf", "Page_Load(object sender, EventArgs e)", "BEGIN");

            string source = Request.QueryString["Source"];
            string messageSource = Request.Url.ToString();
            int id = Convert.ToInt32(Request.QueryString["ID"]);
            string state = Request.GetQueryStringValue(MeetingsCommon.Constants.QUERYSTRINGPARAMETER_STATE_NAME);
            string statusMessage = Request.GetQueryStringValue(MeetingsCommon.Constants.QUERYSTRINGPARAMETER_MESSAGE_NAME);
            this.litMessage.Text = statusMessage;

            if (!string.IsNullOrEmpty(state))
                return;

            using (SPLongOperation operation = new SPLongOperation(this.Page))
            {
                try
                {
                    operation.Begin();
                    SPWeb currentWeb = SPContext.Current.Web;
                    SPSite currentSite = currentWeb.Site;
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite elevatedSite = new SPSite(source))
                        {
                            using (SPWeb elevatedWeb = elevatedSite.OpenWeb())
                            {
                                elevatedWeb.AllowUnsafeUpdates = true;
                                SPList drafts = elevatedWeb.GetSafeListByName(MeetingsCommon.Constants.LISTS_HIDDENCONVERSION_NAME);
                                SPDocumentLibrary draftsDL = elevatedWeb.GetSafeDocumentLibraryByName(MeetingsCommon.Constants.LISTS_HIDDENCONVERSION_NAME);

                                SPListItem item = drafts.GetItemById(id);

                                ConversionJobSettings pdfConversionJobSettings = new ConversionJobSettings();
                                pdfConversionJobSettings.OutputFormat = SaveFormat.PDF;
                                pdfConversionJobSettings.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite;

                                string serviceName = "Word Automation Services";
                                ConversionJob pdfConversionJob = new ConversionJob(serviceName, pdfConversionJobSettings);
                                pdfConversionJob.UserToken = elevatedWeb.CurrentUser.UserToken;

                                string docxFile = elevatedWeb.Url + "/" + item.Url;
                                string pdfFile = docxFile.Replace("docx", "pdf");
                                SPList destinationList = null;


                                pdfConversionJob.AddFile(docxFile, pdfFile);
                                Stream document = draftsDL.GetDocumentTemplate(item.Name);
                                RemoveDraft(document);




private void RemoveDraft(Stream wordFile)
        {
            Logger.LogDebug("GenerateRefuseLetter", "BuildDocument(Stream templateFile, RefuseLetter refuseLetter)", "BEGIN");
            Stream returnValue = null;
            try
            {
                using (Package package = Package.Open(wordFile, FileMode.Open, FileAccess.ReadWrite))
                {
                    string relationshipType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";

                    //  Get the main document part (workbook.xml, document.xml, presentation.xml).
                    var relationShipCollection = package.GetRelationshipsByType(relationshipType);
                    if (relationShipCollection.Count() == 0)
                        throw new Exception(string.Format("Could not find a relationship with type:{0} in the package", relationshipType));

                    //  There should only be one document part in the package. 
                    PackageRelationship relationship = relationShipCollection.First();

                    Uri documentUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), relationship.TargetUri);
                    PackagePart documentPart = package.GetPart(documentUri);

                    Uri uriData = null;

                    List<Uri> lstPackageParts = new List<Uri>();
                    foreach (PackagePart p in package.GetParts())
                    {
                        XmlDocument doc = new XmlDocument();
                        doc.Load(p.GetStream());


                    }

                }
            }
            catch(Exception ex)
            {
                    throw ex;
            }        
        }

1 个答案:

答案 0 :(得分:2)

假设您有单个内容控件,其类型为SdtRun,则在保留文本的同时删除内容控件的示例代码可以

using (WordprocessingDocument wordProcessingDocument = WordprocessingDocument.Open(stream, true))
            {
                SdtRun sdtRun = wordProcessingDocument.MainDocumentPart.Document.Body.Descendants<SdtRun>().FirstOrDefault();

                if (sdtRun != null)
                {
                    foreach (var elem in sdtRun.SdtContentRun.Elements())
                    {
                        sdtRun.Parent.InsertBefore(elem.CloneNode(true), sdtRun);
                    }

                    sdtRun.Remove();

                    wordProcessingDocument.MainDocumentPart.Document.Save();
                }                    
            }