如何使用iTextSharp将PDF旋转90度?参数调整遇问题求帮助
解决iTextSharp旋转PDF90度的问题
别担心,我太懂你调整AddTemplate参数时的崩溃感了——要么页面缩成一半,要么直接消失,这大多是没处理好PDF的坐标系变换和页面尺寸适配。我来给你一套靠谱的实现方案:
核心思路
PDF的坐标系原点在页面左下角,旋转90度时,不仅要设置旋转矩阵,还要通过平移参数把旋转后的页面拉回可视区域,同时必须同步调整新文档的页面尺寸(因为旋转后宽高互换了),否则肯定会出现裁剪或缩放问题。
完整代码示例
下面是顺时针/逆时针旋转90度的完整实现,你可以直接套用:
using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; public void RotatePdf90Degrees(string inputPath, string outputPath, bool clockwise = true) { using (PdfReader reader = new PdfReader(inputPath)) using (FileStream outputStream = new FileStream(outputPath, FileMode.Create)) { Document document = new Document(); PdfWriter writer = PdfWriter.GetInstance(document, outputStream); document.Open(); PdfContentByte contentByte = writer.DirectContent; for (int pageNum = 1; pageNum <= reader.NumberOfPages; pageNum++) { Rectangle originalSize = reader.GetPageSize(pageNum); // 旋转后页面宽高互换,设置新的页面尺寸 document.SetPageSize(new Rectangle(originalSize.Height, originalSize.Width)); document.NewPage(); PdfImportedPage importedPage = writer.GetImportedPage(reader, pageNum); if (clockwise) { // 顺时针旋转90度:变换矩阵+平移偏移,确保页面在可视区域 contentByte.AddTemplate(importedPage, 0, 1, -1, 0, originalSize.Height, 0); } else { // 逆时针旋转90度 contentByte.AddTemplate(importedPage, 0, -1, 1, 0, 0, originalSize.Width); } } document.Close(); } }
关键参数解释
AddTemplate的6个参数对应PDF的变换矩阵,这里给你拆解下旋转时的逻辑:
a, b, c, d:控制旋转和缩放,我们用的是纯旋转矩阵(没有缩放)- 顺时针90度矩阵:
0, 1, -1, 0 - 逆时针90度矩阵:
0, -1, 1, 0
- 顺时针90度矩阵:
e, f:平移偏移量,用来修正旋转后页面的位置——如果不加这个,旋转后的页面会跑到文档可视区域之外,看起来就是“消失”了
为什么你之前会出错?
- 没调整文档页面尺寸:旋转后宽高互换,如果还是用原尺寸,内容会被强制缩放或裁剪
- 没设置平移偏移:旋转是围绕坐标系原点(左下角)进行的,旋转后页面会偏移到可视区域外,所以必须用
e和f把它拉回来
调用这个方法时,只需要传入输入输出路径,以及是否顺时针旋转即可,比如:
RotatePdf90Degrees("input.pdf", "output_clockwise.pdf", true);
内容的提问来源于stack exchange,提问作者bmurrell30
相关产品推荐
相关产品推荐

