ในบทช่วยสอนนี้ เราจะเรียนรู้วิธี **อ่าน PDF ไฟล์ใน C++++ คุณสามารถแยกข้อความหรือรูปภาพจากหน้าใดก็ได้หรือเอกสารทั้งหมดของไฟล์ PDF ด้วยการเรียก API อย่างง่ายใน C++ คุณลักษณะนี้ไม่ขึ้นอยู่กับ Adobe Acrobat หรือแอปพลิเคชันใดๆ สำหรับการอ่าน PDF บนแพลตฟอร์ม Windows หรือ Linux
ขั้นตอนในการอ่านไฟล์ PDF ใน C++
- ติดตั้ง Aspose.Pdf for C++ จากเครื่องมือจัดการแพ็คเกจของ NuGet
- เพิ่มการอ้างอิงไปยังเนมสเปซ Aspose::Pdf
- โหลดอินพุต PDF โดยใช้ Document Class
- เริ่มต้นอินสแตนซ์คลาส TextFragmentAbsorber
- พิมพ์ข้อความที่แยกออกมาบนคอนโซล
- ทำซ้ำผ่านแต่ละหน้าและรูปภาพของเอกสาร
- บันทึกภาพเอาต์พุตที่แยกออกมาเป็นไฟล์ JPG
คุณสามารถ เปิดและอ่านไฟล์ pdf ใน C++ ด้วยโค้ดง่ายๆ ไม่กี่บรรทัด สามารถแยกข้อความและรูปภาพทั้งหมดออกจากไฟล์ PDF ได้อย่างมีประสิทธิภาพ
รหัสสำหรับอ่านไฟล์ PDF ใน C++
#pragma once | |
#include <iostream> | |
#include <system/smart_ptr.h> | |
#include <Aspose.PDF.Cpp/License.h> | |
#include <Aspose.PDF.Cpp/Document.h> | |
#include <Aspose.PDF.Cpp/Page.h> | |
#include <Aspose.PDF.Cpp/PageCollection.h> | |
#include <Aspose.PDF.Cpp/Resources.h> | |
#include <Aspose.PDF.Cpp/XImageCollection.h> | |
#include <Aspose.PDF.Cpp/XImage.h> | |
#include <Aspose.PDF.Cpp/Text/TextFragmentAbsorber.h> | |
#include <system/console.h> | |
#include <system/io/file.h> | |
#include <drawing/imaging/image_format.h> | |
using namespace System; | |
using namespace Aspose::Pdf; | |
class ReadPDFEx { | |
public: | |
static void ReadPDF() | |
{ | |
// Set the license for Aspose.PDF for CPP to Read PDF file | |
SharedPtr<License> ReadPdfLicense = System::MakeObject<License>(); | |
ReadPdfLicense->SetLicense(u"Aspose.PDF.NET.lic"); | |
// Load input PDF file with Document class object | |
SharedPtr<Document> doc = MakeObject<Document>(u"Test.pdf"); | |
// Initialize a TextFragmentAbsorber class instance | |
SharedPtr<Aspose::Pdf::Text::TextFragmentAbsorber> absorber = MakeObject<Aspose::Pdf::Text::TextFragmentAbsorber>(); | |
doc->get_Pages()->Accept(absorber); | |
// Print the extracted text on console | |
System::Console::WriteLine(absorber->get_Text()); | |
// Set the image counter variable | |
int ImageCount = 1; | |
// Iterate through each page of the PDF document | |
for (SharedPtr<Page> page : doc->get_Pages()) | |
{ | |
// Iterate through all the images | |
for (SharedPtr<XImage> image : page->get_Resources()->get_Images()) | |
{ | |
// Initialize an object of the FileStream type | |
System::SharedPtr<System::IO::FileStream> outputImage = | |
System::IO::File::Create(String::Format(u"Image{0}.jpg", ImageCount)); | |
// Save the output image | |
image->Save(outputImage, System::Drawing::Imaging::ImageFormat::get_Jpeg()); | |
// Close the FileStream | |
outputImage->Close(); | |
ImageCount++; | |
} | |
} | |
} | |
}; |
ในหัวข้อที่แล้ว เราได้สำรวจ วิธีทำให้ฟิลด์แบบฟอร์ม PDF เรียบใน C # หัวข้อนี้มุ่งเน้นไปที่วิธีการ อ่านข้อความจากไฟล์ PDF ใน C++