Node.js中如何将字节数组转为PDF,并将外部服务字节流转为服务响应?
Hey there! Let's tackle these two Node.js PDF handling scenarios step by step—they're super common when working with document-based services.
If you've got a byte array (usually a Uint8Array in JavaScript) and want to save it as a PDF file on your filesystem, Node.js's built-in fs module is all you need. The key here is converting the byte array to a Node.js Buffer first, since fs works seamlessly with Buffers for binary data.
Here's a practical example:
const fs = require('fs'); const path = require('path'); // 假设这是你的输入字节数组(比如从数据库或另一个服务获取的) const pdfByteArray = new Uint8Array([/* 你的字节数据 */]); // 将Uint8Array转换为Node.js Buffer const pdfBuffer = Buffer.from(pdfByteArray); // 写入到本地PDF文件 fs.writeFile(path.join(__dirname, 'generated.pdf'), pdfBuffer, (err) => { if (err) { console.error('Failed to write PDF file:', err); return; } console.log('PDF file saved successfully!'); }); // 如果你更喜欢同步写法(适合脚本,不推荐在服务端请求处理中使用): // fs.writeFileSync(path.join(__dirname, 'generated.pdf'), pdfBuffer);
Quick note: If your byte array is already a Buffer (common in Node.js), you can skip the Buffer.from() step and write it directly to the file.
When you call an external service that returns a PDF as a byte stream, you need to ensure you capture the raw binary data first, then convert it to a byte array (or pass it directly as a response to your own clients).
Let's use axios for the external request (a popular HTTP client) and Express for our own service:
const express = require('express'); const axios = require('axios'); const app = express(); app.get('/get-proxied-pdf', async (req, res) => { try { // 调用外部服务时,必须设置responseType为'arraybuffer'以获取原始字节数据 const externalServiceResponse = await axios.get('https://your-external-service.com/pdf-endpoint', { responseType: 'arraybuffer' }); // 将返回的二进制数据转换为字节数组(Uint8Array) const pdfByteArray = new Uint8Array(externalServiceResponse.data); // 设置响应头,让客户端识别这是PDF文件 res.setHeader('Content-Type', 'application/pdf'); res.setHeader('Content-Disposition', 'inline; filename="proxied.pdf"'); // 或者用'attachment'让浏览器下载 // 将字节数组作为响应发送——Express会自动处理为Buffer res.send(pdfByteArray); // 替代方案:如果不需要显式转成Uint8Array,直接发送Buffer也可以: // res.send(externalServiceResponse.data); } catch (error) { console.error('Error fetching PDF from external service:', error); res.status(500).send('Failed to retrieve PDF'); } }); app.listen(3000, () => { console.log('Service running on port 3000'); });
Key point: Setting responseType: 'arraybuffer' is critical here. Without it, axios will try to parse the response as a UTF-8 string, which will corrupt the PDF binary data.
内容的提问来源于stack exchange,提问作者Sowmya Poovannan




