2017-02-16 163 views
1

我想讀取.docx文件並將其內容作爲電子郵件正文而不是附件發送。OpenXml從Word文檔轉換爲帶有標題的HTML

因此,爲此,我使用openXML和OpenXmlPowerTools將docx文件轉換爲html。這幾乎工作正常,直到我有一個文件有標頭頁腳與圖像。

這裏是我的代碼的.docx轉換爲HTML

using (WordprocessingDocument doc = WordprocessingDocument.Open(stream, true)) 
       { 
        HtmlConverterSettings convSettings = new HtmlConverterSettings() 
        { 
         FabricateCssClasses = true, 
         CssClassPrefix = "cls-", 
         RestrictToSupportedLanguages = false, 
         RestrictToSupportedNumberingFormats = false, 
         ImageHandler = imageInfo => 
         { 
          DirectoryInfo localDirInfo = new DirectoryInfo(imageDirectoryName); 
          if (!localDirInfo.Exists) 
          { 
           localDirInfo.Create(); 
          } 

          ++imageCounter; 
          string extension = imageInfo.ContentType.Split('/')[1].ToLower(); 
          ImageFormat imageFormat = null; 
          if (extension == "png") 
          { 
           extension = "jpeg"; 
           imageFormat = ImageFormat.Jpeg; 
          } 
          else if (extension == "bmp") 
          { 
           imageFormat = ImageFormat.Bmp; 
          } 
          else if (extension == "jpeg") 
          { 
           imageFormat = ImageFormat.Jpeg; 
          } 
          else if (extension == "tiff") 
          { 
           imageFormat = ImageFormat.Tiff; 
          } 

          // If the image format is not one that you expect, ignore it, 
          // and do not return markup for the link. 
          if (imageFormat == null) 
          { 
           return null; 
          } 

          string imageFileName = imageDirectoryName + "/image" + imageCounter.ToString() + "." + extension; 

          try 
          { 
           imageInfo.Bitmap.Save(imageFileName, imageFormat); 
          } 
          catch (System.Runtime.InteropServices.ExternalException) 
          { 
           return null; 
          } 

          XElement img = new XElement(Xhtml.img, new XAttribute(NoNamespace.src, imageFileName), imageInfo.ImgStyleAttribute, imageInfo.AltText != null ? new XAttribute(NoNamespace.alt, imageInfo.AltText) : null); 
          return img; 
         } 
        }; 

        XElement html = OpenXmlPowerTools.HtmlConverter.ConvertToHtml(doc1, convSettings); 

上面的代碼工作正常,圖像轉換爲好,但如果文檔頁眉和頁腳那些不轉換。

所以他們的任何解決方法,包括在HTML文件中的頁眉和頁腳。

請給我建議。謝謝!

+0

(我知道這有點不相關)是否有什麼特別的原因,你爲什麼使用OpenXML SDK而不是MS Word Interop Assembly? –

+2

@AzazulHaq我認爲MS Word互操作大會需要MS Office安裝在您的機器上,所以我避免這種情況。 –

回答

0

當將docx-document轉換爲HTML時,OpenXmlPowerTools會忽略頁眉和頁腳,因此它們不會顯示在生成的HTML中(您可以在github上使用browse the source code)。

也許是因爲「頁面」的概念不適用於HTML,所以沒有明顯的等同於文檔標題。