26#include <allheaders.h>
173static const int kCharWidth = 2;
178static const int kMaxBytesPerCodepoint = 20;
186 textonly_ = textonly;
187 offsets_.push_back(0);
190void TessPDFRenderer::AppendPDFObjectDIY(
size_t objectsize) {
191 offsets_.push_back(objectsize + offsets_.back());
195void TessPDFRenderer::AppendPDFObject(
const char *data) {
196 AppendPDFObjectDIY(strlen(data));
203static double prec(
double x) {
204 double kPrecision = 1000.0;
205 double a = round(x * kPrecision) / kPrecision;
212static long dist2(
int x1,
int y1,
int x2,
int y2) {
213 return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
224static void GetWordBaseline(
int writing_direction,
int ppi,
int height,
int word_x1,
int word_y1,
225 int word_x2,
int word_y2,
int line_x1,
int line_y1,
int line_x2,
226 int line_y2,
double *x0,
double *y0,
double *length) {
228 std::swap(word_x1, word_x2);
229 std::swap(word_y1, word_y2);
236 double l2 = dist2(line_x1, line_y1, line_x2, line_y2);
241 double t = ((px - line_x2) * (line_x2 - line_x1) + (py - line_y2) * (line_y2 - line_y1)) / l2;
242 x = line_x2 + t * (line_x2 - line_x1);
243 y = line_y2 + t * (line_y2 - line_y1);
245 word_length = sqrt(
static_cast<double>(dist2(word_x1, word_y1, word_x2, word_y2)));
246 word_length = word_length * 72.0 / ppi;
248 y = height - (y * 72.0 / ppi);
252 *length = word_length;
263static void AffineMatrix(
int writing_direction,
int line_x1,
int line_y1,
int line_x2,
int line_y2,
264 double *a,
double *b,
double *c,
double *d) {
266 atan2(
static_cast<double>(line_y1 - line_y2),
static_cast<double>(line_x2 - line_x1));
271 switch (writing_direction) {
291static void ClipBaseline(
int ppi,
int x1,
int y1,
int x2,
int y2,
int *line_x1,
int *line_y1,
292 int *line_x2,
int *line_y2) {
297 int rise = abs(y2 - y1) * 72;
298 int run = abs(x2 - x1) * 72;
299 if (rise < 2 * ppi && 2 * ppi < run) {
300 *line_y1 = *line_y2 = (y1 + y2) / 2;
304static bool CodepointToUtf16be(
int code,
char utf16[kMaxBytesPerCodepoint]) {
305 if ((code > 0xD7FF && code < 0xE000) || code > 0x10FFFF) {
306 tprintf(
"Dropping invalid codepoint %d\n", code);
309 if (code < 0x10000) {
310 snprintf(utf16, kMaxBytesPerCodepoint,
"%04X", code);
312 int a = code - 0x010000;
313 int high_surrogate = (0x03FF & (a >> 10)) + 0xD800;
314 int low_surrogate = (0x03FF & a) + 0xDC00;
315 snprintf(utf16, kMaxBytesPerCodepoint,
"%04X%04X", high_surrogate, low_surrogate);
320char *TessPDFRenderer::GetPDFTextObjects(
TessBaseAPI *api,
double width,
double height) {
321 double ppi = api->GetSourceYResolution();
324 double old_x = 0.0, old_y = 0.0;
325 int old_fontsize = 0;
327 bool new_block =
true;
334 std::stringstream pdf_str;
336 pdf_str.imbue(std::locale::classic());
338 pdf_str.precision(8);
343 pdf_str <<
"q " << prec(width) <<
" 0 0 " << prec(height) <<
" 0 0 cm";
345 pdf_str <<
" /Im1 Do";
354 const std::unique_ptr< ResultIterator> res_it(api->GetIterator());
356 if (res_it->IsAtBeginningOf(
RIL_BLOCK)) {
357 pdf_str <<
"BT\n3 Tr";
365 ClipBaseline(ppi, x1, y1, x2, y2, &line_x1, &line_y1, &line_x2, &line_y2);
379 res_it->Orientation(&orientation, &writing_direction, &textline_order, &deskew_angle);
381 switch (res_it->WordDirection()) {
389 writing_direction = old_writing_direction;
395 double x, y, word_length;
397 int word_x1, word_y1, word_x2, word_y2;
398 res_it->Baseline(
RIL_WORD, &word_x1, &word_y1, &word_x2, &word_y2);
399 GetWordBaseline(writing_direction, ppi, height, word_x1, word_y1, word_x2, word_y2, line_x1,
400 line_y1, line_x2, line_y2, &x, &y, &word_length);
403 if (writing_direction != old_writing_direction || new_block) {
404 AffineMatrix(writing_direction, line_x1, line_y1, line_x2, line_y2, &a, &b, &c, &d);
405 pdf_str <<
" " << prec(a)
414 double dx = x - old_x;
415 double dy = y - old_y;
416 pdf_str <<
" " << prec(dx * a + dy * b) <<
" " << prec(dx * c + dy * d)
421 old_writing_direction = writing_direction;
428 bool bold, italic, underlined, monospace, serif, smallcaps;
430 res_it->WordFontAttributes(&bold, &italic, &underlined, &monospace, &serif, &smallcaps,
431 &fontsize, &font_id);
432 const int kDefaultFontsize = 8;
434 fontsize = kDefaultFontsize;
436 if (fontsize != old_fontsize) {
437 pdf_str <<
"/f-0-0 " << fontsize <<
" Tf ";
438 old_fontsize = fontsize;
444 std::string pdf_word;
445 int pdf_word_len = 0;
447 const std::unique_ptr<const char[]> grapheme(res_it->GetUTF8Text(
RIL_SYMBOL));
448 if (grapheme && grapheme[0] !=
'\0') {
450 char utf16[kMaxBytesPerCodepoint];
451 for (
char32 code : unicodes) {
452 if (CodepointToUtf16be(code, utf16)) {
460 if (res_it->IsAtBeginningOf(
RIL_WORD)) {
464 if (word_length > 0 && pdf_word_len > 0) {
465 double h_stretch = kCharWidth * prec(100.0 * word_length / (fontsize * pdf_word_len));
466 pdf_str << h_stretch <<
" Tz"
467 <<
" [ <" << pdf_word
470 if (last_word_in_line) {
473 if (last_word_in_block) {
477 const std::string &text = pdf_str.str();
478 char *result =
new char[text.length() + 1];
479 strcpy(result, text.c_str());
484 AppendPDFObject(
"%PDF-1.5\n%\xDE\xAD\xBE\xEB\n");
503 " /BaseFont /GlyphLessFont\n"
504 " /DescendantFonts [ 4 0 R ]\n"
505 " /Encoding /Identity-H\n"
507 " /ToUnicode 6 0 R\n"
513 std::stringstream stream;
515 stream.imbue(std::locale::classic());
516 stream <<
"4 0 obj\n"
518 " /BaseFont /GlyphLessFont\n"
519 " /CIDToGIDMap 5 0 R\n"
522 " /Ordering (Identity)\n"
523 " /Registry (Adobe)\n"
526 " /FontDescriptor 7 0 R\n"
527 " /Subtype /CIDFontType2\n"
530 << (1000 / kCharWidth)
534 AppendPDFObject(stream.str().c_str());
537 const int kCIDToGIDMapSize = 2 * (1 << 16);
538 const std::unique_ptr<unsigned char[]> cidtogidmap(
new unsigned char[kCIDToGIDMapSize]);
539 for (
int i = 0; i < kCIDToGIDMapSize; i++) {
540 cidtogidmap[i] = (i % 2) ? 1 : 0;
543 unsigned char *comp = zlibCompress(cidtogidmap.get(), kCIDToGIDMapSize, &len);
545 stream <<
"5 0 obj\n"
549 <<
" /Filter /FlateDecode\n"
553 long objsize = stream.str().size();
554 AppendData(
reinterpret_cast<char *
>(comp), len);
557 const char *endstream_endobj =
561 objsize += strlen(endstream_endobj);
562 AppendPDFObjectDIY(objsize);
564 const char stream2[] =
565 "/CIDInit /ProcSet findresource begin\n"
570 " /Registry (Adobe)\n"
574 "/CMapName /Adobe-Identify-UCS def\n"
576 "1 begincodespacerange\n"
578 "endcodespacerange\n"
580 "<0000> <FFFF> <0000>\n"
583 "CMapName currentdict /CMap defineresource pop\n"
589 stream <<
"6 0 obj\n"
591 << (
sizeof(stream2) - 1)
597 AppendPDFObject(stream.str().c_str());
601 stream <<
"7 0 obj\n"
608 << (1000 / kCharWidth)
610 " /FontFile2 8 0 R\n"
611 " /FontName /GlyphLessFont\n"
614 " /Type /FontDescriptor\n"
617 AppendPDFObject(stream.str().c_str());
620 stream << datadir_.c_str() <<
"/pdf.ttf";
622 std::ifstream input(stream.str().c_str(), std::ios::in | std::ios::binary);
623 std::vector<unsigned char> buffer(std::istreambuf_iterator<char>(input), {});
624 auto size = buffer.size();
626 font = buffer.data();
629 tprintf(
"Cannot open file \"%s\"!\nUsing internal glyphless font.\n", stream.str().c_str());
632 size =
sizeof(pdf_ttf);
637 stream <<
"8 0 obj\n"
648 objsize = stream.str().size();
649 AppendData(
reinterpret_cast<const char *
>(font), size);
652 objsize += strlen(endstream_endobj);
653 AppendPDFObjectDIY(objsize);
657bool TessPDFRenderer::imageToPDFObj(Pix *pix,
const char *filename,
long int objnum,
658 char **pdf_object,
long int *pdf_object_size,
659 const int jpg_quality) {
660 if (!pdf_object_size || !pdf_object) {
663 *pdf_object =
nullptr;
664 *pdf_object_size = 0;
665 if (!filename && !pix) {
669 L_Compressed_Data *cid =
nullptr;
672 if (pixGetInputFormat(pix) == IFF_PNG) {
673 sad = pixGenerateCIData(pix, L_FLATE_ENCODE, 0, 0, &cid);
676 sad = l_generateCIDataForPdf(filename, pix, jpg_quality, &cid);
680 l_CIDataDestroy(&cid);
684 const char *group4 =
"";
688 filter =
"/FlateDecode";
691 filter =
"/DCTDecode";
694 filter =
"/CCITTFaxDecode";
698 filter =
"/JPXDecode";
701 l_CIDataDestroy(&cid);
708 std::stringstream colorspace;
710 colorspace.imbue(std::locale::classic());
711 if (cid->ncolors > 0) {
712 colorspace <<
" /ColorSpace [ /Indexed /DeviceRGB " << (cid->ncolors - 1) <<
" "
713 << cid->cmapdatahex <<
" ]\n";
717 if (cid->bps == 1 && pixGetInputFormat(pix) == IFF_PNG) {
719 " /ColorSpace /DeviceGray\n"
722 colorspace.str(
" /ColorSpace /DeviceGray\n");
726 colorspace.str(
" /ColorSpace /DeviceRGB\n");
729 l_CIDataDestroy(&cid);
734 int predictor = (cid->predictor) ? 14 : 1;
737 std::stringstream b1;
739 b1.imbue(std::locale::classic());
746 " /Subtype /Image\n";
748 std::stringstream b2;
750 b2.imbue(std::locale::classic());
751 b2 <<
" /Width " << cid->w
756 " /BitsPerComponent "
769 << group4 <<
" /Columns " << cid->w
771 " /BitsPerComponent "
782 size_t b1_len = b1.str().size();
783 size_t b2_len = b2.str().size();
784 size_t b3_len = strlen(b3);
785 size_t colorspace_len = colorspace.str().size();
787 *pdf_object_size = b1_len + colorspace_len + b2_len + cid->nbytescomp + b3_len;
788 *pdf_object =
new char[*pdf_object_size];
790 char *p = *pdf_object;
791 memcpy(p, b1.str().c_str(), b1_len);
793 memcpy(p, colorspace.str().c_str(), colorspace_len);
795 memcpy(p, b2.str().c_str(), b2_len);
797 memcpy(p, cid->datacomp, cid->nbytescomp);
798 p += cid->nbytescomp;
799 memcpy(p, b3, b3_len);
800 l_CIDataDestroy(&cid);
808 if (!pix || ppi <= 0) {
811 double width = pixGetWidth(pix) * 72.0 / ppi;
812 double height = pixGetHeight(pix) * 72.0 / ppi;
814 std::stringstream xobject;
816 xobject.imbue(std::locale::classic());
818 xobject <<
"/XObject << /Im1 " << (obj_ + 2) <<
" 0 R >>\n";
822 std::stringstream stream;
824 stream.imbue(std::locale::classic());
826 stream << std::fixed << obj_
832 << width <<
" " << height
841 " /ProcSet [ /PDF /Text /ImageB /ImageI /ImageC ]\n"
842 " /Font << /f-0-0 3 0 R >>\n"
846 pages_.push_back(obj_);
847 AppendPDFObject(stream.str().c_str());
850 const std::unique_ptr<char[]> pdftext(GetPDFTextObjects(api, width, height));
851 const size_t pdftext_len = strlen(pdftext.get());
853 unsigned char *comp_pdftext =
854 zlibCompress(
reinterpret_cast<unsigned char *
>(pdftext.get()), pdftext_len, &len);
855 long comp_pdftext_len = len;
862 <<
" /Filter /FlateDecode\n"
866 long objsize = stream.str().size();
867 AppendData(
reinterpret_cast<char *
>(comp_pdftext), comp_pdftext_len);
868 objsize += comp_pdftext_len;
869 lept_free(comp_pdftext);
874 objsize += strlen(b2);
875 AppendPDFObjectDIY(objsize);
878 char *pdf_object =
nullptr;
881 if (!imageToPDFObj(pix, filename, obj_, &pdf_object, &objsize, jpg_quality)) {
885 AppendPDFObjectDIY(objsize);
899 const long int kPagesObjectNumber = 2;
900 offsets_[kPagesObjectNumber] = offsets_.back();
901 std::stringstream stream;
903 stream.imbue(std::locale::classic());
904 stream << kPagesObjectNumber <<
" 0 obj\n<<\n /Type /Pages\n /Kids [ ";
906 size_t pages_objsize = stream.str().size();
907 for (
const auto &page : pages_) {
909 stream << page <<
" 0 R ";
911 pages_objsize += stream.str().size();
914 stream <<
"]\n /Count " << pages_.size() <<
"\n>>\nendobj\n";
916 pages_objsize += stream.str().size();
917 offsets_.back() += pages_objsize;
920 std::string utf16_title =
"FEFF";
922 char utf16[kMaxBytesPerCodepoint];
923 for (
char32 code : unicodes) {
924 if (CodepointToUtf16be(code, utf16)) {
925 utf16_title += utf16;
929 char *datestr = l_getFormattedDate();
934 " /Producer (Tesseract "
935 << tesseract::TessBaseAPI::Version()
941 << utf16_title.c_str()
946 AppendPDFObject(stream.str().c_str());
948 stream <<
"xref\n0 " << obj_ <<
"\n0000000000 65535 f \n";
950 for (
int i = 1; i < obj_; i++) {
954 stream << offsets_[i] <<
" 00000 n \n";
958 stream <<
"trailer\n<<\n /Size " << obj_
965 << offsets_.back() <<
"\n%%EOF\n";
struct TessBaseAPI TessBaseAPI
void tprintf(const char *format,...)
@ WRITING_DIRECTION_TOP_TO_BOTTOM
@ WRITING_DIRECTION_LEFT_TO_RIGHT
@ WRITING_DIRECTION_RIGHT_TO_LEFT
const char * GetInputName()
bool GetIntVariable(const char *name, int *value) const
int GetSourceYResolution()
void AppendString(const char *s)
const char * title() const
void AppendData(const char *s, int len)
bool EndDocumentHandler() override
bool BeginDocumentHandler() override
TessPDFRenderer(const char *outputbase, const char *datadir, bool textonly=false)
bool AddImageHandler(TessBaseAPI *api) override
static std::vector< char32 > UTF8ToUTF32(const char *utf8_str)