node.js实现pdf与图片互转代码示例
更新时间:2024年04月10日 08:46:31 作者:#老程
因工作需求,记录一次如何在Node中pdf与图片互转各种操作,这篇文章主要给大家介绍了关于node.js实现pdf与图片互转的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下
PDF转图片
效果图

代码
const path = require('path');
const pdf = require('pdf-poppler');
const fs = require('fs');
// PDF文件路径
const pdfFilePath = './path/test.pdf';
// 转换选项
const opts = {
format: 'png', // 输出图片格式,可以是 'jpeg', 'png', 'ppm', 'tiff', 'xps', 'xml', 'xps1', 'xps2' 等
out_dir: './path/output', // 输出目录
out_prefix: 'outputImg', // 输出文件的前缀
page: null // 要转换的页码,可以是具体的页码或者一个页码范围,例如 [1, 3, 5] 或者 '1-5'
};
// 转换PDF为图片
pdf.convert(pdfFilePath, opts)
.then(res => {
console.log('Successfully converted:', res);
// res 是一个包含转换后图片文件路径的数组
// 例如:['./output/output-1.jpeg', './output/output-2.jpeg']
})
.catch(error => {
console.error('Error converting PDF to images:', error);
});
图片转PDF
效果图如下

代码:
const PDFDocument = require('pdfkit');
const fs = require('fs');
const path = require('path');
// 创建一个PDF文档
const doc = new PDFDocument();
// 设置文档元数据(可选)
doc.info.title = 'My Image to PDF';
// 将PDF文档流写入一个文件
const outputStream = fs.createWriteStream(path.resolve('./path/output/output.pdf'));
doc.pipe(outputStream);
// 将图片添加到PDF文档中
doc.image('./path/zgr.jpg', {
width: 500, // 设置图片宽度
height: 300, // 设置图片高度
fit: [500, 300] // 或者使用fit来适应指定尺寸
});
// 结束文档并关闭流
doc.end();
outputStream.on('finish', () => {
console.log('PDF生成完成');
});
outputStream.on('error', (err) => {
console.error('PDF生成出错:', err);
});总结
到此这篇关于node.js实现pdf与图片互转的文章就介绍到这了,更多相关nodejs pdf与图片互转内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
您可能感兴趣的文章:
相关文章
nodejs和npm版本不匹配:ERROR: npm v9.5.1 is known not to run
本文主要介绍了nodejs和npm版本不匹配:ERROR: npm v9.5.1 is known not to run on Node.js,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2023-06-06
Node.js中的http请求客户端示例(request client)
本篇文章主要介绍了Node.js中的http请求客户端示例(request client),具有一定的参考价值,感兴趣的小伙伴们可以参考一下2017-05-05
node+express框架中连接使用mysql(经验总结)
这篇文章主要介绍了node+express框架中连接使用mysql(经验总结),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-11-11


最新评论