【发布时间】:2017-02-17 00:08:11
【问题描述】:
我想阅读 .docx 文件并将其内容作为电子邮件正文而不是附件发送到电子邮件中。
为此,我使用 openXML 和 OpenXmlPowerTools 将 docx 文件转换为 html。这几乎可以正常工作,直到我得到一个包含 Header 和 Footer 图像的文档。
这是我将 .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 文件中包含页眉和页脚的任何解决方法也是如此。
请给我建议。谢谢!
【问题讨论】:
-
(我知道这有点无关紧要)您使用 OpenXML SDK 而不是 MS Word Interop Assembly 有什么特别的原因吗?
-
@AzazulHaq 我认为 MS Word Interop Assembly 需要在您的机器上安装 MS Office,所以我避免这样做。
标签: c# asp.net-mvc openxml