C#/VB.NET 如何旋转PDF页面
在日常工作中有时候会碰到PDF文档页面方向倒置的情况,这样文档阅读起来很不方便,因此我们需要对PDF文档的页面方向进行调整,也就是旋转页面。本文将介绍如何使用C#和免费PDF组件Free Spire.PDF实现旋转PDF页面的功能。
首先下载Free Spire.PDF并安装,然后创建C#/VB应用程序,再通过下面的路径把Bin文件夹里的Spire.PDF.dll添加为引用。路径大致如下:"...\Spire.pdf-fe\Bin\NET4.0\ Spire.PDF.dll"
方法/步骤:
步骤1:创建PdfDocument实例并载入PDF文档。
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Sample.pdf");
步骤2:获取需要被旋转的页面,此处为第一页。如果要旋转所有页面,只需遍历pdf.Pages。
PdfPageBase page =pdf.Pages[0];
步骤3:获取页面当前的旋转角度,然后在当前旋转角度的基础上旋转页面,角度可选0/90/180/270。
int rotation = (int)page.Rotation;
rotation += (int)PdfPageRotateAngle.RotateAngle270;
page.Rotation = (PdfPageRotateAngle)rotation;
步骤4:保存文档。
pdf.SaveToFile("Output.pdf");
旋转前:
旋转后:
完整代码:
C#:
using Spire.Pdf;
namespace RotatePDFPage
{
class Program
{
static void Main(string[] args)
{
//载入PDF文档
PdfDocument pdf = newPdfDocument();
pdf.LoadFromFile("Sample.pdf");
//获取需要旋转的页面,此处为第一页
PdfPageBase page =pdf.Pages[0];
//获取页面当前的旋转角度,然后在当前角度的基础上旋转页面
int rotation = (int)page.Rotation;
rotation += (int)PdfPageRotateAngle.RotateAngle270;
page.Rotation = (PdfPageRotateAngle)rotation;
//保存文档
pdf.SaveToFile("Output.pdf");
}
}
}
VB.NET:
Imports Spire.Pdf
Namespace RotatePDFPage
ClassProgram
PrivateShared Sub Main(args As String())
'载入PDF文档
Dimpdf As New PdfDocument()
pdf.LoadFromFile("Sample.pdf")
'获取需要旋转的页面,此处为第一页
Dimpage As PdfPageBase = pdf.Pages(0)
'获取页面当前的旋转角度,然后在当前角度的基础上旋转页面
Dimrotation As Integer = CInt(page.Rotation)
rotation+= CInt(PdfPageRotateAngle.RotateAngle270)
page.Rotation= DirectCast(rotation, PdfPageRotateAngle)
'保存文档
pdf.SaveToFile("Output.pdf")
EndSub
EndClass
End Namespace