简体   繁体   English

jspdf 正在生成损坏的 pdf

[英]jspdf is generating a corrupted pdf

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

The pdf generated in the above fiddle is corrupted according to Acrobat reader, but renders fine in Google Chrome.根据 Acrobat 阅读器,上述小提琴中生成的 pdf 已损坏,但在 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.编辑:问题最初是问为什么与原始 pdf 相比,压缩的 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. Adobe PDF 似乎在单词之间的空格上崩溃。 One solution that may work on your case it to replace the spaces with &nbsp;一种可能适用于您的情况的解决方案将空格替换为&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/工作示例https://jsfiddle.net/8mu4hbhe/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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