Solve Phpword Chinese characters and set Chinese fonts, common use problems

Source: Internet
Author: User
Tags autoloader phpword
Solve Phpword Chinese characters and set Chinese fonts, common use problems

A recent project development uses PHP technology to export Word documents, comparing several scenarios, starting with the Activex/com components that Microsoft Office comes with. For example, Word.Application, the advantage of this way is that the format compatibility is high, can generate a pure Doc Word2003 format document, the disadvantage is that the comparison of resources (call will start a WINWORD.EXE process), not suitable for Web multi-user access to use The second is that PHP, the Web development technology is mostly run on the Linux server, of course, can not use the technology under Windows, platform portability and compatibility is not good. The second way to build word is to generate a word-compatible Web page format, and then open it in Word, which is generally weird, after all, the file format is HTML and the format compatibility is not good, but the advantage of this way is to save server resources, can quickly generate The final scenario, which is today's protagonist, uses Phpword to generate Word2007 (docx)-formatted documents, which are now basically compatible with the version of Microsoft Office Word 2003, and for Version 2003, You only need to download and install a compatible format package (download address), and you can open such files normally, but if you are using the latest version of Office (including but not limited to Office 2007, Office 2010), you do not need to install this format package.

OK, let me introduce you to Phpword, you can download and get more information about the project through Phpword.

I am in the process of using the main problem of Chinese garbled, combined with the guidance of the gods on the Internet, through the following way to solve this kind of problem, I hope to help you.

1. Added East Asian font support

Open and edit the path/writer/word2007/base.php file content, probably in line No. 349 (the number of lines as the version may change) The approximate function is added inside _writetextstyle:

$objWriter->writeattribute (' W:eastasia ', $font)

For example, my modified fragment is basically the following:

Fontif ($font! = ' Arial ') {    $objWriter->startelement (' w:rfonts ');        $objWriter->writeattribute (' W:eastasia ', $font); Add this line        $objWriter->writeattribute (' W:ascii ', $font);        $objWriter->writeattribute (' W:hansi ', $font);        $objWriter->writeattribute (' W:cs ', $font);    $objWriter->endelement ();}

2. Solve Chinese garbled problem edit phpword/template.php, find code $replace = Utf8_encode ($replace), delete or comment out this line of code, add $replace = Iconv (' GBK ', ' utf-8 ', $replace), such as code changed to read as follows:

/** * Set a Template value *  * @param mixed $search * @param mixed $replace */public function SetValue ($search, $repla CE) {    if (substr ($search, 0, 2)!== ' ${' && substr ($search,-1)!== '} ') {        $search = ' ${'. $search. '} ';    }     if (!is_array ($replace)) {        //$replace = Utf8_encode ($replace);        $replace =iconv (' GBK ', ' utf-8 ', $replace); Add this line after commenting out the line    }     $this->_documentxml = Str_replace ($search, $replace, $this->_documentxml);}

The method is called as follows:

/** * ADD a Text Element *  * @param string $text * @param mixed $styleFont * @param mixed $styleParagraph * @return PH Pword_section_text */public function AddText ($text, $styleFont = null, $styleParagraph = null) {    //$givenText = Utf8_e Ncode ($text);    $givenText = Iconv (' GBK ', ' utf-8 ', $text); Add this line after commenting out the line    $text = new Phpword_section_text ($givenText, $styleFont, $styleParagraph);    $this->_elementcollection[] = $text;    return $text;}

The above code mainly solves the problem of the template, the following same reason, solve the problem of section add text, find code $giventext = Utf8_encode ($text), delete or comment out this line of code, add $giventext = Iconv (' GBK ', ' utf-8 ', $text), such as the following code:

The calling method is similar to the above template invocation, which is not listed here.

Tossing so much, suddenly found on the internet there is another version of the Phpword, Project class name case is slightly different, subordinate to the Phpoffice/phpword,github Project address (document). This version of the Phpword content richer, supported by more features (including line spacing, indentation and first line indentation, etc.), finally I also take this version of the Phpword, it is noteworthy that the two versions of Phpword in the API interface basically consistent, can be common. But some APIs, in the Phpoffice/phpword is not recommended, such as createsection need to change to addsection, and the application of this version of the Phpword do not need to do any Chinese support changes like the above , More convenient.

All of the two Phpword projects have been provided with more detailed usage examples and documentation, which is not covered here.

The last hint is: In the template mode LoadTemplate, can only use SetValue and other template operation method, can not add paragraph or paragraph changes. This is slightly inconvenient.

For Phpoffice/phpword I provide a simple example for reference (of course the official example more):

Require_once ' phpoffice/phpword/phpword.php '; Contains header file use Phpoffice\phpword\autoloader;use phpoffice\phpword\settings;use phpoffice\phpword\iofactory; Require_once __dir__. '/phpoffice/phpword/autoloader.php '; Autoloader::register (); Settings::loadconfig (); Create a new Phpword Object$phpword = new \phpoffice\phpword\phpword (); $PHPWordHelper = new \phpoffice\phpword\shared\ Font (); $PHPWord->setdefaultfontname (' imitation ');     Global Font $phpword->setdefaultfontsize (16); The global font size is number 3rd//Set the document properties, which can be seen on right-click properties of the document, or omit these steps $properties = $PHPWord->getdocumentproperties (); $properties   Setcreator (' Zhang San '); Creator $properties->setcompany (' a company '); Company $properties->settitle (' xxx documents '); Title $properties->setdescription (' http://wangye.org '); Description $properties->setlastmodifiedby (' John Doe ');      Last Modified $properties->setcreated (time ());     Creation time $properties->setmodified (); Modify the time//add 3rd Imitation font to ' fangsong16pt ' to keep the following using $phpword->addfontstyle (' fangsong16pt ', Array (' name ' = = ' imitation ', ' size '=>16));    Add a paragraph style to ' normal ' for the following using $phpword->addparagraphstyle (' normal ', array (' align ' = ' both ', ' spacebefore ' = + 0,    ' SpaceAfter ' = 0, ' spacing ' + $PHPWordHelper->pointsizetotwips (2.8), ' lineheight ' = 1.19,//Line spacing ' Indentation ' = = Array (//First line indent ' firstline ' = + $PHPWordHelper->pointsizetotwips (32)))); Section style: Upper 3.5 cm, lower 3.8 cm, left 3 cm, right 3 cm, footer 3 cm//note here centimeters (centimeter) to convert to twips units $sectionstyle = Array (' Orientation ' = NULL, ' marginleft ' = $PHPWordHelper->centimetersizetotwips (3), ' marginright ' = $PHPWordHelper->centime Tersizetotwips (3), ' margintop ' = $PHPWordHelper->centimetersizetotwips (3.5), ' marginbottom ' = $PHPWordHel Per->centimetersizetotwips (3.8), ' Pagenumberingstart ' + 1,//page number starting from 1 ' footerheight ' = $PHPWordHelper Centimetersizetotwips (3),); $section = $PHPWord->addsection ($sectionStyle); Add a section//the following sentence is the input document content, note here we have just added the//font style FANGSONG16PT and paragraph style normal$secTion->addtext (' document content ', ' fangsong16pt ', ' Normal '); $section->addtextbreak (1); A new blank paragraph $objWriter = iofactory::createwriter ($PHPWord, ' Word2007 '); $objWriter->save ('/path/to/file '); Save to/path/to/file Path
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.