Wakka02
Wakka02

Reputation: 1541

How to bold certain text only in PDFsharp?

I'm programming on VB.NET, and making use of the PDFsharp library to create PDF pages according to my program's needs. Now, I need to bold only certain parts of text, but I only know how to bold entire parts of it at once. How do I go about doing this?

Currently, the code I'm using to render words is as follows:

Dim graph As XGraphics = XGraphics.FromPdfPage(pdfPage)
graph.DrawString("Sample Text", New XFont("Arial", 12, FontStyle.Bold), New SolidBrush(Color.Black), New RectangleF(X, Y, 700, 30), New XStringFormat())

Upvotes: 0

Views: 3092

Answers (2)

TheBugger
TheBugger

Reputation: 51

In your example above, if you wish to write "Sample Text" with the word "Text" in bold, perform the following;

  • Include the MigraDoc+PDFsharp NuGet package, as mentioned by previous reply.
  • Replace the graph.DrawString line with the following code (although this is C#, sorry) to render the text using a MigraDoc Paragraph instance, using your existing XGraphics graph instance from PDFsharp.

    var document = new Document();
    var section = document.AddSection();
    var paragraph = section.AddParagraph();
    paragraph.Format.Alignment = ParagraphAlignment.Left;
    paragraph.Format.Font.Name = "Arial";
    paragraph.Format.Font.Size = 12;
    
    paragraph.AddText("Sample ");
    paragraph.AddFormattedText("Text", TextFormat.Bold);
    
    var docRenderer = new DocumentRenderer(document);                            
    docRenderer.PrepareDocument();
    docRenderer.RenderObject(graph, XUnit.FromPoint(X), XUnit.FromPoint(Y), XUnit.FromPoint(700), paragraph);
    

Upvotes: 3

Invoke DrawString for the regular part, then invoke DrawString for the bold part, then invoke DrawString for the next regular part. Always give the correct position for each string.

You can look at the XTextFormatter class. It implements automatic linebreaks, but does not support mixing different font styles yet. It can get you started.

Pro tip: You can get MigraDoc and PDFsharp in one NuGet package. MigraDoc allows mixing in a single paragraph, handles linebreaks and pagebreaks automatically and also brings other benefits like page headers and footers.

Upvotes: 0

Related Questions