简体   繁体   中英

jspdf is generating a corrupted pdf

https://jsfiddle.net/yt92n1pt/49/

The pdf generated in the above fiddle is corrupted according to Acrobat reader, but renders fine in Google Chrome. Why does this happen and how can I avoid it?

Edit: The question was originally asking why the contents of a zipped pdf were different when compared to the original pdf. But that's not the case.

原始PDF 压缩PDF

window.create_zip = function() {
  var pdf = new jsPDF('p', 'pt', 'a4');
  addHtml(document.getElementById('tables').outerHTML, pdf).then(function(){
    var zip = new JSZip();
    zip.file("notok.pdf", pdf.output());
    zip.generateAsync({
      type: "blob"
    })
      .then(function(content) {
      saveAs(content, "example.zip");
    });
  });
}

window.create_pdf = function() {
  var pdf = new jsPDF('p', 'pt', 'a4');
  addHtml(document.getElementById('tables').outerHTML, pdf).then(function(){
    pdf.save('ok.pdf');
  });
}


function addHtml(html, doc) {
  var canvas = doc.canvas;
  canvas.pdf = doc;

  html = html.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');

  var div = document.createElement('div');
  div.setAttribute('style','position:fixed;left:15px; top:15px; display: none');
  div.setAttribute('id', 'hidden_div_123');
  document.body.insertBefore(div, document.body.firstChild);
  div.insertAdjacentHTML('beforeend', html);

  return html2canvas(div.firstChild, {canvas : canvas, onclone: _onclone}).then(function(canvas) {
    if (div) {
      div.parentElement.removeChild(div);
    }
  });

  function _onclone(clone) {
    $(clone.getElementById('hidden_div_123')).show();
  }
}

Adobe PDF seems to crash on the spaces between words. One solution that may work on your case it to replace the spaces with &nbsp; .

In order to make it a little dynamic, we need to replace the spaces in any child that don't have any other child (that has only text inside).

// Replace spaces with non-breaking space (nbsp)
var tags = div.getElementsByTagName('*');
for(var i = 0; i < tags.length; i++){
    if (tags[i].children.length == 0 && tags[i].innerHTML.length > 0) {
        tags[i].innerHTML = tags[i].innerHTML.replace(/ /gm, '&nbsp;');
    }
}

Working example https://jsfiddle.net/8mu4hbhe/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM