Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
599 views
in Technique[技术] by (71.8m points)

php - PHPWord HTML to Word design issue

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

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

1 Reply

0 votes
by (71.8m points)

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');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...