對PDF檔案中的內容進行查找時,可針對檔案全篇內容獲取查找結果,也可在PDF指定頁面中的特定范圍內(矩形框區域)進行查找,對獲取的查找結果可執行文本高亮或替換等操作,本文將對此作相關介紹(附VB.NET代碼,有需要可參考),
關于工具使用
工具:需下載Spire.PDF for .NET Pack hotfix 6.12.20版本(注:hotfixt版本無需安裝,若下載的是Pack版本則需要安裝至本地路徑,可在安裝后,查看演示程式及API),
參考:下載并解壓到本地路徑,將Bin檔案夾下的Spire.Pdf.dll檔案添加參考至VS程式,具體參考方法可參考如下步驟:
在VS程式中打開“解決方案資源管理器”-滑鼠右鍵點擊“參考”-“添加參考”-然后執行如下操作:

添加參考結果如圖:

C# 代碼
using Spire.Pdf; using Spire.Pdf.General.Find; using Spire.Pdf.Graphics; using System.Drawing; namespace FindAndHighlightText2 { class Program { static void Main(string[] args) { //加載PDF測驗檔案 PdfDocument pdf = new PdfDocument(); pdf.LoadFromFile("咖啡豆.pdf", FileFormat.PDF); //指定需要查找的頁面區域范圍 RectangleF pagerec = new RectangleF(0, 0, 500, 700); //在第一頁的指定區域查找指定文本 PdfTextFindCollection findCollection1 = pdf.Pages[0].FindText(pagerec, "咖啡豆", TextFindParameter.WholeWord); PdfTextFindCollection findCollection2 = pdf.Pages[0].FindText(pagerec, "洪都拉斯", TextFindParameter.WholeWord); //替換查找結果 PdfBrush brush = new PdfSolidBrush(Color.Red); PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 12f, FontStyle.Regular)); RectangleF textrec; foreach (PdfTextFind find1 in findCollection1.Finds) { textrec = find1.Bounds; pdf.Pages[0].Canvas.DrawRectangle(PdfBrushes.White, textrec); pdf.Pages[0].Canvas.DrawString("NewText", font, brush, textrec); } //高亮查找結果 foreach (PdfTextFind find2 in findCollection2.Finds) { find2.ApplyHighLight(Color.Yellow); } //保存檔案 pdf.SaveToFile("result.pdf", FileFormat.PDF); System.Diagnostics.Process.Start("result.pdf"); } } }
查找替換及高亮結果如圖效果:

Vb.net代碼
Imports Spire.Pdf Imports Spire.Pdf.General.Find Imports Spire.Pdf.Graphics Imports System.Drawing Namespace FindAndHighlightText2 Class Program Private Shared Sub Main(args As String()) '加載PDF測驗檔案 Dim pdf As New PdfDocument() pdf.LoadFromFile("咖啡豆.pdf", FileFormat.PDF) '指定需要查找的頁面區域范圍 Dim pagerec As New RectangleF(0, 0, 500, 700) '在第一頁的指定區域查找指定文本 Dim findCollection1 As PdfTextFindCollection = pdf.Pages(0).FindText(pagerec, "咖啡豆", TextFindParameter.WholeWord) Dim findCollection2 As PdfTextFindCollection = pdf.Pages(0).FindText(pagerec, "洪都拉斯", TextFindParameter.WholeWord) '替換查找結果 Dim brush As PdfBrush = New PdfSolidBrush(Color.Red) Dim font As New PdfTrueTypeFont(New Font("Arial", 12F, FontStyle.Regular)) Dim textrec As RectangleF For Each find1 As PdfTextFind In findCollection1.Finds textrec = find1.Bounds pdf.Pages(0).Canvas.DrawRectangle(PdfBrushes.White, textrec) pdf.Pages(0).Canvas.DrawString("NewText", font, brush, textrec) Next '高亮查找結果 For Each find2 As PdfTextFind In findCollection2.Finds find2.ApplyHighLight(Color.Yellow) Next '保存檔案 pdf.SaveToFile("result.pdf", FileFormat.PDF) System.Diagnostics.Process.Start("result.pdf") End Sub End Class End Namespace
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/246384.html
標籤:.NET技术
