如何使用HtmlConverterSettings居中图像

时间:2014-05-22 13:15:28

标签: xml openxml

我正在使用我的代码中的OpenXMLPowerTools HtmlConverterSetting类将Word文档(docx)解析为可比较的HTML等价物。我在Html生成的文档中立即注意到的事情是,在Word文档的页面中居中的一些图像对齐到html输出的左侧。

只关注我试图找到解决方案的代码部分,我有这个:

HtmlConverterSettings settings = new HtmlConverterSettings()
   {
      PageTitle = pageTitle, 
      FabricateCssClasses = true,
      CssClassPrefix = "cls-",
      RestrictToSupportedLanguages = false,
      RestrictToSupportedNumberingFormats = false,
      ImageHandler = imgInfo =>
          {
             XElement img = new XElement(Xhtml.img,
             new XAttribute(NoNamespace.src, imageName),
             imgInfo.ImgStyleAttribute);
             return img;
          }
     };
XElement html = HtmlConverter.ConvertToHtml(wordDoc, settings);

在完整执行完整代码后(注意:为了简化问题省略了其他代码部分)....我得到了一个html文档,其中包含几乎每个组件标记的样式部分。

更具体地说,问题是,我得到了我的图像的内联样式,并且大多数都包含宽度和高度属性,但是与原始文档相关的图像的实际定位相关的属性不存在。

例如调试XAttribute的ImgStyleAttribute,我发现:

{style="width:1.5in; height:1.4375in;"}

在Html生成的文件中生成以下内嵌样式的图像:

{img src="<pathToImage>" style="width: 1.5in; height: 1.4375in"}

我还注意到Html标记上方的Style块动态创建了一些span类。其中1个类我已经确定为分配给文件中的每个图像。

span.cls-DefaultParagraphFont-000003 {
    font-size:11pt;
    font-weight:normal;
    margin:0in;
    padding:0in;    
}

所以我决定拦截这个过程,理想情况是在生成图像的内联样式时添加额外的属性以使图像居中(如果没有定位属性)就在图像的XElement是合理的选项之前:

var infoimg = imageInfo.ImgStyleAttribute;
imageInfo.ImgStyleAttribute.Value = imageInfo.ImgStyleAttribute.Value + ";margin-left: auto; margin-right: auto; display: block;";

这很好用,但为了有效地工作,我显然需要在执行之前解析Element的现有样式属性,以避免使已经具有某些定位属性的图像居中。所以我不确定这是否是解决问题的正确方法。

我有兴趣听到更优雅的问题解决方法,以及其他人如何有效地解决这个问题。

注意:在旁注中,我正在使用带有以下库的C#:

iTextSharp,DocumentFormat.OpenXml和OpenXMLPowerTools

由于

1 个答案:

答案 0 :(得分:0)

因此,我对如何使用DocumentFormat和OpenXML组件居中图像的问题的最终解决方案是使用辅助函数解析ImageHandler对象的ImgStyleAttribute属性,以确定是否存在每个图像的任何现有HTML定位元素。 / p>

如果原始标记不包含图像的任何现有内嵌位置样式元素,则在将内容写入PDF格式之前,我会附加这些元素以使图像居中。我将函数命名为ContainsStylePositioning,它接受一个字符串值,即ImgStyleAttributeValue,并将字符串转换为名称/值对的数组,以搜索样式元素。

如果没有与图像相关的定位相关的任何内联样式元素,那么我将属性附加到样式元素以自动居中图像。

var infoimg = imageInfo.ImgStyleAttribute;
    if (!ContainStylePositioning(imageInfo.ImgStyleAttribute.Value))
       { imageInfo.ImgStyleAttribute.Value = imageInfo.ImgStyleAttribute.Value + ";margin-left: auto; margin-right: auto; display: block;"; }

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

这在我测试过的所有可能场景中都有效。我正在寻找其他人的意见,但显然没有其他人有这个要求与这些特定组件合作。

由于