HTML2PDF未创建横向方向的PDF。

huangapple go评论55阅读模式
英文:

HTML2PDF not creating landscape orientation PDF

问题

我尝试在PHP应用程序中使用html2pdf.js库创建横向方向的PDF文件。我的代码从JSON文件中获取表单响应,生成HTML字符串,然后尝试将此HTML字符串转换为PDF文件。尽管在html2pdf选项中设置了方向为“landscape”,但生成的PDF文件始终以纵向方向显示。我已尝试多种方法来解决此问题,但似乎没有任何作用。以下是我的代码的相关部分:

function generatePrintReport(indexes) {
  // 获取JSON文件
  fetch('responses/form_<?php echo $id; ?>.json')
    .then(response => response.json())
    .then(data => {
      const selectedResponses = indexes.map(index => data[index]);
      const printData = formatPrintData(selectedResponses);

      // 使用html2pdf.js库生成PDF
      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], // 根据需要设置边距
        })
        .save();
    })
    .catch(error => {
      console.error('Error:', error);
      alert('获取响应时出错,请重试。');
    });
}

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>';

  // 添加表头
  const quesHeaders = <?php echo json_encode($ques_data); ?>;
  quesHeaders.forEach(header => {
    html += '<th>' + header.ques + '</th>';
  });

  html += '<th>Verified by</th></tr>';

  // 添加表格行
  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文件以纵向方向显示?如果有任何建议或帮助,我将不胜感激。谢谢!

英文:

I'm trying to create a PDF file in landscape orientation using the html2pdf.js library in a PHP application. My code fetches form responses from a JSON file, generates a HTML string from these responses, and then attempts to convert this HTML string to a PDF file. Despite setting the orientation to 'landscape' in the html2pdf options, the generated PDF file always ends up in portrait orientation. I've tried various ways to fix this issue, but nothing seems to work. Below is the relevant portion of my code:

    function generatePrintReport(indexes) {
// Fetch the JSON file
fetch(&#39;responses/form_&lt;?php echo $id; ?&gt;.json&#39;)
.then(response =&gt; response.json())
.then(data =&gt; {
const selectedResponses = indexes.map(index =&gt; data[index]);
const printData = formatPrintData(selectedResponses);
// Generate PDF using html2pdf.js library
const element = document.createElement(&#39;DIV&#39;);
element.innerHTML = printData;
html2pdf()
.from(element)
.set({
width: 279.4,
height: 215.9,
filename: &#39;&lt;?php echo json_encode($form_data[&#39;name&#39;]); ?&gt;.pdf&#39;,
pagebreak: { mode: &#39;avoid-all&#39; },
margin: [ 0, 10, 10, 10], // Set the margin as needed
})
.save();
})
.catch(error =&gt; {
console.error(&#39;Error:&#39;, error);
alert(&#39;Error fetching the responses. Please try again.&#39;);
});
}
function formatPrintData(responses) {
let html = &#39;&lt;h3&gt;&#39; + &lt;?php echo json_encode($form_data[&#39;name&#39;]); ?&gt; + &#39;&lt;/h3&gt;&#39;;
html += &#39;&lt;p&gt;&#39; + &lt;?php echo json_encode($form_data[&#39;description&#39;]); ?&gt; + &#39;&lt;/p&gt;&#39;;
html += &#39;&lt;table border=&quot;1&quot;&gt;&#39;;
html += &#39;&lt;tr&gt;&lt;th&gt;#&lt;/th&gt;&#39;;
// Add table headers
const quesHeaders = &lt;?php echo json_encode($ques_data); ?&gt;;
quesHeaders.forEach(header =&gt; {
html += &#39;&lt;th&gt;&#39; + header.ques + &#39;&lt;/th&gt;&#39;;
});
html += &#39;&lt;th&gt;Verified by&lt;/th&gt;&lt;/tr&gt;&#39;;
// Add table rows
responses.forEach(response =&gt; {
html += &#39;&lt;tr&gt;&#39;;
html += &#39;&lt;td&gt;&#39; + (response.id || &#39;&#39;) + &#39;&lt;/td&gt;&#39;;
Object.keys(response).forEach(key =&gt; {
if (key !== &#39;id&#39;) {
html += &#39;&lt;td&gt;&#39; + (response[key] || &#39;&#39;) + &#39;&lt;/td&gt;&#39;;
}
});
html += &#39;&lt;td&gt;&#39; + (response.verified || &#39;&#39;) + &#39;&lt;/td&gt;&#39;;
html += &#39;&lt;/tr&gt;&#39;;
});
html += &#39;&lt;/table&gt;&#39;;
html += &#39;&lt;p class=&quot;signa&quot;&gt;Signature:____________________________________ Date:_____________&lt;/p&gt;&#39;
return html;
}

In this function, formatPrintData is a helper function that formats the selected responses into a HTML string.

Is there anything wrong with my code that's causing the generated PDF to be in portrait orientation? I would appreciate any suggestions or help. Thanks!

答案1

得分: 1

你的代码中有以下内容:

html2pdf()
  .from(element)
  .set({
    width: 279.4,
    height: 215.9,
    filename: '&lt;?php echo json_encode($form_data[&#39;name&#39;]); ?&gt;.pdf',
    pagebreak: { mode: 'avoid-all' },
    margin: [ 0, 10, 10, 10], // 根据需要设置边距
  })
  .save();

宽度和高度不是通过html2pdf.js工作器上的.set()调用设置的选项。html2pdf.js API用于传递选项给在底层使用的html2canvas和jsPDF,您可以阅读jsPDF属性,然后像这样设置它们:

html2pdf()
  .from(element)
  .set({
    filename: '&lt;?php echo json_encode($form_data[&#39;name&#39;]); ?&gt;.pdf',
    pagebreak: { mode: 'avoid-all' },
    margin: [ 0, 10, 10, 10], // 根据需要设置边距
    jsPDF: {
      unit: "px",
      format: [215.9, 279.4],
      orientation: "landscape",
      hotfixes: ["px_scaling"]
    }
  })
  .save();

顺便说一下,html2pdf.js已经有大约两年没有更新了,并且积累了一些错误报告和拉取请求,您可能更喜欢html3pdf,它几乎相同(不应需要对您的代码进行任何更改),但有一些改进。

英文:

In your code you have this:

  html2pdf()
.from(element)
.set({
width: 279.4,
height: 215.9,
filename: &#39;&lt;?php echo json_encode($form_data[&#39;name&#39;]); ?&gt;.pdf&#39;,
pagebreak: { mode: &#39;avoid-all&#39; },
margin: [ 0, 10, 10, 10], // Set the margin as needed
})
.save();

Width and height are not options that are set by using the .set() call on the html2pdf.js worker. The html2pdf.js api is for you to pass options to html2canvas and jsPDF, which are used under the hood. You can read about the jsPDF properties and then set them like this:

  html2pdf()
.from(element)
.set({
filename: &#39;&lt;?php echo json_encode($form_data[&#39;name&#39;]); ?&gt;.pdf&#39;,
pagebreak: { mode: &#39;avoid-all&#39; },
margin: [ 0, 10, 10, 10], // Set the margin as needed,
jsPDF: {
unit: &quot;px&quot;,
format: [215.9, 279.4],
orientation: &quot;landscape&quot;,
hotfixes: [&quot;px_scaling&quot;]
}
})
.save();

By the way, html2pdf.js has not been updated in ~2 years and has accumulated some bug reports and pull requests, you may prefer html3pdf which is almost the same (should not require any changes to your code) but with some improvements.

huangapple
  • 本文由 发表于 2023年7月3日 23:15:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76606062.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定