本文介绍如何使用Spire.PDF for .NET为PDF文档中的文字块加上行号。
原文档:
C#
using Spire.Pdf;
using Spire.Pdf.General.Find;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace AddLineNumber
{
class Program
{
static void Main(string[] args)
{
//创建PdfDocument对象
PdfDocument doc = new PdfDocument();
//加载PDF文档
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.pdf");
//获取第一页
PdfPageBase page = doc.Pages[0];
//查找第一行中的指定文字
PdfTextFind topLine = page.FindText("成都冰蓝科技", TextFindParameter.None).Finds[0];
//获取行高
float lineHeight = topLine.Bounds.Height;
//获取一个y坐标,用于写入编号的起始y坐标
float y = topLine.Bounds.Location.Y - 2;
//获取第二行中的指定文字
PdfTextFind secondLine = page.FindText("Office控件产品", TextFindParameter.None).Finds[0];
//计算行间距
float lineSpacing = secondLine.Bounds.Top - topLine.Bounds.Bottom;
//查找最后一行中的指定文字
PdfTextFind bottomLine = page.FindText("开发并向他们", TextFindParameter.None).Finds[0];
//获取获取最后一行的底部y坐标,亦即添加行号区域的高度
float height = bottomLine.Bounds.Bottom;
//创建一个字体,大小和PDF中文字大小一致
PdfTrueTypeFont trueTypeFont = new PdfTrueTypeFont(new Font("黑体", 12f), true);
int i = 1;
while (y < height)
{
//绘制行号到每一行的前面
page.Canvas.DrawString(i.ToString(), trueTypeFont, PdfBrushes.Black, new PointF(15, y));
y += lineHeight + lineSpacing;
i++;
}
//保存文档
doc.SaveToFile("result.pdf");
}
}
}
VB.NET
Imports Spire.Pdf
Imports Spire.Pdf.General.Find
Imports Spire.Pdf.Graphics
Imports System.Drawing
Namespace AddLineNumber
Class Program
Shared Sub Main(ByVal args() As String)
'创建PdfDocument对象
Dim doc As PdfDocument = New PdfDocument()
'加载PDF文档
doc.LoadFromFile("C:\Users\Administrator\Desktop\input-cn3.pdf")
'获取第一页
Dim page As PdfPageBase = doc.Pages(0)
'查找第一行中的指定文字
Dim topLine As PdfTextFind = page.FindText("成都冰蓝科技",TextFindParameter.None).Finds(0)
'获取行高
Dim lineHeight As single = topLine.Bounds.Height
'获取一个y坐标,用于写入编号的起始y坐标
Dim y As single = topLine.Bounds.Location.Y - 2
'获取第二行中的指定文字
Dim secondLine As PdfTextFind = page.FindText("Office控件产品",TextFindParameter.None).Finds(0)
'计算行间距
Dim lineSpacing As single = secondLine.Bounds.Top - topLine.Bounds.Bottom
'查找最后一行中的指定文字
Dim bottomLine As PdfTextFind = page.FindText("开发并向他们",TextFindParameter.None).Finds(0)
'获取获取最后一行的底部y坐标,亦即添加行号区域的高度
Dim height As single = bottomLine.Bounds.Bottom
'创建一个字体,大小和PDF中文字大小一致
Dim TrueTypeFont As PdfTrueTypeFont = New PdfTrueTypeFont(New Font("黑体",12f),True)
Dim i As Integer = 1
While y < height
'绘制行号到每一行的前面
page.Canvas.DrawString(i.ToString(),TrueTypeFont,PdfBrushes.Black,New PointF(15,y))
y += lineHeight + lineSpacing
i = i + 1
End While
'保存文档
doc.SaveToFile("result.pdf")
End Sub
End Class
End Namespace
结果文档: