Javascript функция перестает работать при добавлении изображения - PullRequest
0 голосов
/ 25 апреля 2020

Я пытаюсь создать инструмент для генерации PDF, и он работает, за исключением случаев, когда я добавляю изображение в div.encabezado. Я пытался использовать другие элементы, такие как div с встроенным фоновым изображением, и я также пытался использовать его собственный раздел. но каждый раз, когда я получаю, чтобы это выглядело, как мне нужно, это прекращает генерировать PDF. Я знаю, что код правильный, потому что, если я изменю или раскомментирую изображение sr c или изменим div id, оно будет работать правильно

 <style>
/* Style the header */
header {
  background-color: #fff;
  text-align: center;
  font-size: 35px;
  color: black;
  height:15%;
}

div.encabezado{
    backgroundImage: url("sgh.png");
}

/* Style the footer */
footer {
  background-color: #777;
  padding: 10px;
  text-align: center;
  color: white;
}

/* Responsive layout - makes the two columns/boxes stack on top of each other instead of next to each other, on small screens */
@media (max-width: 600px) {
  nav, article {
    width: 100%;
    height: auto;
  }
}
</style>


<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>

<script>
function getPDF(){

 var HTML_Width = $(".canvas_div_pdf").width();
 var HTML_Height = $(".canvas_div_pdf").height();
 var top_left_margin = 15;
 var PDF_Width = HTML_Width+(top_left_margin*2);
 var PDF_Height = (PDF_Width*1.5)+(top_left_margin*2);
 var canvas_image_width = HTML_Width;
 var canvas_image_height = HTML_Height;

 var totalPDFPages = Math.ceil(HTML_Height/PDF_Height)-1;


 html2canvas($(".canvas_div_pdf")[0],{allowTaint:true}).then(function(canvas) {
 canvas.getContext('2d');

 console.log(canvas.height+"  "+canvas.width);


 var imgData = canvas.toDataURL("image/jpeg", 1.0);
 var pdf = new jsPDF('p', 'pt',  [PDF_Width, PDF_Height]);
     pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin,canvas_image_width,canvas_image_height);


 for (var i = 1; i <= totalPDFPages; i++) { 
 pdf.addPage(PDF_Width, PDF_Height);
 pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height*i)+(top_left_margin*4),canvas_image_width,canvas_image_height);
 }

     pdf.save("HTML-Document.pdf");
        });
 };
  </script>
 <div class="canvas_div_pdf">




 <div id="encabezado">
//<image src="sgh.png">
</div>

<section>
 <div style="height:120px;width:120px;border:1px solid;overflow:auto;">
As you can see, once there's enough text in this box, the box will grow scroll bars... that's why we call it a scroll box! You could also place an image into the scroll box.
</div>
 <div style="height:120px;width:120px;border:1px solid;overflow:auto;">
As you can see, once there's enough text in this box, the box will grow scroll bars... that's why we call it a scroll box! You could also place an image into the scroll box.
</div>
</section>

<footer>
  <p>Footer</p>
</footer>





<button onclick="getPDF()">Click me</button> 
</div>

1 Ответ

0 голосов
/ 25 апреля 2020

Вы можете попробовать добавить эту опцию к опциям html2canvas:

foreignObjectRendering: true

Более подробную информацию вы можете найти здесь: https://html2canvas.hertzen.com/configuration/ Кроме того, проверьте эту другую статью: https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image, что может помочь вам понять, что происходит.

Кроме того, если вы тестируете это локально, проверьте конфигурацию вашего веб-сервера и настройки cors.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...