Forum


Replies: 1   Views: 126
How to make text bold and some part of that text would be superscript

Posted by fairshareitservices  · 26-09-2024 - 08:14

Hi,

I am getting dynamic text from the input file and i need to convert that text to which is enclosed in <b> </b> to bold and there is some text remaining after </b> need to be converted into superscript. For bold i already using below code so how to modify this for superscript

function formatText($inputText,$templateDocx,$placeHolderName){
$docx = new CreateDocx();
$wf = new WordFragment($docx);
 $inputExploded=explode('</b>',$inputText);
foreach ($inputExploded as $key => $partialInput) {

        $partialInputExploded = explode('<b>', $partialInput);

        // Check if we need to add a line break
        if (!empty($partialInputExploded[0])) {
            // Split on <br> tags and handle accordingly
            $lineBreakArray = explode('<br>', $partialInputExploded[0]);
            foreach ($lineBreakArray as $key => $lineBreakText) {
                if (!empty($lineBreakText)) {                    
                    $text[] = array(
                        'text' => $lineBreakText,
                        'lineBreak' => 'after',
                    );                    
                }
            }
        }
           for ($i = 1; $i < count($partialInputExploded); $i++) {
              $text[] = array(
                    'text' => $partialInputExploded[$i],
                    'bold' => true,
                    'fontSize' => 7,
                    'font' => 'Cambria',
                );
            $wf->addText($text, array('font' => 'Cambria', 'fontSize' => 7));
         }

       return $wf;
}

 

Posted by admin  · 26-09-2024 - 10:28

Hello,

addText (https://www.phpdocx.com/api-documentation/word-content/add-paragraph-text-Word-document-with-PHP) includes the superscript option to add text in superscript:

$text = array();
$text[] =
    array(
        'text' => 'A bold text',
        'bold' => true,
);
$text[] =
    array(
        'text' => ' superscript content',
        'superscript' => true,
);
$docx->addText($text);

If you are using HTML tags to add contents, you need to use embedHTML or replaceVariableByHTML to transform HTML to DOCX.
You can get the same output using CSS styles (as inline, external, or style tags):

$html = '<p><span style="font-weight: bold;">A bold text</span><span style="vertical-align: super;">superscript content</span></p>';
$docx->embedHTML($html);

or using tags:

$html = '<p><b>A bold text</b><sup>superscript content</sup></p>';
$docx->embedHTML($html);

Regards.