简体   繁体   English

如何将缓冲区转换为 pdf/docx

[英]How to convert buffer into pdf/docx

        await newPage.setRequestInterception(true);
        const xRequest = await new Promise(resolve => {
            newPage.on('request', interceptedRequest => {
                interceptedRequest.abort();     //stop intercepting requests
                resolve(interceptedRequest);
            });
        });

        const options = {
            encoding: null,
            method: xRequest._method,
            uri: xRequest._url,
            body: xRequest._postData,
            headers: xRequest._headers
        }
        
        const cookies = await newPage.cookies();
        options.headers.Cookie = cookies.map(ck => ck.name + '=' + ck.value).join(';');
        
        const res = await request(options);

I'm using puppeteer and trying to download some pdf/docx and getting res as buffer.我正在使用 puppeteer 并尝试下载一些 pdf/docx 并将 res 作为缓冲区。 How can I check the file type from buffer (res) and convert it to that particular file type.如何检查缓冲区(res)中的文件类型并将其转换为该特定文件类型。

if you have the buffer in your hands you dont need to "convert" it.如果您手中有缓冲区,则无需“转换”它。 you can for exemple write it to a file and you will be able to open it with your explorer for example.例如,您可以将其写入文件,例如,您可以使用资源管理器打开它。

fs.writeFile('filename.pdf', buffer);

Also, the solution to your question already exist here: Detecting file type from buffer in node js?此外,您的问题的解决方案已经存在: Detecting file type from buffer in node js? please take time to find already existing solutions on stack overflow before posting.在发布之前,请花时间查找现有的堆栈溢出解决方案。

a buffer contains a pdf if the first bytes are [0x25, 0x50, 0x44, 0x46] you can simply test it like this:一个缓冲区包含一个 pdf 如果第一个字节是 [0x25, 0x50, 0x44, 0x46] 你可以像这样简单地测试它:

var isPdf = (buffer[0] == 0x25 && buffer[1] == 0x50 && buffer[2] == 0x44 && buffer[3] == 0x46);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM