Подтвердить что ты не робот

Как изменить шрифт open xml

Как изменить семейство шрифтов документа через OpenXml? Я пробовал некоторые способы, но когда я открываю документ, он всегда находится в Calibri

Следуйте моему коду и тем, что я пробовал.

Создатель заголовков, я думаю, бесполезно публиковать сообщения

private static void BuildDocument(string fileName, List<string> lista, string tipo)
        {                
            using (WordprocessingDocument w = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
            {
                MainDocumentPart mp = w.AddMainDocumentPart();
                DocumentFormat.OpenXml.Wordprocessing.Document d = new DocumentFormat.OpenXml.Wordprocessing.Document();
                Body b = new Body();
                DocumentFormat.OpenXml.Wordprocessing.Paragraph p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
                Run r = new Run();

                //// Get and format the text.                                    
                for (int i = 0; i < lista.Count; i++)
                {
                    Text t = new Text();                    
                    t.Text = lista[i];
                    if (t.Text == "          ")
                    {
                        r.Append(new CarriageReturn());
                    }
                    else
                    {
                        r.Append(t);
                        r.Append(new CarriageReturn());
                    }
                }

   //// What I Tried
   RunProperties rPr = new RunProperties(
        new RunFonts()
        {
            Ascii = "Arial"
        });                

                lista.Clear();                
                p.Append(r);                
                b.Append(p);
                HeaderPart hp = mp.AddNewPart<HeaderPart>();
                string headerRelationshipID = mp.GetIdOfPart(hp);
                SectionProperties sectPr = new SectionProperties();                
                HeaderReference headerReference = new HeaderReference();                
                headerReference.Id = headerRelationshipID;
                headerReference.Type = HeaderFooterValues.Default;
                sectPr.Append(headerReference);
                b.Append(sectPr);
                d.Append(b);                

                //// Customize the header.
                if (tipo == "alugar")
                {
                    hp.Header = BuildHeader(hp, "Anúncio Aluguel de Imóvel");
                }
                else if (tipo == "vender")
                {
                    hp.Header = BuildHeader(hp, "Anúncio Venda de Imóvel");
                }
                else
                {
                    hp.Header = BuildHeader(hp, "Aluguel/Venda de Imóvel");
                }

                hp.Header.Save();
                mp.Document = d;
                mp.Document.Save();
                w.Close();
            }             
        }
4b9b3361

Ответ 1

Чтобы стилизовать текст с помощью определенного шрифта, выполните следующие действия:

  • Создайте экземпляр класса RunProperties.
  • Создайте экземпляр класса RunFont. Задайте свойство Ascii для нужного шрифта familiy.
  • Укажите размер шрифта (размер шрифта половинной точки) с помощью класса FontSize.
  • Подготовьте экземпляр RunProperties к вашему прогону, содержащему текст в стиле.

Вот небольшой пример кода, иллюстрирующий шаги, описанные выше:

private static void BuildDocument(string fileName, List<string> text)
{
  using (WordprocessingDocument wordDoc =
    WordprocessingDocument.Create(fileName,
    WordprocessingDocumentType.Document))
  {
    MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
    mainPart.Document = new Document();

    Run run = new Run(); 
    foreach (string currText in text) // Add text to run.
    {
      Text currLine = new Text(currText);

      run.AppendChild<Text>(currLine);
      run.AppendChild<CarriageReturn>(new CarriageReturn());
    }

    Paragraph paragraph = new Paragraph(run);
    Body body = new Body(paragraph);


    mainPart.Document.Append(body);

    RunProperties runProp = new RunProperties(); // Create run properties.
    RunFonts runFont = new RunFonts();           // Create font
    runFont.Ascii = "Arial";                     // Specify font family

    FontSize size = new FontSize();
    size.Val = new StringValue("48");  // 48 half-point font size
    runProp.Append(runFont);
    runProp.Append(size);

    run.PrependChild<RunProperties>(runProp);

    mainPart.Document.Save();
    wordDoc.Close();
  }
}

Надеюсь, это поможет.