js实现pdf旋转
使用PDF.js实现PDF旋转
PDF.js是一个由Mozilla开发的JavaScript库,用于在浏览器中渲染PDF文件。通过PDF.js可以实现PDF页面的旋转功能。
安装PDF.js库:
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.min.js"></script>
旋转PDF页面的代码示例:
// 初始化PDF.js
pdfjsLib.getDocument('yourfile.pdf').promise.then(function(pdf) {
// 获取第一页
pdf.getPage(1).then(function(page) {
const viewport = page.getViewport({ scale: 1.0 });
// 创建canvas元素
const canvas = document.getElementById('pdf-canvas');
const context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
// 渲染页面(不旋转)
page.render({
canvasContext: context,
viewport: viewport
});
// 旋转90度
const rotatedViewport = page.getViewport({
scale: 1.0,
rotation: 90
});
canvas.height = rotatedViewport.height;
canvas.width = rotatedViewport.width;
page.render({
canvasContext: context,
viewport: rotatedViewport
});
});
});
使用PDF-LIB实现PDF旋转
PDF-LIB是一个更现代的JavaScript库,用于创建和修改PDF文档。

安装PDF-LIB:
npm install pdf-lib
旋转PDF页面的代码示例:

import { PDFDocument } from 'pdf-lib';
async function rotatePdf() {
// 加载现有PDF
const existingPdfBytes = await fetch('input.pdf').then(res => res.arrayBuffer());
const pdfDoc = await PDFDocument.load(existingPdfBytes);
// 获取所有页面
const pages = pdfDoc.getPages();
// 旋转每一页(90度)
pages.forEach(page => {
page.setRotation(90);
});
// 保存修改后的PDF
const pdfBytes = await pdfDoc.save();
download(pdfBytes, 'rotated.pdf', 'application/pdf');
}
function download(data, filename, type) {
const blob = new Blob([data], { type });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = filename;
link.click();
}
使用浏览器打印API旋转PDF
对于简单的查看场景,可以使用浏览器的打印功能实现旋转:
function printWithRotation() {
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = 'document.pdf';
document.body.appendChild(iframe);
iframe.onload = function() {
setTimeout(() => {
iframe.contentWindow.print();
document.body.removeChild(iframe);
}, 1000);
};
// 在打印对话框中手动选择旋转选项
}
使用服务端旋转PDF
如果需要永久旋转PDF文件,可以考虑使用服务端解决方案:
Node.js示例(使用pdf-lib):
const fs = require('fs');
const { PDFDocument } = require('pdf-lib');
async function rotatePdfFile(inputPath, outputPath) {
const pdfBytes = fs.readFileSync(inputPath);
const pdfDoc = await PDFDocument.load(pdfBytes);
const pages = pdfDoc.getPages();
pages.forEach(page => page.setRotation(180)); // 旋转180度
const rotatedPdf = await pdfDoc.save();
fs.writeFileSync(outputPath, rotatedPdf);
}
rotatePdfFile('input.pdf', 'output.pdf');
每种方法适用于不同场景:PDF.js适合浏览器内查看时临时旋转,PDF-LIB适合需要修改并保存PDF文件,服务端方案适合批量处理PDF文件。





