我需要将HTML转换为PDF。我已经尝试过jsPDF,并在stackoverflow上阅读了很多与此相关的问题。我已经尝试了所有存在的方法,例如html(),fromHtml,html2pdf和html2canvas。但是它们都有各种问题。缺少内容,模糊内容或边距都会完全消失。
所以我正在尝试另一条路线。我发现以下代码片段可以转换为Word文档。这可行。
function exportHTML(){
var header = "<html xmlns:o='urn:schemas-microsoft-com:office:office' "+
"xmlns:w='urn:schemas-microsoft-com:office:word' "+
"xmlns='http://www.w3.org/TR/REC-html40'>"+
"<head><meta charset='utf-8'><title>Export HTML to Word Document with JavaScript</title></head><body>";
var footer = "</body></html>";
var sourceHTML = header+document.getElementById("source-html").innerHTML+footer;
var source = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(sourceHTML);
var fileDownload = document.createElement("a");
document.body.appendChild(fileDownload);
fileDownload.href = source;
fileDownload.download = 'document.doc';
fileDownload.click();
document.body.removeChild(fileDownload);
}
但是,我不希望下载Word文件。我需要捕获它并将其转换为base64字符串,因为然后我可以将其发送到可以将Word文档转换为pdf的rest api。其余的api不直接支持html,否则我只会发送html。因此,解决方法是先用词再用pdf。 ps由于敏感信息,我无法使用在线pdf解决方案,其余api是内部服务。
最佳答案
但是,我不希望下载Word文件。我需要捕获它并将其转换为base64字符串,因为然后我可以将其发送到可以将Word文档转换为pdf的rest api。
然后,无需将其插入下载链接。只是base64使用btoa
编码字符串:
function exportHTML(){
var header = "<html xmlns:o='urn:schemas-microsoft-com:office:office' "+
"xmlns:w='urn:schemas-microsoft-com:office:word' "+
"xmlns='http://www.w3.org/TR/REC-html40'>"+
"<head><meta charset='utf-8'><title>Export HTML to Word Document with JavaScript</title></head><body>";
var footer = "</body></html>";
var sourceHTML = header+document.getElementById("source-html").innerHTML+footer;
var source = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(sourceHTML);
// encode here instead of creating a link
var encoded = window.btoa(source);
return encoded;
}
然后,您可以随意使用
XMLHttpRequest
将编码的字符串发送到您的API端点。例如。:var encodedString = exportHTML();
var xhr = new XMLHttpRequest();
xhr.open('POST', '/my-conversion-endpoint', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
// request finished
alert(xhr.responseText);
}
}
xhr.send('encodedString=' + encodedString);
关于javascript - 将HTML转换为Word然后转换为pdf,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58139662/