How to Read PDF File in C++

In this tutorial, we will learn how to read PDF file in C++. You can extract text or images from any page or whole document of the PDF file with simple API calls in C++. The feature is not dependent on Adobe Acrobat or any application for reading PDF on Windows or Linux platforms.

Steps to Read PDF File in C++

  1. Install the Aspose.Pdf for C++ from NuGet package manager tool
  2. Add the reference to Aspose::Pdf namespace
  3. Load input PDF using Document Class
  4. Initialize a TextFragmentAbsorber class instance
  5. Print the extracted text on console
  6. Iterate through each page and image of document
  7. Save the extracted output image as a JPG file

You can open and read pdf file in C++ with few simple lines of code. It can efficiently extract all the text and images from the PDF file.

Code to Read PDF File in 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++;
}
}
}
};

In the previous topic, we explored How to Flatten PDF Form Fields in C#. This topic focuses on how to read text from PDF file in C++.

 English