如何使用iTextSharp的PdfWriter实现PDF页面旋转
你可以在生成PDF阶段直接通过设置Document的页面属性实现旋转,不需要依赖PdfReader,两种常用实现方案如下:
全局所有页面统一旋转
初始化Document时直接对页面大小对象设置旋转参数即可:
- 常用的90度横屏可以直接调用
Rotate()方法:
// 替换原初始化Document的代码即可 Document document = new Document(PageSize.A4.Rotate(), 45, 45, 80, 80);
- 自定义其他角度(支持0/90/180/270四个取值):
Rectangle customPage = PageSize.A4; customPage.Rotation = 180; // 页面倒置 Document document = new Document(customPage, 45, 45, 80, 80);
单页单独设置旋转
如果只需要指定页面旋转,其余页面保持默认,可以在调用NewPage()生成新页面前修改Document的页面大小参数:
修改后的完整示例代码如下:
private void CreatePdf(string strPdfPath) { using (FileStream fs = new FileStream(strPdfPath, FileMode.Create, FileAccess.Write, FileShare.None)) using (Document document = new Document(PageSize.A4, 45, 45, 80, 80)) { PdfWriter writer = PdfWriter.GetInstance(document, fs); document.Open(); document.AddTitle("This is Title"); document.AddCreationDate(); // 第一页默认无旋转 Paragraph content1 = new Paragraph("This is first Page"); document.Add(content1); // 设置第二页旋转180度 var rotatedPage = PageSize.A4; rotatedPage.Rotation = 180; document.SetPageSize(rotatedPage); document.NewPage(); Paragraph content2 = new Paragraph("This is second Page"); document.Add(content2); // 后续页面如需恢复默认旋转,重新设置页面大小即可 // document.SetPageSize(PageSize.A4); // document.NewPage(); } }
提示:建议用
using语法管理IO流、Document、PdfWriter对象的生命周期,无需手动调用Close()方法即可自动释放资源,避免资源泄漏。
内容的提问来源于stack exchange,提问作者broUk
相关产品推荐
相关产品推荐

