如何通过puppeteer获取嵌入页面的pdf?

2024-01-08

我正在尝试获取一个页面的 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,中间写着“无法加载插件”。


对于其他偶然发现这个问题的人来说,

在撰写本文时,这是 chromium 中的一个已知错误,您无法导航到 pdf 或嵌入 pdf 的页面headless:true mode.

我找到了一个临时解决方案here https://github.com/GoogleChrome/puppeteer/issues/610,尽管您必须事先知道获取 pdf 的 url。

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);
            });
        });
    });

在上一页中,您必须使用评估调用并获取 api 来获取 pdf,以最初获取缓冲区响应并进行转换:

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);
   }); 
 });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何通过puppeteer获取嵌入页面的pdf? 的相关文章

随机推荐