jspdf正在生成一个损坏的pdf

时间:2018-03-21 17:02:27

标签: javascript pdf zip jspdf jszip

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

根据Acrobat阅读器,上述小提琴中生成的pdf已损坏,但在Google Chrome中呈现正常。为什么会发生这种情况,我该如何避免呢?

编辑:问题最初是在询问为什么压缩pdf的内容与原始pdf相比有所不同。但事实并非如此。

Original PDF Zipped 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();
  }
}

1 个答案:

答案 0 :(得分:1)

Adob​​e PDF似乎在单词之间的空格上崩溃。 一个可能适用于您的情况的解决方案,用&nbsp;替换空格。

为了使它有点动态,我们需要替换任何没有其他孩子的孩子的空间(里面只有文字)。

// 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;');
    }
}

工作示例https://jsfiddle.net/8mu4hbhe/2/

相关问题