PHP项目中使用html2pdf.js生成PDF无法设置横向的问题
问题分析与解决方案
核心问题
你提供的代码中缺少orientation: 'landscape'的配置项——虽然你提到尝试设置了横向,但在html2pdf().set()的参数对象里并没有这个属性,html2pdf会默认使用纵向(portrait)生成PDF。
另外,你硬设置的width: 279.4和height: 215.9会和orientation配置冲突,因为html2pdf会根据orientation自动匹配纸张的宽高逻辑,手动指定尺寸可能覆盖横向设置的效果。
修复步骤
添加横向配置
在set()的配置对象中明确加入orientation: 'landscape',这是开启横向模式的关键。移除冲突的宽高设置
删除手动设置的width和height参数,让html2pdf根据orientation自动适配纸张尺寸(比如A4横向的默认尺寸是宽297mm、高210mm)。如果需要自定义纸张尺寸,改用format参数配合unit来定义(格式为[宽度, 高度])。确保HTML内容适配横向页面
给生成的HTML容器或内容添加宽度适配样式,避免内容过宽导致页面被挤压回纵向:- 给动态生成的DIV添加样式:
element.style.width = '100%'; - 给表格添加样式:
html += '<table border="1" style="width:100%;table-layout:fixed;">';,防止表格超出页面宽度。
- 给动态生成的DIV添加样式:
修改后的代码示例
function generatePrintReport(indexes) { // Fetch the JSON file fetch('responses/form_<?php echo $id; ?>.json') .then(response => response.json()) .then(data => { const selectedResponses = indexes.map(index => data[index]); const printData = formatPrintData(selectedResponses); // Generate PDF using html2pdf.js library const element = document.createElement('DIV'); element.innerHTML = printData; // 添加宽度适配样式 element.style.width = '100%'; element.style.maxWidth = '279mm'; // 对应你之前的自定义宽度 html2pdf() .from(element) .set({ orientation: 'landscape', // 关键:添加横向配置 filename: '<?php echo json_encode($form_data['name']); ?>.pdf', pagebreak: { mode: 'avoid-all' }, margin: [0, 10, 10, 10], // 如果需要自定义纸张尺寸,取消下面注释 // format: [279.4, 215.9], // unit: 'mm' }) .save(); }) .catch(error => { console.error('Error:', error); alert('Error fetching the responses. Please try again.'); }); } // formatPrintData函数保持不变,建议给table添加宽度样式 function formatPrintData(responses) { let html = '<h3>' + <?php echo json_encode($form_data['name']); ?> + '</h3>'; html += '<p>' + <?php echo json_encode($form_data['description']); ?> + '</p>'; // 给table添加宽度适配样式 html += '<table border="1" style="width:100%;table-layout:fixed;">'; html += '<tr><th>#</th>'; // Add table headers const quesHeaders = <?php echo json_encode($ques_data); ?>; quesHeaders.forEach(header => { html += '<th>' + header.ques + '</th>'; }); html += '<th>Verified by</th></tr>'; // Add table rows responses.forEach(response => { html += '<tr>'; html += '<td>' + (response.id || '') + '</td>'; Object.keys(response).forEach(key => { if (key !== 'id') { html += '<td>' + (response[key] || '') + '</td>'; } }); html += '<td>' + (response.verified || '') + '</td>'; html += '</tr>'; }); html += '</table>'; html += '<p class="signa">Signature:____________________________________ Date:_____________</p>' return html; }
额外排查点
- 如果仍不生效,检查html2pdf的版本,建议升级到最新稳定版,旧版本可能存在orientation配置的兼容性问题。
- 可以直接通过
jsPDF配置项强制设置:set({ jsPDF: { orientation: 'l', // 'l'代表landscape,'p'代表portrait unit: 'mm', format: 'a4' } })
内容的提问来源于stack exchange,提问作者farmerm3
相关产品推荐
相关产品推荐

