我正在尝试获取结构如下的页面的pdf副本:
<body style="background-color: rgb(38,38,38); height: 100%; width: 100%; overflow: hidden; margin: 0">
<embed width="100%" height="100%" name="plugin" id="plugin" src="https://www.thesourceurl.com" type="application/pdf" internalinstanceid="7" title="">
</body>
我尝试用page.pdf
获取它但是我得到了一个空白的pdf,中间写着“无法加载插件”。
答案 0 :(得分:1)
这似乎是Puppeteer中的一个错误。它绝对适用于早期版本。
答案 1 :(得分:0)
对于偶然发现这个问题的其他人,
在撰写本文时,这是Chrome中的一个已知错误,您无法在headless:true
模式下导航到pdf或嵌入pdf的页面。
我找到了这个here的临时解决方案,但您必须知道您将事先获得pdf的网址。
page.exposeFunction("writeABString", async (strbuf, targetFile) => {
var str2ab = function _str2ab(str) { // Convert a UTF-8 String to an ArrayBuffer
var buf = new ArrayBuffer(str.length); // 1 byte for each char
var bufView = new Uint8Array(buf);
for (var i=0, strLen=str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
console.log("In 'writeABString' function...");
return new Promise((resolve, reject) => {
// Convert the ArrayBuffer string back to an ArrayBufffer, which in turn is converted to a Buffer
let buf = Buffer.from(str2ab(strbuf));
// Try saving the file.
fs.writeFile(targetFile, buf, (err, text) => {
if(err) reject(err);
else resolve(targetFile);
});
});
});
在上一页,您需要获取pdf,使用evaluate调用并获取api以初始获取缓冲区响应并转换相同的内容:
page.evaluate( async () => {
function arrayBufferToString(buffer){ // Convert an ArrayBuffer to an UTF-8 String
var bufView = new Uint8Array(buffer);
var length = bufView.length;
var result = '';
var addition = Math.pow(2,8)-1;
for(var i = 0;i<length;i+=addition){
if(i + addition > length){
addition = length - i;
}
result += String.fromCharCode.apply(null, bufView.subarray(i,i+addition));
}
return result;
}
let geturl = "https://whateverurl.example.com";
return fetch(geturl, {
credentials: 'same-origin', // usefull when we are logged into a website and want to send cookies
responseType: 'arraybuffer', // get response as an ArrayBuffer
})
.then(response => response.arrayBuffer())
.then( arrayBuffer => {
var bufstring = arrayBufferToString(arrayBuffer);
return window.writeABString(bufstring, '/tmp/downloadtest.pdf');
})
.catch(function (error) {
console.log('Request failed: ', error);
});
});