Font change in PDF file

I am trying to change font type in pdf. I am getting an error

|Severity|Code|Description|Project|File|Line|Suppression State|
|---|---|---|---|---|---|---|
|Error|CS0030|Cannot convert type 'Aspose.Pdf.XImage' to 'Aspose.Pdf.Text.TextFragment'|CreateDocument.Core|C:\Cloud\AddoCreateDocument....


           // Specify the desired font name
           string desiredFontName = "Arial";

           // Loop through all pages and set the font name
           foreach (Aspose.Pdf.Page page in pdfDocument.Pages)
           {
               // Loop through all the text fragments on the page
               foreach (TextFragment textFragment in page.Resources.Images)
               {
                   // Set the desired font name
                   textFragment.TextState.Font = FontRepository.FindFont(desiredFontName);
               }
           }

           // Save the modified PDF document
           pdfDocument.Save("output.pdf");

@niku2023

You are facing this error because you are using the wrong code snippet. Please use the correct code as below:

foreach (var page in pdfDocument.Pages)
{
    TextFragmentAbsorber absorber = new TextFragmentAbsorber();
    absorber.Visit(page);
    foreach (TextFragment fragment in absorber.TextFragments)
    {
        fragment.TextState.Font = FontRepository.FindFont("Arial");
    }
    page.Resources.Images.Clear();
}
1 Like

fragment.TextState.Font = FontRepository.FindFont(“Abadi”); this line not executing. getting an error

@niku2023

Please make sure that “Abadi” is properly installed in your system. In case font is installed and you are still not able to execute the code, please share the sample PDF with us along with the font file. We will test the scenario in our environment and address it accordingly.

1 Like