鍍金池/ 問答/C#/ c# 使用spire.doc導(dǎo)出word文檔,設(shè)置文字樣式無效。

c# 使用spire.doc導(dǎo)出word文檔,設(shè)置文字樣式無效。

public void CreatJbDocX(string jbHead, string jbBody, string path)
        {
            //創(chuàng)建一個(gè)Document實(shí)例
            Document doc = new Document();
            //添加一個(gè)section
            Section section = doc.AddSection();
            //設(shè)置頁(yè)面大小,方向
            section.PageSetup.PageSize = PageSize.A4;
            section.PageSetup.Orientation = PageOrientation.Landscape;
            section.PageSetup.Margins.Top = 35f;
            section.PageSetup.Margins.Left = 35f;
            section.PageSetup.Margins.Bottom = 35f;
            section.PageSetup.Margins.Right = 35f;
            //添加表格
            Table table = section.AddTable(true);
            //指定表格的行數(shù)和列數(shù)(2行,1列)
            table.ResetCells(2, 1);
            //寫入數(shù)據(jù)
            table[0, 0].AddParagraph().AppendHTML(jbHead);
            table[1, 0].AddParagraph().AppendHTML(jbBody);
            //創(chuàng)建段落格式
            ParagraphStyle style1 = new ParagraphStyle(doc);
            style1.Name = "txtStyle1";
            style1.CharacterFormat.FontName = "宋體";
            style1.CharacterFormat.FontSize = 50;
            //style3.CharacterFormat.TextColor = Color.Gray;
            doc.Styles.Add(style1);
            //設(shè)置表格內(nèi)段落樣式
            Paragraph tableParagraph = table[0, 0].Paragraphs[0];
            tableParagraph.ApplyStyle("txtStyle1");
            //保存文檔
            try
            {
                doc.SaveToFile(path, FileFormat.Docx2010);
            }
            catch (Exception)
            {
                throw;
            }
        }

發(fā)現(xiàn)是以下兩句造成的,如果用.AppendText方法就沒問題了,但(jbHead)和jbBody里包含著定義文字顏色的html標(biāo)簽,我只想在加載文字后保留字體顏色,改變一下字體大小而已,我該怎么做呢?

//寫入數(shù)據(jù)
            table[0, 0].AddParagraph().AppendHTML(jbHead);
            table[1, 0].AddParagraph().AppendHTML(jbBody);
回答
編輯回答
殘淚

通過測(cè)試,Spire.Doc在從HTML創(chuàng)建Word文檔有下面的規(guī)則:

  1. 字體樣式(包括大小、顏色、下劃線、粗斜體等)優(yōu)先以HTML為準(zhǔn)。當(dāng)HTML,ParagraphStyle都定義了樣式,優(yōu)先選擇HTML的樣式。
  2. HTML中<h1>,<p>這些標(biāo)簽本身暗含 了字體大小,所以在后面ParagraphStyle設(shè)置字體大小不生效。

解決方案有:

  1. 在HTML中定義好字體大小:
string headHtml = "<h1><font size=\"24\">This is head.</font></f1>";
  1. 通過代碼清除HTML中的字體樣式,再應(yīng)用自定義樣式
//清除Html的樣式
foreach (var item in table[0, 0].Paragraphs[0].Items)
{
    if (item is TextRange)
    {
        TextRange tr = item as TextRange;
        tr.CharacterFormat.ClearFormatting();
    }
}
//重新應(yīng)用自定義格式
table[0, 0].Paragraphs[0].ApplyStyle(style1.Name);
2018年3月31日 22:03