Search code examples
c#.netpdfpdfsharpmigradoc

PdfSharp/MigraDoc - how to shade part of a paragraph


Is there a way to apply shading to part (for example, just a word) of a Paragraph in PdfSharp/MigraDoc? I tried adding a Style with the shading to the Document and then passing the style name to the AddFormattedText method but it only takes the font information from the style.

Thanks,


Solution

  • I'm using PdfSharp/MigraDoc from few weeks and before answer precisely to your question I've read the source code of it, freely disponible.

    The short answer is: IS NOT POSSIBLE

    The long answer is: The only part on Style considered by AddFormattedText(string text, string style) is the Character part. Then the Shading, that is a part of ParagraphFormat, cannot be applied, and the renderized, by PdfSharp/MigraDoc.

    The coded answer is:

       public FormattedText AddFormattedText(string text, string style)
        {
          FormattedText formattedText = AddFormattedText(text);
          formattedText.Style = style;
          return formattedText;
        }
    
    
    
     internal class FormattedTextRenderer : RendererBase
       ...
     /// <summary>
        /// Renders the style if it is a character style and the font of the formatted text.
        /// </summary>
        void RenderStyleAndFont()
        {
          bool hasCharacterStyle = false;
          if (!this.formattedText.IsNull("Style"))
          {
            Style style = this.formattedText.Document.Styles[this.formattedText.Style];
            if (style != null && style.Type == StyleType.Character)
              hasCharacterStyle = true;
          }
          object font = GetValueAsIntended("Font");
          if (font != null)
          {
            if (hasCharacterStyle)
              this.rtfWriter.WriteControlWithStar("cs", this.docRenderer.GetStyleIndex(this.formattedText.Style));
    
            RendererFactory.CreateRenderer(this.formattedText.Font, this.docRenderer).Render();
          }
        }
    

    I hope this can help you. Davide.