如何用jsPDF将Fetch API响应数据写入PDF?解决空白PDF问题
问题:生成的PDF完全空白,如何将网站标题写入PDF?
我尝试将网站标题写入PDF,但生成的PDF完全空白。通过console.log(title)能看到正确的标题值,但推测PDF在文本写入前就已完成下载,该如何修复?
用户提供的代码:
const doc = new jsPDF(); fetch('https://api.codetabs.com/v1/proxy?quest=https://arunachaltimes.in/index.php/2022/04/27/mein-requests-vaishnaw-to-start-murkongselek-pasighat-broad-gauge-project/') .then( function (response) { response.text().then(function(data) { const parser = new DOMParser(); const htmldoc = parser.parseFromString(data, "text/html"); let title = htmldoc.getElementsByTagName("title")[0].innerText; console.log(title) //显示正确值 doc.text(10,10, title); }) } ) .catch(function(err) { console.log(err); }) doc.save('myfile.pdf'); //生成完全空白的PDF
问题原因
核心问题是异步执行顺序:fetch属于异步操作,它的回调函数会在浏览器完成网络请求后,才进入事件队列等待执行;而你的doc.save('myfile.pdf')是同步代码,会在fetch请求完成、标题解析并写入PDF之前就执行,因此保存的PDF还未写入任何内容,自然显示空白。
修复方案
方案1:将doc.save()放入异步回调的最内层
确保PDF内容写入完成后,再执行保存操作:
const doc = new jsPDF(); fetch('https://api.codetabs.com/v1/proxy?quest=https://arunachaltimes.in/index.php/2022/04/27/mein-requests-vaishnaw-to-start-murkongselek-pasighat-broad-gauge-project/') .then(response => response.text()) .then(data => { const parser = new DOMParser(); const htmldoc = parser.parseFromString(data, "text/html"); let title = htmldoc.getElementsByTagName("title")[0].innerText; console.log(title); doc.text(10, 10, title); // 写入内容后再保存PDF doc.save('myfile.pdf'); }) .catch(err => { console.log(err); });
方案2:使用async/await简化异步逻辑
如果环境支持ES6+语法,用async/await可以避免回调嵌套,让代码更易读:
async function generatePDF() { const doc = new jsPDF(); try { const response = await fetch('https://api.codetabs.com/v1/proxy?quest=https://arunachaltimes.in/index.php/2022/04/27/mein-requests-vaishnaw-to-start-murkongselek-pasighat-broad-gauge-project/'); const data = await response.text(); const parser = new DOMParser(); const htmldoc = parser.parseFromString(data, "text/html"); const title = htmldoc.getElementsByTagName("title")[0].innerText; console.log(title); doc.text(10, 10, title); doc.save('myfile.pdf'); } catch (err) { console.log(err); } } // 调用函数生成PDF generatePDF();
内容的提问来源于stack exchange,提问作者user19835820
相关产品推荐
相关产品推荐

