免费库 free spire.pdf for .net 提供了接口来获取pdf页面信息,我们可以从官网下载产品包后手动添加引用,或者直接通过nuget安装。
pm> install-package freespire.pdf
输入文档如图:

c# 读取pdf页面大小(宽度、高度)
免费spire.pdf提供了 pdfpagebase.size.width 和 pdfpagebase.size.height 属性来获取指定pdf页面的宽度和高度。
获取到的值默认单位为磅(point),如果想要将其转换为厘米、毫米等常见单位,可以通过 pdfunitconvertor 类的 convertunits(float value, pdfgraphicsunit from, pdfgraphicsunit to) 方法进行转换。
示例代码如下:
using system;
using system.text;
using spire.pdf;
using spire.pdf.graphics;
namespace getpdfpagesize
{
class program
{
static void main(string[] args)
{
//加载pdf文件
pdfdocument pdf = new pdfdocument();
pdf.loadfromfile("示例.pdf");
//获取第一页
pdfpagebase page = pdf.pages[0];
//获取页面宽度和高度(默认单位为point)
float pointwidth = page.size.width;
float pointheight = page.size.height;
//创建pdfunitconvertor对象用于转换单位
pdfunitconvertor unitcvtr = new pdfunitconvertor();
//将单位从磅(point)转换为厘米
float centimeterwidth = unitcvtr.convertunits(pointwidth, pdfgraphicsunit.point, pdfgraphicsunit.centimeter);
float centimeterheight = unitcvtr.convertunits(pointheight, pdfgraphicsunit.point, pdfgraphicsunit.centimeter);
//将单位从磅(point)转换为毫米
float millimeterwidth = unitcvtr.convertunits(pointwidth, pdfgraphicsunit.point, pdfgraphicsunit.millimeter);
float millimeterheight = unitcvtr.convertunits(pointheight, pdfgraphicsunit.point, pdfgraphicsunit.millimeter);
//输出pdf页面宽高度信息
console.writeline("该pdf页面大小为(以磅为单位): 宽度 " + pointwidth + "pt, 高度 " + pointheight + "pt");
console.writeline("该pdf页面大小为(以厘米为单位): 宽度 " + centimeterwidth + "cm, 高度 " + centimeterheight + "cm");
console.writeline("该pdf页面大小为(以毫米为单位): 宽度 " + millimeterwidth + "mm, 高度 " + millimeterheight + "mm");
}
}
}
输出结果:

c# 判断pdf页面方向
页面的方向通常以横向或纵向表示。要判断指定pdf页面的方向:
- 先获取页面宽度和高度
- 再比较这两个值。(如果宽度大于高度,则页面方向为横向,反之则为纵向。)
示例代码如下:
using spire.pdf;
using system;
namespace getpdfpageorientation
{
class program
{
static void main(string[] args)
{
//加载pdf文档
pdfdocument pdf = new pdfdocument();
pdf.loadfromfile("示例.pdf");
//获取第一页
pdfpagebase page = pdf.pages[0];
//获取页面宽度和高度
float width = page.size.width;
float height = page.size.height;
//通过比较页面宽度和高度来判断页面方向
if (width > height)
{
console.writeline("当前页面方向为横向。");
}
else
{
console.writeline("当前页面方向为纵向。");
}
}
}
}
输出结果:

c# 检测pdf页面旋转角度
使用 pdfpagebase.rotation 可以获取指定pdf页面的旋转角度。如果为 0,则表示页面保持原来的方向。
示例代码如下:
using spire.pdf;
using system;
namespace getpdfpageorientation
{
class program
{
static void main(string[] args)
{
//加载pdf文档
pdfdocument pdf = new pdfdocument();
pdf.loadfromfile("示例.pdf");
//获取第一页
pdfpagebase page = pdf.pages[0];
//获取页面的旋转角度并输出结果
pdfpagerotateangle rotationangle = page.rotation;
string rotation = rotationangle.tostring();
console.writeline("当前页面旋转角度为: " + rotation);
}
}
}
输出结果:

以上就是通过c#实现获取pdf页面大小、方向和旋转角度的详细内容,更多关于c#获取pdf页面属性的资料请关注代码网其它相关文章!
发表评论