在Node.js中,您可以使用pdf-lib
库生成仅第一页的缩略PDF文件
步骤1: 安装pdf-lib
库,使用以下命令:
npm install pdf-lib
步骤2: 编写生成仅第一页的缩略PDF文件的代码,如下所示:
const fs = require('fs');
const { PDFDocument } = require('pdf-lib');
async function generateThumbnail(pdfPath, outputPath) {
// 读取PDF文件
const pdfBytes = fs.readFileSync(pdfPath);
// 加载PDF文档
const pdfDoc = await PDFDocument.load(pdfBytes);
// 获取第一页
const firstPage = pdfDoc.getPage(0);
// 设置缩放比例(例如,50%)
const scale = 0.5;
// 计算新的宽度和高度
const newWidth = firstPage.getWidth() * scale;
const newHeight = firstPage.getHeight() * scale;
// 创建一个新的空白PDF文档
const thumbnailDoc = await PDFDocument.create();
// 添加一个新的页面,其尺寸为新的宽度和高度
const thumbnailPage = thumbnailDoc.addPage([newWidth, newHeight]);
// 将第一页绘制到缩略图页面上
thumbnailPage.drawPage(firstPage, {
x: 0,
y: 0,
width: newWidth,
height: newHeight,
scaleX: scale,
scaleY: scale,
});
// 将缩略图PDF文档保存为文件
const thumbnailBytes = await thumbnailDoc.save();
fs.writeFileSync(outputPath, thumbnailBytes);
}
// 使用示例
const pdfPath = 'path/to/your/pdf/file.pdf';
const outputPath = 'path/to/your/output/thumbnail.pdf';
generateThumbnail(pdfPath, outputPath)
.then(() => console.log('缩略图已成功生成'))
.catch((error) => console.error('生成缩略图时出错:', error));
在上面的代码中,pdfPath
变量应替换为您要生成缩略图的PDF文件的路径,outputPath
变量应替换为生成的缩略图PDF文件的输出路径。
此代码将创建一个新的PDF文档,其尺寸为原始PDF第一页的缩放版本,并将其保存为指定的输出路径。您可以根据需要调整缩放比例。
领取专属 10元无门槛券
手把手带您无忧上云