วิธีอ่านไฟล์ PDF ใน C#

การอ่านเอกสารประเภทต่างๆ โดยทางโปรแกรมถือเป็นเรื่องปกติในทุกวันนี้ ในคำแนะนำวิธีใช้นี้ คุณจะได้เรียนรู้วิธีอ่านไฟล์ PDF ใน C# โดยทำตามขั้นตอนง่ายๆ ด้านล่างนี้

ขั้นตอนในการอ่านไฟล์ PDF ใน C#

  1. สร้างแอปพลิเคชันคอนโซล C# ที่ว่างเปล่าใน Visual Studio
  2. เพิ่มการอ้างอิงถึง Aspose.PDF for .NET โดยติดตั้งจาก NuGet.org
  3. โหลดไฟล์ PDF ที่มีอยู่ในวัตถุเอกสาร
  4. เริ่มต้นคลาส TextAbsorber เพื่ออ่านไฟล์ PDF
  5. แยกข้อความ PDF และเขียนไปยังเอาต์พุตคอนโซล
  6. วนซ้ำผ่านหน้า PDF Resources เพื่อค้นหาภาพ
  7. สร้างวัตถุ FileStream ด้วยภาพที่พบ
  8. บันทึกภาพลงในดิสก์ภายในเครื่อง

ข้อมูลโค้ดด้านล่างอธิบายวิธีเปิดและอ่านไฟล์ PDF ใน C# คุณจะสามารถอ่านข้อความและแยกรูปภาพจากไฟล์ PDF ได้โดยใช้ API มี TextAbsorber Class ที่ใช้ในการอ่านข้อความจากไฟล์ PDF และคุณสามารถรับผลลัพธ์ที่แยกออกมาผ่านวัตถุ Text การค้นหารูปภาพและบันทึกลงในดิสก์ภายในเครื่องสามารถทำได้โดยการวนซ้ำทรัพยากรของหน้า PDF ดังที่แสดงด้านล่าง

รหัสสำหรับอ่านไฟล์ PDF ใน C#

using System;
using System.IO;
// Add reference to Aspose.PDF for .NET API
// Use following namespace to read PDF file
using Aspose.Pdf;
namespace ReadPDFFiles
{
class Program
{
static void Main(string[] args)
{
// Set license before reading PDF file
Aspose.Pdf.License AsposePDFLicense = new Aspose.Pdf.License();
AsposePDFLicense.SetLicense(@"c:\asposelicense\license.lic");
string inFile = @"c:\ReadPDFFileInCSharp.pdf";
// Load an existing PDF file in Document object to read
Document pdf = new Document(inFile);
// 1. Read text from PDF file
// Initialize TextAbsorber Class to read Text from PDF file
Aspose.Pdf.Text.TextAbsorber textAbsorber = new Aspose.Pdf.Text.TextAbsorber();
// Call Page.Accept() method to let TextAbsorber find text in PDF Pages
pdf.Pages.Accept(textAbsorber);
// Write the extracted text to Console output
Console.WriteLine(textAbsorber.Text);
// 2. Extract images from PDF file
int imageIndex = 1;
// Iterate through PDF pages
foreach (var pdfPage in pdf.Pages)
{
// Check available images while reading the PDF
foreach (XImage image in pdfPage.Resources.Images)
{
// Create file stream for found image
FileStream extractedImage = new FileStream(String.Format("Page{0}_Image{1}.jpg", pdfPage.Number, imageIndex), FileMode.Create);
// Save output image to the disk
image.Save(extractedImage, System.Drawing.Imaging.ImageFormat.Jpeg);
// Close stream
extractedImage.Close();
imageIndex++;
}
// Reset image index
imageIndex = 1;
}
}
}
}

ในหัวข้อที่แล้ว คุณได้เรียนรู้ วิธีประมวลผลไฟล์ PDF ขนาดใหญ่ใน C# ตัวอย่างข้อมูลและโค้ดข้างต้นจะช่วยให้คุณสามารถเปิดและอ่านไฟล์ PDF ใน C# เพื่อแยกข้อความและรูปภาพ

 ไทย