Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am using PHPWord library to convert my HTML template to Word.

Library link

My code to convert HTML to Word file is as below:

$phpWord = new PhpOfficePhpWordPhpWord();
$section = $phpWord->addSection();
PhpOfficePhpWordSharedHtml::addHtml($section, $htmlTemplate);
$targetFile = __DIR__ . "/1.docx";
$phpWord->save($targetFile, 'HTML');

I am facing below issues:

  1. I am applying background color and font color using inline style but font color is only working and background color is not working.
 <p style="background-color:#FFFF00;color:#FF0000;">Some text</p>
  1. I am using below HTML code to allow Page break within sections of HTML templates. but it does not work in exported Word file.
<div style="page-break-after:always"><span style="display:none">&nbsp;</span></div>
  1. I am using span tag to mark some word in bold or change the color of word in paragraph. but when i export to Word file, content after span tag, moves to new line below the word. I tried with display:inline css property in span tag. but it doesn't work.
<p>some text before span tag <span style="color:#FF0000;display:inline">XXXXX</span> Text after span tag.</p>

Edit:

Please recommend any other library which i can use to convert HTML with inline css to Word if above mentioned issues can't be resolved with PHPWord!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
587 views
Welcome To Ask or Share your Answers For Others

1 Answer

I just performed a very simple test and it is working correctly. My code is pretty much exactly the same as yours except that I'm telling the system to write it as a Word document, not HTML.

use PhpOfficePhpWordPhpWord;
use PhpOfficePhpWordSharedHtml;

require_once __DIR__ . '/vendor/autoload.php';

$htmlTemplate = ' <p style="background-color:#FFFF00;color:#FF0000;">Some text</p>';

$phpWord = new PhpWord();
$section = $phpWord->addSection();
Html::addHtml($section, $htmlTemplate);
$targetFile = __DIR__ . "/1.docx";
$phpWord->save($targetFile, 'Word2007');

Which produces:

Screenshot showing requested background and foreground text correctly applied in Word document

If you change the save mode to HTML, the background color does disappear, however it isn't a Word document anymore anyways, just raw HTML, so I don't think that matters.

$targetFile = __DIR__ . "/1.html";
$phpWord->save($targetFile, 'HTML');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...