https://jsfiddle.net/yt92n1pt/49/
根据 Acrobat 阅读器,上述 fiddle 中生成的 pdf 已损坏,但在 Google Chrome 中呈现良好。为什么会发生这种情况,我该如何避免?
编辑:问题最初是问为什么压缩 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 似乎在单词之间的空格上崩溃。
一种可能适用于您的情况的解决方案是用
替换空格。
为了让它有点动态,我们需要替换任何没有任何其他 child (里面只有文本)的 child 中的空格。
// 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, ' ');
}
}
关于javascript - jspdf 正在生成损坏的 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49412461/