Example #1
0
        /// <summary>
        /// add a new part that needs a relationship id
        /// </summary>
        /// <param name="document"></param>
        public static void AddNewPart(string document)
        {
            // Create a new word processing document.
            WordprocessingDocument wordDoc = WordprocessingDocument.Create(document, WordprocessingDocumentType.Document);

            // Add the MainDocumentPart part in the new word processing document.
            var mainDocPart = wordDoc.AddNewPart <MainDocumentPart>("application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", "rId1");

            mainDocPart.Document = new Document();

            // Add the CustomFilePropertiesPart part in the new word processing document.
            var customFilePropPart = wordDoc.AddCustomFilePropertiesPart();

            customFilePropPart.Properties = new DocumentFormat.OpenXml.CustomProperties.Properties();

            // Add the CoreFilePropertiesPart part in the new word processing document.
            var coreFilePropPart = wordDoc.AddCoreFilePropertiesPart();

            using (XmlTextWriter writer = new XmlTextWriter(coreFilePropPart.GetStream(FileMode.Create), System.Text.Encoding.UTF8))
            {
                writer.WriteRaw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<cp:coreProperties xmlns:cp=\"http://schemas.openxmlformats.org/package/2006/metadata/core-properties\"></cp:coreProperties>");
                writer.Flush();
            }

            // Add the DigitalSignatureOriginPart part in the new word processing document.
            wordDoc.AddNewPart <DigitalSignatureOriginPart>("rId4");

            // Add the ExtendedFilePropertiesPart part in the new word processing document.
            var extendedFilePropPart = wordDoc.AddNewPart <ExtendedFilePropertiesPart>("rId5");

            extendedFilePropPart.Properties = new DocumentFormat.OpenXml.ExtendedProperties.Properties();

            // Add the ThumbnailPart part in the new word processing document.
            wordDoc.AddNewPart <ThumbnailPart>("image/jpeg", "rId6");

            wordDoc.Close();
        }
        private static void CopyStartingParts(WordprocessingDocument sourceDocument, WordprocessingDocument newDocument,
            List<ImageData> images)
        {
            // A Core File Properties part does not have implicit or explicit relationships to other parts.
            CoreFilePropertiesPart corePart = sourceDocument.CoreFilePropertiesPart;
            if (corePart != null && corePart.GetXDocument().Root != null)
            {
                newDocument.AddCoreFilePropertiesPart();
                XDocument newXDoc = newDocument.CoreFilePropertiesPart.GetXDocument();
                newXDoc.Declaration.Standalone = "yes";
                newXDoc.Declaration.Encoding = "UTF-8";
                XDocument sourceXDoc = corePart.GetXDocument();
                newXDoc.Add(sourceXDoc.Root);
            }

            // An application attributes part does not have implicit or explicit relationships to other parts.
            ExtendedFilePropertiesPart extPart = sourceDocument.ExtendedFilePropertiesPart;
            if (extPart != null)
            {
                OpenXmlPart newPart = newDocument.AddExtendedFilePropertiesPart();
                XDocument newXDoc = newDocument.ExtendedFilePropertiesPart.GetXDocument();
                newXDoc.Declaration.Standalone = "yes";
                newXDoc.Declaration.Encoding = "UTF-8";
                newXDoc.Add(extPart.GetXDocument().Root);
            }

            // An custom file properties part does not have implicit or explicit relationships to other parts.
            CustomFilePropertiesPart customPart = sourceDocument.CustomFilePropertiesPart;
            if (customPart != null)
            {
                newDocument.AddCustomFilePropertiesPart();
                XDocument newXDoc = newDocument.CustomFilePropertiesPart.GetXDocument();
                newXDoc.Declaration.Standalone = "yes";
                newXDoc.Declaration.Encoding = "UTF-8";
                newXDoc.Add(customPart.GetXDocument().Root);
            }

            DocumentSettingsPart oldSettingsPart = sourceDocument.MainDocumentPart.DocumentSettingsPart;
            if (oldSettingsPart != null)
            {
                DocumentSettingsPart newSettingsPart = newDocument.MainDocumentPart.AddNewPart<DocumentSettingsPart>();
                XDocument settingsXDoc = oldSettingsPart.GetXDocument();
                AddRelationships(oldSettingsPart, newSettingsPart, new[] { settingsXDoc.Root });
                CopyFootnotesPart(sourceDocument, newDocument, settingsXDoc, images);
                CopyEndnotesPart(sourceDocument, newDocument, settingsXDoc, images);
                XDocument newXDoc = newDocument.MainDocumentPart.DocumentSettingsPart.GetXDocument();
                newXDoc.Declaration.Standalone = "yes";
                newXDoc.Declaration.Encoding = "UTF-8";
                newXDoc.Add(settingsXDoc.Root);
                CopyRelatedPartsForContentParts(oldSettingsPart, newSettingsPart, new[] { newXDoc.Root }, images);
            }

            WebSettingsPart oldWebSettingsPart = sourceDocument.MainDocumentPart.WebSettingsPart;
            if (oldWebSettingsPart != null)
            {
                WebSettingsPart newWebSettingsPart = newDocument.MainDocumentPart.AddNewPart<WebSettingsPart>();
                XDocument settingsXDoc = oldWebSettingsPart.GetXDocument();
                AddRelationships(oldWebSettingsPart, newWebSettingsPart, new[] { settingsXDoc.Root });
                XDocument newXDoc = newDocument.MainDocumentPart.WebSettingsPart.GetXDocument();
                newXDoc.Declaration.Standalone = "yes";
                newXDoc.Declaration.Encoding = "UTF-8";
                newXDoc.Add(settingsXDoc.Root);
            }

            ThemePart themePart = sourceDocument.MainDocumentPart.ThemePart;
            if (themePart != null)
            {
                ThemePart newThemePart = newDocument.MainDocumentPart.AddNewPart<ThemePart>();
                XDocument newXDoc = newDocument.MainDocumentPart.ThemePart.GetXDocument();
                newXDoc.Declaration.Standalone = "yes";
                newXDoc.Declaration.Encoding = "UTF-8";
                newXDoc.Add(themePart.GetXDocument().Root);
                CopyRelatedPartsForContentParts(themePart, newThemePart, new[] { newThemePart.GetXDocument().Root }, images);
            }

            // If needed to handle GlossaryDocumentPart in the future, then
            // this code should handle the following parts:
            //   MainDocumentPart.GlossaryDocumentPart.StyleDefinitionsPart
            //   MainDocumentPart.GlossaryDocumentPart.StylesWithEffectsPart

            // A Style Definitions part shall not have implicit or explicit relationships to any other part.
            StyleDefinitionsPart stylesPart = sourceDocument.MainDocumentPart.StyleDefinitionsPart;
            if (stylesPart != null)
            {
                newDocument.MainDocumentPart.AddNewPart<StyleDefinitionsPart>();
                XDocument newXDoc = newDocument.MainDocumentPart.StyleDefinitionsPart.GetXDocument();
                newXDoc.Declaration.Standalone = "yes";
                newXDoc.Declaration.Encoding = "UTF-8";
                newXDoc.Add(stylesPart.GetXDocument().Root);
            }

            // A StylesWithEffects part shall not have implicit or explicit relationships to any other part.
            StylesWithEffectsPart stylesWithEffectsPart = sourceDocument.MainDocumentPart.StylesWithEffectsPart;
            if (stylesWithEffectsPart != null)
            {
                newDocument.MainDocumentPart.AddNewPart<StylesWithEffectsPart>();
                XDocument newXDoc = newDocument.MainDocumentPart.StylesWithEffectsPart.GetXDocument();
                newXDoc.Declaration.Standalone = "yes";
                newXDoc.Declaration.Encoding = "UTF-8";
                newXDoc.Add(stylesWithEffectsPart.GetXDocument().Root);
            }

            // Note: Do not copy the numbering part.  For every source, create new numbering definitions from
            // scratch.
            //NumberingDefinitionsPart numberingPart = sourceDocument.MainDocumentPart.NumberingDefinitionsPart;
            //if (numberingPart != null)
            //{
            //    newDocument.MainDocumentPart.AddNewPart<NumberingDefinitionsPart>();
            //    XDocument newXDoc = newDocument.MainDocumentPart.NumberingDefinitionsPart.GetXDocument();
            //    newXDoc.Declaration.Standalone = "yes";
            //    newXDoc.Declaration.Encoding = "UTF-8";
            //    newXDoc.Add(numberingPart.GetXDocument().Root);
            //    newXDoc.Descendants(W.numIdMacAtCleanup).Remove();
            //}

            // A Font Table part shall not have any implicit or explicit relationships to any other part.
            FontTablePart fontTablePart = sourceDocument.MainDocumentPart.FontTablePart;
            if (fontTablePart != null)
            {
                newDocument.MainDocumentPart.AddNewPart<FontTablePart>();
                XDocument newXDoc = newDocument.MainDocumentPart.FontTablePart.GetXDocument();
                newXDoc.Declaration.Standalone = "yes";
                newXDoc.Declaration.Encoding = "UTF-8";
                CopyFontTable(sourceDocument.MainDocumentPart.FontTablePart, newDocument.MainDocumentPart.FontTablePart);
                newXDoc.Add(fontTablePart.GetXDocument().Root);
            }
        }
Example #3
0
        /// <summary>
        /// プロパティを書き込みます
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="propertiesTable"></param>
        /// <returns></returns>
        public bool WriteProperties(string filePath, string keyword, int filetype, bool bFileInfoUpdate, List <string> lstFinal, ref DateTime LastWriteTime, ref string error_reason)  // 20171011 修正(ファイル書込み時のエラー理由を保存) // step2 iwasa
        {
            bool bRet = true;

            // 20171010 修正(try-catch追加(対象ファイルが存在しない場合に発生するエラー対応))
            // (検索ボタン押下後、ファイルを移動/削除した場合など)
            try
            {
                System.IO.FileInfo fi = new System.IO.FileInfo(filePath);
                if (fi.Length == 0)
                {
                    // ファイルサイズがゼロの場合プロパティが存在しないのでエラー
                    // 20171228 追加(エラー理由保存)
                    error_reason = ListForm.LIST_VIEW_NA;
                    return(false);
                }

                // 最終版
            }
            catch
            {
                // 対象ファイルが存在しない場合にここに来る
                // ファイルが存在しない場合のエラー
                error_reason = ListForm.LIST_VIEW_NA;
                return(false);
            }

            // ファイルのプロパティ領域を開く
            SpreadsheetDocument    excel = null;
            WordprocessingDocument word  = null;
            PresentationDocument   ppt   = null;

            CoreFilePropertiesPart coreFileProperties;

            // 20171010 修正(try-catch追加(開いているファイルを開こうとして発生するエラー対応))
            try
            {
                switch (filetype)
                {
                case ListForm.EXTENSION_EXCEL:
                    excel = SpreadsheetDocument.Open(filePath, true);
                    coreFileProperties = excel.CoreFilePropertiesPart;
                    break;

                case ListForm.EXTENSION_WORD:
                    word = WordprocessingDocument.Open(filePath, true);
                    coreFileProperties = word.CoreFilePropertiesPart;
                    break;

                case ListForm.EXTENSION_POWERPOINT:
                    ppt = PresentationDocument.Open(filePath, true);
                    coreFileProperties = ppt.CoreFilePropertiesPart;
                    break;

                default:
                    // 異常なファイル
                    // 20171228 追加(エラー理由保存)
                    error_reason = ListForm.LIST_VIEW_NA;
                    return(false);
                }
            }
            catch
            {
                // 開いているファイルを開いた場合にここに来る
                // ファイルが開かれている場合のエラー
                // または読み取り専用のファイル
                error_reason = ListForm.LIST_VIEW_NA;
                return(false);
            }

            LastWriteTime = new DateTime();

            NameTable           nt        = new NameTable();
            XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);

            nsManager.AddNamespace(PropertiesKeyList.STR_TAG_CP, PropertiesSchemaList.CorePropertiesSchema);
            nsManager.AddNamespace(PropertiesKeyList.STR_TAG_DC, PropertiesSchemaList.DcPropertiesSchema);
            nsManager.AddNamespace(PropertiesKeyList.STR_TAG_DCTRMS, PropertiesSchemaList.DctermsPropertiesSchema);
            nsManager.AddNamespace(PropertiesKeyList.STR_TAG_DCMITYPE, PropertiesSchemaList.DcmitypePropertiesSchema);
            nsManager.AddNamespace(PropertiesKeyList.STR_TAG_XSI, PropertiesSchemaList.XsiPropertiesSchema);

            XmlDocument xdoc = new XmlDocument();

            try
            {
                xdoc.Load(coreFileProperties.GetStream());

                // 最終版のチェック
                string searchString = string.Format(PropertiesKeyList.STR_CORE_PROPERTIES + "{0}", PropertiesKeyList.STR_CONTENT_STATUS);
                // 書き込み先を検索
                XmlNode xNode = xdoc.SelectSingleNode(searchString, nsManager);

                //if (xNode != null && xNode.InnerText == PropertiesKeyList.STR_FINAL_CONTENT)
                if (xNode != null && lstFinal.Contains(xNode.InnerText))    // step2 iwasa
                {
                    // 最終版のファイルへの書き込みはできないのでエラーを返す
                    // 20171228追加(エラーの理由を保存)
                    error_reason = ListForm.LIST_VIEW_NA;
                    return(false);
                }

                // 更新日時を読み込む
                // 書き込み先のキーワードを指定
                searchString = string.Format(PropertiesKeyList.STR_CORE_PROPERTIES + "{0}", PropertiesKeyList.STR_MODIFIED);
                // 書き込み先を検索
                xNode = xdoc.SelectSingleNode(searchString, nsManager);

                if (xNode != null)
                {
                    LastWriteTime = DateTime.Parse(xNode.InnerText);
                }
                else
                {
                    // なかったら今日の日付
                    LastWriteTime = DateTime.Now;
                }

                // キーワードの書込
                // 書き込み先のキーワードを指定
                searchString = string.Format(PropertiesKeyList.STR_CORE_PROPERTIES + "{0}", PropertiesKeyList.STR_KEYWORDS);
                // 書き込み先を検索
                xNode = xdoc.SelectSingleNode(searchString, nsManager);

                if (xNode != null)
                {
                    // 書き込む
                    xNode.InnerText = keyword;
                }
                else
                {
                    // keywordsタグが存在していないので作成する
                    XmlNode node = xdoc.DocumentElement;

                    // TSE kitada Comment.
                    // .NETのバグ(?)により、"cp:keywords"を出力すると「:」より前をprefix扱いして勝手に削除してしまうため
                    // Excelのフォーマットとして破損した形で出力されてしまう。
                    // "cp:"の部分は名前空間を指定することで勝手に付与されるので、qualifiedNameにはcp:をつけなくてよい。
                    XmlElement el = xdoc.CreateElement(PropertiesKeyList.STR_KEYWORDS, PropertiesSchemaList.CorePropertiesSchema);
                    el.InnerText = keyword;
                    node.AppendChild(el);
                }

                // カテゴリのリセット
                // 書き込み先のキーワードを指定
                searchString = string.Format(PropertiesKeyList.STR_CORE_PROPERTIES + "{0}", PropertiesKeyList.STR_CATEGORY);
                // 書き込み先を検索
                xNode = xdoc.SelectSingleNode(searchString, nsManager);

                if (xNode != null)
                {
                    // 書き込む
                    xNode.InnerText = "";
                    // 保存
                    //xdoc.Save(coreFileProperties.GetStream());
                }

                // 20190705 TSE matsuo ファイルのプロパティ領域を再作成する
                if (excel != null)
                {
                    excel.DeletePart(excel.CoreFilePropertiesPart);
                    excel.AddCoreFilePropertiesPart();
                    coreFileProperties = excel.CoreFilePropertiesPart;
                }
                if (word != null)
                {
                    word.DeletePart(word.CoreFilePropertiesPart);
                    word.AddCoreFilePropertiesPart();
                    coreFileProperties = word.CoreFilePropertiesPart;
                }
                if (ppt != null)
                {
                    ppt.DeletePart(ppt.CoreFilePropertiesPart);
                    ppt.AddCoreFilePropertiesPart();
                    coreFileProperties = ppt.CoreFilePropertiesPart;
                }

                // 20180109 TSE kitada 保存は最後に一回だけ
                // 保存
                xdoc.Save(coreFileProperties.GetStream());
            }
            catch (Exception e)
            {
                bRet = false;
                // 20171011 追加 (読取専用、ファイ存在しない以外のエラー)
                error_reason = ListForm.LIST_VIEW_NA;
            }
            finally
            {
                // ファイルのプロパティ領域を閉じる
                if (excel != null)
                {
                    excel.Close();
                }
                if (word != null)
                {
                    word.Close();
                }
                if (ppt != null)
                {
                    ppt.Close();
                }
            }
            try
            {
                // 更新日は更新しない場合は元の更新日を上書きする
                if (!bFileInfoUpdate)
                {
                    System.IO.File.SetLastWriteTime(filePath, LastWriteTime);
                }
            }
            catch (Exception e)
            {
                // 対象ファイルがロックされている場合はスルーする
            }

            return(bRet);
        }