В этом руководстве мы узнаем, как читать 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-файла на С++
#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++.