Extract text from multi-column PDFs in C++
Contents
[
Hide
]
Extract text after reducing font sizes
Adjust in-memory text fragment sizes before extracting text from a reloaded document.
This technique changes the intermediate document. Review extraction order for your input; the example does not guarantee correct column ordering.
- Open the input PDF as a Document.
- Create a TextFragmentAbsorber and process all pages.
- Multiply each fragment font size by reduceRatio.
- Save the modified document to a memory stream with Save().
- Reload the document from the stream and process it with TextAbsorber.
- Write the extracted text to the output file.
#include <Aspose.PDF.Cpp/Document.h>
#include <Aspose.PDF.Cpp/Page.h>
#include <Aspose.PDF.Cpp/PageCollection.h>
#include <Aspose.PDF.Cpp/Text/TextAbsorber.h>
#include <Aspose.PDF.Cpp/Text/TextFragmentAbsorber.h>
#include <Aspose.PDF.Cpp/Text/TextFragment.h>
#include <Aspose.PDF.Cpp/Text/TextFragmentCollection.h>
#include <Aspose.PDF.Cpp/Text/TextFragmentState.h>
using namespace System;
using namespace Aspose::Pdf;
using namespace Aspose::Pdf::Text;
void ExtractTextReduceFont(String inputFile, String outputFile, float reduceRatio)
{
auto document = MakeObject<Document>(inputFile);
auto fragmentAbsorber = MakeObject<TextFragmentAbsorber>();
document->get_Pages()->Accept(fragmentAbsorber);
for (auto& fragment : fragmentAbsorber->get_TextFragments()) {
fragment->get_TextState()
->set_FontSize((fragment->get_TextState()->get_FontSize() * reduceRatio));
}
auto stream = MakeObject<System::IO::MemoryStream>();
document->Save(stream);
auto document2 = MakeObject<Document>(stream);
auto textAbsorber = MakeObject<TextAbsorber>();
document2->get_Pages()->Accept(textAbsorber);
System::IO::File::WriteAllText(outputFile, textAbsorber->get_Text());
}
Extract text with a scale factor
Configure Pure text formatting and a scale factor without explicitly editing text fragments.
- Open the input PDF as a Document.
- Create a TextAbsorber and TextExtractionOptions with Pure formatting.
- Set ScaleFactor to reduceRatio and assign the extraction options.
- Process all pages.
- Write the extracted text to the output file.
#include <Aspose.PDF.Cpp/Document.h>
#include <Aspose.PDF.Cpp/PageCollection.h>
#include <Aspose.PDF.Cpp/Text/TextAbsorber.h>
#include <Aspose.PDF.Cpp/Text/TextOptions/TextExtractionOptions.h>
using namespace System;
using namespace Aspose::Pdf;
using namespace Aspose::Pdf::Text;
void ExtractTextScaleFactor(String inputFile, String outputFile, float reduceRatio)
{
auto document = MakeObject<Document>(inputFile);
auto textAbsorber = MakeObject<TextAbsorber>();
auto extractionOptions = MakeObject<TextExtractionOptions>(TextExtractionOptions::TextFormattingMode::Pure);
extractionOptions->set_ScaleFactor(reduceRatio);
textAbsorber->set_ExtractionOptions(extractionOptions);
document->get_Pages()->Accept(textAbsorber);
System::IO::File::WriteAllText(outputFile, textAbsorber->get_Text());
}