HTML导出Word文档:如何从第二页开始显示页眉页脚
解决HTML导出Word时页眉页脚从第二页开始显示的问题
你的核心需求是让第一页无页眉页脚,从第二页开始显示对应内容。当前代码的问题在于第一页的页眉页脚(fh1、ff1)包含实际内容,即使设置了mso-title-page: yes,Word仍会渲染这些内容。以下是修正方案:
关键修改点
- 将第一页对应的页眉(
fh1)和页脚(ff1)元素设置为空,确保第一页无内容显示 - 保持
mso-first-header、mso-first-footer与空元素的绑定,同时保留mso-title-page: yes开启“首页不同”的功能
修正后的完整代码
<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40"> <head> <meta charset="utf-8" /> <!--[if gte mso 9]> <xml> <w:WordDocument><w:View>Print</w:View><w:Zoom>100</w:Zoom><w:DoNotOptimizeForBrowser /></w:WordDocument> </xml> <![endif]--> <style type="text/css"> body { font-family: Arial, sans-serif; } @page WordSection1 { size: 8.5in 11in; mso-header-space: 0.5in; mso-footer-space: 0in; mso-paper-source: 0; mso-title-page: yes; mso-first-header: fh1; mso-first-footer: ff1; mso-header: h1; mso-footer: f1; } div.WordSection1 { page: WordSection1; } /* 确保首页页眉页脚无内容且不占空间 */ #fh1, #ff1 { margin: 0; padding: 0; height: 0; overflow: hidden; } </style> </head> <body> <div class="WordSection1"> <table style="margin-left: 150in;"> <tr style="height: 1pt; mso-height-rule: exactly;"> <td> <div style="mso-element: header;" id="h1"> <p class="header" style="text-align: right;"> <img height="36" width="36" src="data:image/jpg;base64,{{headerBase64Image}}" alt="" /> </p> </div> </td> <td> <div style="mso-element: footer;" id="f1"> <p style="font-family: ff2; font-size: 9px; color: rgb(166, 166, 166); width: 100%; text-align: center; margin: 0in 0in 0pt;"> Page <span style="mso-field-code: PAGE;"></span> </p> </div> <!-- 首页页眉设为空 --> <div style="mso-element: header;" id="fh1"> <p class="MsoHeader"></p> </div> <!-- 首页页脚设为空 --> <div style="mso-element: footer;" id="ff1"> <p class="MsoFooter"></p> </div> </td> </tr> </table> <!-- 第一页内容 --> <p>第一页内容,无页眉页脚</p> <!-- 分页符,第二页开始显示页眉页脚 --> <div style="page-break-before: always;"> <p>第二页及以后的内容,显示页眉页脚</p> </div> </div> </body> </html>
额外说明
- Word对HTML/CSS的解析依赖特定的MSO属性,必须确保
mso-element: header/footer的ID与@page中mso-first-header、mso-header的取值完全匹配 - 用于存放页眉页脚的表格通过
margin-left: 150in隐藏在页面可视区域外,这是Word兼容方案中的常用技巧,不要删除 - 如果仍有问题,可尝试移除
mso-title-page: yes,直接通过空的首页页眉页脚元素实现需求(部分Word版本对mso-title-page的支持存在差异)
内容的提问来源于stack exchange,提问作者Saigal Amatya
相关产品推荐
相关产品推荐

