我正在尝试使用 PHP 应用程序中的 html2pdf.js 库创建横向 PDF 文件。我的代码从 JSON 文件获取表单响应,从这些响应生成 HTML 字符串,然后尝试将此 HTML 字符串转换为 PDF 文件。尽管在 html2pdf 选项中将方向设置为“横向”,但生成的 PDF 文件始终以纵向方向结束。我尝试了各种方法来解决这个问题,但似乎没有任何效果。以下是我的代码的相关部分:
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;
html2pdf()
.from(element)
.set({
width: 279.4,
height: 215.9,
filename: '<?php echo json_encode($form_data['name']); ?>.pdf',
pagebreak: { mode: 'avoid-all' },
margin: [ 0, 10, 10, 10], // Set the margin as needed
})
.save();
})
.catch(error => {
console.error('Error:', error);
alert('Error fetching the responses. Please try again.');
});
}
function formatPrintData(responses) {
let html = '<h3>' + <?php echo json_encode($form_data['name']); ?> + '</h3>';
html += '<p>' + <?php echo json_encode($form_data['description']); ?> + '</p>';
html += '<table border="1">';
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;
}
在此函数中,formatPrintData 是一个辅助函数,可将所选响应格式化为 HTML 字符串。
我的代码是否有任何问题导致生成的 PDF 为纵向?我将不胜感激任何建议或帮助。谢谢!
在你的代码中你有这个:
html2pdf()
.from(element)
.set({
width: 279.4,
height: 215.9,
filename: '<?php echo json_encode($form_data['name']); ?>.pdf',
pagebreak: { mode: 'avoid-all' },
margin: [ 0, 10, 10, 10], // Set the margin as needed
})
.save();
宽度和高度不是通过在 html2pdf.js Worker 上使用 .set() 调用来设置的选项。 html2pdf.js api 用于将选项传递给 html2canvas 和 jsPDF,它们在幕后使用。您可以阅读 jsPDF 属性,然后像这样设置它们:
html2pdf()
.from(element)
.set({
filename: '<?php echo json_encode($form_data['name']); ?>.pdf',
pagebreak: { mode: 'avoid-all' },
margin: [ 0, 10, 10, 10], // Set the margin as needed,
jsPDF: {
unit: "px",
format: [215.9, 279.4],
orientation: "landscape",
hotfixes: ["px_scaling"]
}
})
.save();
顺便说一句,html2pdf.js 已经有大约 2 年没有更新了,并且积累了一些错误报告和拉取请求,您可能更喜欢 html3pdf,它几乎相同(不应该需要对您的代码进行任何更改),但有一些改进。