#include <iostream>
#include <iomanip>
#include <poppler/PDFDoc.h>
#include <poppler/PDFDocFactory.h>
#include <poppler/goo/GooString.h>
#include <poppler/TextOutputDev.h>
#include <poppler/GlobalParams.h>
using namespace std;
enum ResultCode {
NoError = 0,
InternalError = 1,
CouldntReadPdf = 2,
CouldntOutput = 3,
};
typedef void (*NewPageFunc)(void *stream, int page);
extern "C" ResultCode pdftotext_print_with_layout(char *filename, void * stream, NewPageFunc newpage_f, TextOutputFunc output_f) {
globalParams = std::make_unique<GlobalParams>();
if (!(globalParams->getTextEncoding())) {
return InternalError;
}
GooString *inputPdf = new GooString(filename);
PDFDoc *doc = PDFDocFactory().createPDFDoc(*inputPdf, nullptr, nullptr);
if (!doc->isOk()) {
return CouldntReadPdf;
}
TextOutputDev* textOut;
int lastPage = doc->getNumPages();
for (int pageNum = 1; pageNum <= lastPage; pageNum++) {
newpage_f(stream, pageNum);
textOut = new TextOutputDev(nullptr, true, 0.0, false, false, false);
if (!textOut->isOk()) {
return CouldntOutput;
}
textOut->setTextEOL(eolUnix);
doc->displayPage(textOut, pageNum, 72.0, 72.0, 0, true, false, false);
TextPage *page = textOut->takeText();
page->dump(stream, output_f, true, eolUnix, false);
delete textOut;
}
return NoError;
}