在当今数字化办公环境中自动化文档生成已成为提高工作效率的关键技术。本文将详细介绍如何使用PHP配合PHPWord库来自动化生成专业合同文档并提供完整的代码实现。一、技术准备1. 环境要求PHP 7.0或更高版本Composer依赖管理工具服务器写入权限2. 安装PHPWord1composer require phpoffice/phpword二、基础合同生成实现1. 简单合同生成示例123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051?phprequirevendor/autoload.php;usePhpOffice\PhpWord\PhpWord;usePhpOffice\PhpWord\IOFactory;usePhpOffice\PhpWord\Shared\Converter;// 初始化PHPWord对象$phpWordnewPhpWord();// 设置文档属性$phpWord-getDocInfo()-setCreator(智能合同生成系统)-setCompany(XX科技有限公司)-setTitle(销售合同)-setDescription(自动生成的电子合同);// 添加文档部分$section$phpWord-addSection();// 添加合同标题$section-addText(商品销售合同,[name宋体,size 16,bold true],[alignmentcenter,spaceAfter Converter::pointToTwip(24)]);// 合同基本信息$infoTable$section-addTable([borderSize 1]);$infoTable-addRow();$infoTable-addCell(3000)-addText(合同编号HT-.date(YmdHis));$infoTable-addCell(3000)-addText(签订日期.date(Y年m月d日));// 合同正文内容$section-addTextBreak(1);$section-addText(甲方卖方XX科技有限公司, [bold true]);$section-addText(乙方买方___________________, [bold true]);// 合同条款$section-addTextBreak(1);$section-addText(第一条 商品信息, [underlinesingle]);$section-addListItem(商品名称XX智能设备, 0, null,listParagraph);$section-addListItem(规格型号Pro-2023, 0, null,listParagraph);$section-addListItem(数量1台, 0, null,listParagraph);// 保存文档$filenamecontract_.date(YmdHis)..docx;$objWriter IOFactory::createWriter($phpWord,Word2007);$objWriter-save($filename);echo合同已生成a href$filename下载合同/a;三、高级功能实现创建Word模板在开始编写代码之前你需要准备一个Word模板文件。在这个模板中所有需要动态替换的内容都应该使用占位符表示。例如你的合同模板可能看起来像这样1234甲方借款人${borBusNm}身份证号码${aidcard}乙方出借人${lender}身份证号码${bidcard}在这个例子中${borBusNm}、${aidcard}、${lender}和${bidcard}是将被替换的变量。1. 使用模板生成合同1234567891011121314151617181920212223242526272829303132333435usePhpOffice\PhpWord\TemplateProcessor;// 合同数据$contractData [contract_noHT-.date(YmdHis),datedate(Y年m月d日),sellerXX科技有限公司,buyer张三,productXX智能设备,price¥5,999.00,terms1. 质保期1年\n2. 7天无理由退货];// 加载模板$templatenewTemplateProcessor(contract_template.docx);// 替换模板变量内容foreach($contractDataas$key$value) {$template-setValue($key,$value);}// 添加签名图片$template-setImageValue(signature, [pathsignatures/sign.png,width 120,height 60,ratio true,alignmentleft,spaceBefore Converter::pointToTwip(12),spaceAfter Converter::pointToTwip(12)]);// 保存生成的合同$outputFilecontract_.date(YmdHis)..docx;$template-saveAs($outputFile);2. 复杂表格生成123456789101112131415161718192021222324252627// 创建商品明细表格$productsTable$section-addTable([borderSize 1,borderColor000000,cellMargin 50]);// 表头$productsTable-addRow();$productsTable-addCell(1000)-addText(序号, [bold true,alignmentcenter]);$productsTable-addCell(3000)-addText(商品名称, [bold true]);$productsTable-addCell(2000)-addText(单价, [bold true]);$productsTable-addCell(2000)-addText(数量, [bold true]);// 表格内容$products [[XX智能设备,¥5,999.00, 1],[配件套装,¥299.00, 2]];foreach($productsas$i$product) {$productsTable-addRow();$productsTable-addCell(1000)-addText($i1, [alignmentcenter]);$productsTable-addCell(3000)-addText($product[0]);$productsTable-addCell(2000)-addText($product[1], [alignmentright]);$productsTable-addCell(2000)-addText($product[2], [alignmentcenter]);}四、实用技巧1. 添加页眉页脚12345678910111213// 添加页眉$header$section-addHeader();$header-addText(XX科技有限公司销售合同,[size 10,color666666],[alignmentcenter]);// 添加页脚$footer$section-addFooter();$footer-addPreserveText(第 {PAGE} 页 共 {NUMPAGES} 页,[size 9],[alignmentcenter]);2. 设置文档样式123456// 定义样式$phpWord-addTitleStyle(1, [size 16,bold true], [spaceAfter 240]);$phpWord-addParagraphStyle(indent, [indentation [firstLine 400]]);// 使用样式$section-addText(特别条款, null,indent);3. 生成PDF版本123456789usePhpOffice\PhpWord\Settings;// 设置PDF渲染库Settings::setPdfRendererName(Settings::PDF_RENDERER_DOMPDF);Settings::setPdfRendererPath(vendor/dompdf/dompdf);// 生成PDF$pdfWriter IOFactory::createWriter($phpWord,PDF);$pdfWriter-save(contract.pdf);五、完整项目示例一个完整的合同自动化生成系统应包含以下结构1234567891011121314/project-root│├── /templates # 合同模板目录│ ├── sales_contract.docx # 销售合同模板│ └── service_contract.docx # 服务合同模板│├── /signatures # 签名图片目录│ ├── sign1.png│ └── sign2.png│├── /generated # 生成的合同目录│├── composer.json # 依赖配置└── contract_generator.php # 主程序文件contract_generator.php 完整示例12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576?phprequirevendor/autoload.php;usePhpOffice\PhpWord\TemplateProcessor;usePhpOffice\PhpWord\Shared\Converter;classContractGenerator {private$templatePathtemplates/sales_contract.docx;private$outputDirgenerated/;publicfunctiongenerate($data) {// 检查输出目录if(!file_exists($this-outputDir)) {mkdir($this-outputDir, 0777, true);}// 加载模板$templatenewTemplateProcessor($this-templatePath);// 替换基本内容foreach($data[basic]as$key$value) {$template-setValue($key,$value);}// 添加商品表格if(!empty($data[products])) {$this-addProductsTable($template,$data[products]);}// 添加签名if(!empty($data[signature])) {$template-setImageValue(signature, [path$data[signature][path],width$data[signature][width] ?? 120,ratio true,alignmentleft,spaceBefore Converter::pointToTwip(12),spaceAfter Converter::pointToTwip(12)]);}// 保存文件$filenamecontract_.date(YmdHis)..docx;$outputPath$this-outputDir.$filename;$template-saveAs($outputPath);return$outputPath;}privatefunctionaddProductsTable($template,$products) {// 实现添加商品表格的逻辑}}// 使用示例$generatornewContractGenerator();$contractData [basic [contract_noHT-.date(YmdHis),datedate(Y年m月d日),sellerXX科技有限公司,buyer张三],products [[nameXX智能设备,price¥5,999.00,qty 1],[name配件套装,price¥299.00,qty 2]],signature [pathsignatures/sign1.png,width 150]];$filepath$generator-generate($contractData);echo合同已生成a href$filepath下载/a;六、总结通过PHPWord库我们可以实现从模板生成标准化合同文档动态插入文本、表格和图片灵活控制文档样式和格式批量生成不同内容的合同输出为DOCX或PDF格式这种自动化方案特别适合需要频繁生成标准合同的企业可以显著提高工作效率减少人为错误并确保所有合同格式统一规范。