繁体   English   中英

jspdf 正在生成损坏的 pdf

[英]jspdf is generating a corrupted pdf

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

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

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

原始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 似乎在单词之间的空格上崩溃。 一种可能适用于您的情况的解决方案将空格替换为&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/

暂无
暂无

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

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