如何通过pdf-lib编程重置PDF页面旋转值为0(不实际旋转)
如何用pdf-lib重置PDF页面旋转值为0(不实际旋转页面)
可以实现,以下是具体方案:
原理说明
PDF页面的旋转值(Rotate)是存储在页面字典中的标记属性,我们只需直接修改该属性为0,无需调整页面内容的实际布局或坐标,就能完成重置操作。
实现步骤与代码
1. 安装依赖
首先确保安装pdf-lib:
npm install pdf-lib
2. 处理代码(Node.js环境)
const { PDFDocument } = require('pdf-lib'); const fs = require('fs').promises; async function resetPageRotation(inputPath, outputPath) { // 读取目标PDF文件 const pdfBytes = await fs.readFile(inputPath); // 加载PDF文档 const pdfDoc = await PDFDocument.load(pdfBytes); // 遍历所有页面,重置旋转值 pdfDoc.getPages().forEach(page => { const currentRotation = page.getRotation(); // 仅处理90度倍数的旋转值 if (currentRotation % 90 === 0) { page.setRotation(0); } }); // 保存修改后的PDF const modifiedPdfBytes = await pdfDoc.save(); await fs.writeFile(outputPath, modifiedPdfBytes); console.log('页面旋转值已成功重置为0'); } // 调用示例(替换为你的文件路径) resetPageRotation('./90.pdf', './reset-rotation.pdf') .catch(err => console.error('处理失败:', err));
关键API说明
page.getRotation():获取页面当前的旋转属性值page.setRotation(0):直接将页面旋转标记设为0,不会改动页面内容的实际显示位置
内容的提问来源于stack exchange,提问作者Shun.Tagami
相关产品推荐
相关产品推荐

