PHP manipulates Word for template variable substitution

Install extensions for PHP to manipulate Word

composer require phpoffice/phpword

Word templates

Let’s say our Word is callediamking.docxAs shown in figure

PHP code replacement

Create a PHP file, index. PHP, in the blank project

<? php /** * Created by PhpStorm. * User: smallForest<[email protected]> * Date: 2021/1/6 * Time: 17:44 */ require_once "vendor/autoload.php"; // Use Phpoffice \PhpWord\TemplateProcessor; $templateProcessor = new TemplateProcessor('word/iamking.docx'); $templateprocesser-> setValue('kouhao', 'I am the test number! Ollie give nice '); $templateProcessor->setValue('date', '2021-10-01'); // Save the file $templateprocessor-> saveAs('word/iamking2.docx');

Convert Word to PDF

Usually the most used is Linux operation, need to install a LibreOffice service. Local environment Centos7

yum install libreoffice

Assume that the file we saved in the previous step, iamking2.docx, is in /root/word. Execute the following command

cd /root/word/
libreoffice --convert-to pdf:writer_pdf_Export iamking2.docx

A PDF file of the same name, iamking2.pdf, is generated in the current directory

Error handling

After the second step you think you’re done, but it’s not. The Chinese in the generated PDF will be recognized as small squares, which is obviously not what we expected.

Error: Linux server lacks Chinese font

Solution: access to the Mac/System/Library/FontsDirectory to find the two font files



Upload to Linux/usr/share/fonts/chineseA directory of

Chmod 755 -R Chinese fc-list // cmod 755 -R Chinese fc-list // cmod 755 -R Chinese fc-list // cmod 755 -R Chinese fc-list



Execute the export command again, and the font will do

Pay attention to

LibreOffice is single-threaded, multiple files exported to be locked queue, otherwise there will be an unexpected error PHP execution script, need to be taken into consideration. The specific implementation details are measured by themselves

code

https://github.com/SmallFores…