-
Notifications
You must be signed in to change notification settings - Fork 394
/
pdfio2.c
2562 lines (2299 loc) · 84.4 KB
/
pdfio2.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*====================================================================*
- Copyright (C) 2001 Leptonica. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions
- are met:
- 1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- 2. Redistributions in binary form must reproduce the above
- copyright notice, this list of conditions and the following
- disclaimer in the documentation and/or other materials
- provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ANY
- CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*====================================================================*/
/*!
* \file pdfio2.c
* <pre>
*
* Lower-level operations for generating pdf.
*
* Intermediate function for single page, multi-image conversion
* l_int32 pixConvertToPdfData()
*
* Intermediate function for generating multipage pdf output
* l_int32 ptraConcatenatePdfToData()
*
* Convert tiff multipage to pdf file
* l_int32 convertTiffMultipageToPdf()
*
* Low-level CID-based operations
*
* Without transcoding
* l_int32 l_generateCIDataForPdf()
* L_COMP_DATA *l_generateFlateDataPdf()
* L_COMP_DATA *l_generateJpegData()
* L_COMP_DATA *l_generateJpegDataMem()
* static L_COMP_DATA *l_generateJp2kData()
*
* With transcoding
* l_int32 l_generateCIData()
* l_int32 pixGenerateCIData()
* L_COMP_DATA *l_generateFlateData()
* static L_COMP_DATA *pixGenerateFlateData()
* static L_COMP_DATA *pixGenerateJpegData()
* static L_COMP_DATA *pixGenerateJp2kData()
* static L_COMP_DATA *pixGenerateG4Data()
* L_COMP_DATA *l_generateG4Data()
*
* Other
* l_int32 cidConvertToPdfData()
* void l_CIDataDestroy()
*
* Helper functions for generating the output pdf string
* static l_int32 l_generatePdf()
* static void generateFixedStringsPdf()
* static char *generateEscapeString()
* static void generateMediaboxPdf()
* static l_int32 generatePageStringPdf()
* static l_int32 generateContentStringPdf()
* static l_int32 generatePreXStringsPdf()
* static l_int32 generateColormapStringsPdf()
* static void generateTrailerPdf()
* static l_int32 makeTrailerStringPdf()
* static l_int32 generateOutputDataPdf()
*
* Helper functions for generating multipage pdf output
* static l_int32 parseTrailerPdf()
* static char *generatePagesObjStringPdf()
* static L_BYTEA *substituteObjectNumbers()
*
* Create/destroy/access pdf data
* static L_PDF_DATA *pdfdataCreate()
* static void pdfdataDestroy()
* static L_COMP_DATA *pdfdataGetCid()
*
* Set flags for special modes
* void l_pdfSetG4ImageMask()
* void l_pdfSetDateAndVersion()
* </pre>
*/
#include <string.h>
#include <math.h>
#include "allheaders.h"
/* --------------------------------------------*/
#if USE_PDFIO /* defined in environ.h */
/* --------------------------------------------*/
/* Typical scan resolution in ppi (pixels/inch) */
static const l_int32 DefaultInputRes = 300;
/* Static helpers */
static L_COMP_DATA *l_generateJp2kData(const char *fname);
static L_COMP_DATA *pixGenerateFlateData(PIX *pixs, l_int32 ascii85flag);
static L_COMP_DATA *pixGenerateJpegData(PIX *pixs, l_int32 ascii85flag,
l_int32 quality);
static L_COMP_DATA *pixGenerateJp2kData(PIX *pixs, l_int32 quality);
static L_COMP_DATA *pixGenerateG4Data(PIX *pixs, l_int32 ascii85flag);
static l_int32 l_generatePdf(l_uint8 **pdata, size_t *pnbytes,
L_PDF_DATA *lpd);
static void generateFixedStringsPdf(L_PDF_DATA *lpd);
static char *generateEscapeString(const char *str);
static void generateMediaboxPdf(L_PDF_DATA *lpd);
static l_int32 generatePageStringPdf(L_PDF_DATA *lpd);
static l_int32 generateContentStringPdf(L_PDF_DATA *lpd);
static l_int32 generatePreXStringsPdf(L_PDF_DATA *lpd);
static l_int32 generateColormapStringsPdf(L_PDF_DATA *lpd);
static void generateTrailerPdf(L_PDF_DATA *lpd);
static char *makeTrailerStringPdf(L_DNA *daloc);
static l_int32 generateOutputDataPdf(l_uint8 **pdata, size_t *pnbytes,
L_PDF_DATA *lpd);
static l_int32 parseTrailerPdf(L_BYTEA *bas, L_DNA **pda);
static char *generatePagesObjStringPdf(NUMA *napage);
static L_BYTEA *substituteObjectNumbers(L_BYTEA *bas, NUMA *na_objs);
static L_PDF_DATA *pdfdataCreate(const char *title);
static void pdfdataDestroy(L_PDF_DATA **plpd);
static L_COMP_DATA *pdfdataGetCid(L_PDF_DATA *lpd, l_int32 index);
/* ---------------- Defaults for rendering options ----------------- */
/* Output G4 as writing through image mask; this is the default */
static l_int32 var_WRITE_G4_IMAGE_MASK = 1;
/* Write date/time and lib version into pdf; this is the default */
static l_int32 var_WRITE_DATE_AND_VERSION = 1;
#define L_SMALLBUF 256
#define L_BIGBUF 2048 /* must be able to hold hex colormap */
#ifndef NO_CONSOLE_IO
#define DEBUG_MULTIPAGE 0
#endif /* ~NO_CONSOLE_IO */
/*---------------------------------------------------------------------*
* Intermediate function for generating multipage pdf output *
*---------------------------------------------------------------------*/
/*!
* \brief pixConvertToPdfData()
*
* \param[in] pix all depths; cmap OK
* \param[in] type L_G4_ENCODE, L_JPEG_ENCODE, L_FLATE_ENCODE,
* L_JP2K_ENCODE
* \param[in] quality for jpeg: 1-100; 0 for default (75)
* for jp2k: 27-45; 0 for default (34)
* \param[out] pdata pdf array
* \param[out] pnbytes number of bytes in pdf array
* \param[in] x, y location of lower-left corner of image, in pixels,
* relative to the PostScript origin (0,0) at
* the lower-left corner of the page)
* \param[in] res override the resolution of the input image, in ppi;
* use 0 to respect resolution embedded in the input
* \param[in] title [optional] pdf title; can be null
* \param[in,out] plpd ptr to lpd; created on the first invocation and
* returned until last image is processed
* \param[in] position in image sequence: L_FIRST_IMAGE, L_NEXT_IMAGE,
* L_LAST_IMAGE
* \return 0 if OK, 1 on error
*
* <pre>
* Notes:
* (1) If %res == 0 and the input resolution field is 0,
* this will use DefaultInputRes.
* (2) This only writes %data if it is the last image to be
* written on the page.
* (3) See comments in convertToPdf().
* </pre>
*/
l_ok
pixConvertToPdfData(PIX *pix,
l_int32 type,
l_int32 quality,
l_uint8 **pdata,
size_t *pnbytes,
l_int32 x,
l_int32 y,
l_int32 res,
const char *title,
L_PDF_DATA **plpd,
l_int32 position)
{
l_int32 pixres, w, h, ret;
l_float32 xpt, ypt, wpt, hpt;
L_COMP_DATA *cid = NULL;
L_PDF_DATA *lpd = NULL;
PROCNAME("pixConvertToPdfData");
if (!pdata)
return ERROR_INT("&data not defined", procName, 1);
*pdata = NULL;
if (!pnbytes)
return ERROR_INT("&nbytes not defined", procName, 1);
*pnbytes = 0;
if (!pix)
return ERROR_INT("pix not defined", procName, 1);
if (type != L_JPEG_ENCODE && type != L_G4_ENCODE &&
type != L_FLATE_ENCODE && type != L_JP2K_ENCODE) {
selectDefaultPdfEncoding(pix, &type);
}
if (plpd) { /* part of multi-page invocation */
if (position == L_FIRST_IMAGE)
*plpd = NULL;
}
/* Generate the compressed image data. It must NOT
* be ascii85 encoded. */
pixGenerateCIData(pix, type, quality, 0, &cid);
if (!cid)
return ERROR_INT("cid not made", procName, 1);
/* Get media box in pts. Guess the input image resolution
* based on the input parameter %res, the resolution data in
* the pix, and the size of the image. */
pixres = cid->res;
w = cid->w;
h = cid->h;
if (res <= 0.0) {
if (pixres > 0)
res = pixres;
else
res = DefaultInputRes;
}
xpt = x * 72. / res;
ypt = y * 72. / res;
wpt = w * 72. / res;
hpt = h * 72. / res;
/* Set up lpd */
if (!plpd) { /* single image */
if ((lpd = pdfdataCreate(title)) == NULL)
return ERROR_INT("lpd not made", procName, 1);
} else if (position == L_FIRST_IMAGE) { /* first of multiple images */
if ((lpd = pdfdataCreate(title)) == NULL)
return ERROR_INT("lpd not made", procName, 1);
*plpd = lpd;
} else { /* not the first of multiple images */
lpd = *plpd;
}
/* Add the data to the lpd */
ptraAdd(lpd->cida, cid);
lpd->n++;
ptaAddPt(lpd->xy, xpt, ypt);
ptaAddPt(lpd->wh, wpt, hpt);
/* If a single image or the last of multiple images,
* generate the pdf and destroy the lpd */
if (!plpd || (position == L_LAST_IMAGE)) {
ret = l_generatePdf(pdata, pnbytes, lpd);
pdfdataDestroy(&lpd);
if (plpd) *plpd = NULL;
if (ret)
return ERROR_INT("pdf output not made", procName, 1);
}
return 0;
}
/*---------------------------------------------------------------------*
* Intermediate function for generating multipage pdf output *
*---------------------------------------------------------------------*/
/*!
* \brief ptraConcatenatePdfToData()
*
* \param[in] pa_data ptra array of pdf strings, each for a
* single-page pdf file
* \param[in] sa [optional] string array of pathnames for
* input pdf files; can be null
* \param[out] pdata concatenated pdf data in memory
* \param[out] pnbytes number of bytes in pdf data
* \return 0 if OK, 1 on error
*
* <pre>
* Notes:
* (1) This only works with leptonica-formatted single-page pdf files.
* pdf files generated by other programs will have unpredictable
* (and usually bad) results. The requirements for each pdf file:
* (a) The Catalog and Info objects are the first two.
* (b) Object 3 is Pages
* (c) Object 4 is Page
* (d) The remaining objects are Contents, XObjects, and ColorSpace
* (2) We remove trailers from each page, and append the full trailer
* for all pages at the end.
* (3) For all but the first file, remove the ID and the first 3
* objects (catalog, info, pages), so that each subsequent
* file has only objects of these classes:
* Page, Contents, XObject, ColorSpace (Indexed RGB).
* For those objects, we substitute these refs to objects
* in the local file:
* Page: Parent(object 3), Contents, XObject(typically multiple)
* XObject: [ColorSpace if indexed]
* The Pages object on the first page (object 3) has a Kids array
* of references to all the Page objects, with a Count equal
* to the number of pages. Each Page object refers back to
* this parent.
* </pre>
*/
l_ok
ptraConcatenatePdfToData(L_PTRA *pa_data,
SARRAY *sa,
l_uint8 **pdata,
size_t *pnbytes)
{
char *fname, *str_pages, *str_trailer;
l_uint8 *pdfdata, *data;
l_int32 i, j, index, nobj, npages;
l_int32 *sizes, *locs;
size_t size;
L_BYTEA *bas, *bad, *bat1, *bat2;
L_DNA *da_locs, *da_sizes, *da_outlocs, *da;
L_DNAA *daa_locs; /* object locations on each page */
NUMA *na_objs, *napage;
NUMAA *naa_objs; /* object mapping numbers to new values */
PROCNAME("ptraConcatenatePdfToData");
if (!pdata)
return ERROR_INT("&data not defined", procName, 1);
*pdata = NULL;
if (!pnbytes)
return ERROR_INT("&nbytes not defined", procName, 1);
*pnbytes = 0;
if (!pa_data)
return ERROR_INT("pa_data not defined", procName, 1);
/* Parse the files and find the object locations.
* Remove file data that cannot be parsed. */
ptraGetActualCount(pa_data, &npages);
daa_locs = l_dnaaCreate(npages);
for (i = 0; i < npages; i++) {
bas = (L_BYTEA *)ptraGetPtrToItem(pa_data, i);
if (parseTrailerPdf(bas, &da_locs) != 0) {
bas = (L_BYTEA *)ptraRemove(pa_data, i, L_NO_COMPACTION);
l_byteaDestroy(&bas);
if (sa) {
fname = sarrayGetString(sa, i, L_NOCOPY);
L_ERROR("can't parse file %s; skipping\n", procName, fname);
} else {
L_ERROR("can't parse file %d; skipping\n", procName, i);
}
} else {
l_dnaaAddDna(daa_locs, da_locs, L_INSERT);
}
}
/* Recompute npages in case some of the files were not pdf */
ptraCompactArray(pa_data);
ptraGetActualCount(pa_data, &npages);
if (npages == 0) {
l_dnaaDestroy(&daa_locs);
return ERROR_INT("no parsable pdf files found", procName, 1);
}
/* Find the mapping from initial to final object numbers */
naa_objs = numaaCreate(npages); /* stores final object numbers */
napage = numaCreate(npages); /* stores "Page" object numbers */
index = 0;
for (i = 0; i < npages; i++) {
da = l_dnaaGetDna(daa_locs, i, L_CLONE);
nobj = l_dnaGetCount(da);
if (i == 0) {
numaAddNumber(napage, 4); /* object 4 on first page */
na_objs = numaMakeSequence(0.0, 1.0, nobj - 1);
index = nobj - 1;
} else { /* skip the first 3 objects in each file */
numaAddNumber(napage, index); /* Page object is first we add */
na_objs = numaMakeConstant(0.0, nobj - 1);
numaReplaceNumber(na_objs, 3, 3); /* refers to parent of all */
for (j = 4; j < nobj - 1; j++)
numaSetValue(na_objs, j, index++);
}
numaaAddNuma(naa_objs, na_objs, L_INSERT);
l_dnaDestroy(&da);
}
/* Make the Pages object (#3) */
str_pages = generatePagesObjStringPdf(napage);
/* Build the output */
bad = l_byteaCreate(5000);
da_outlocs = l_dnaCreate(0); /* locations of all output objects */
for (i = 0; i < npages; i++) {
bas = (L_BYTEA *)ptraGetPtrToItem(pa_data, i);
pdfdata = l_byteaGetData(bas, &size);
da_locs = l_dnaaGetDna(daa_locs, i, L_CLONE); /* locs on this page */
na_objs = numaaGetNuma(naa_objs, i, L_CLONE); /* obj # on this page */
nobj = l_dnaGetCount(da_locs) - 1;
da_sizes = l_dnaDiffAdjValues(da_locs); /* object sizes on this page */
sizes = l_dnaGetIArray(da_sizes);
locs = l_dnaGetIArray(da_locs);
if (i == 0) {
l_byteaAppendData(bad, pdfdata, sizes[0]);
l_byteaAppendData(bad, pdfdata + locs[1], sizes[1]);
l_byteaAppendData(bad, pdfdata + locs[2], sizes[2]);
l_byteaAppendString(bad, str_pages);
for (j = 0; j < 4; j++)
l_dnaAddNumber(da_outlocs, locs[j]);
}
for (j = 4; j < nobj; j++) {
l_dnaAddNumber(da_outlocs, l_byteaGetSize(bad));
bat1 = l_byteaInitFromMem(pdfdata + locs[j], sizes[j]);
bat2 = substituteObjectNumbers(bat1, na_objs);
data = l_byteaGetData(bat2, &size);
l_byteaAppendData(bad, data, size);
l_byteaDestroy(&bat1);
l_byteaDestroy(&bat2);
}
if (i == npages - 1) /* last one */
l_dnaAddNumber(da_outlocs, l_byteaGetSize(bad));
LEPT_FREE(sizes);
LEPT_FREE(locs);
l_dnaDestroy(&da_locs);
numaDestroy(&na_objs);
l_dnaDestroy(&da_sizes);
}
/* Add the trailer */
str_trailer = makeTrailerStringPdf(da_outlocs);
l_byteaAppendString(bad, str_trailer);
/* Transfer the output data */
*pdata = l_byteaCopyData(bad, pnbytes);
l_byteaDestroy(&bad);
#if DEBUG_MULTIPAGE
fprintf(stderr, "******** object mapper **********");
numaaWriteStream(stderr, naa_objs);
fprintf(stderr, "******** Page object numbers ***********");
numaWriteStream(stderr, napage);
fprintf(stderr, "******** Pages object ***********\n");
fprintf(stderr, "%s\n", str_pages);
#endif /* DEBUG_MULTIPAGE */
numaDestroy(&napage);
numaaDestroy(&naa_objs);
l_dnaDestroy(&da_outlocs);
l_dnaaDestroy(&daa_locs);
LEPT_FREE(str_pages);
LEPT_FREE(str_trailer);
return 0;
}
/*---------------------------------------------------------------------*
* Convert tiff multipage to pdf file *
*---------------------------------------------------------------------*/
/*!
* \brief convertTiffMultipageToPdf()
*
* \param[in] filein (tiff)
* \param[in] fileout (pdf)
* \return 0 if OK, 1 on error
*
* <pre>
* Notes:
* (1) A multipage tiff file can also be converted to PS, using
* convertTiffMultipageToPS()
* </pre>
*/
l_ok
convertTiffMultipageToPdf(const char *filein,
const char *fileout)
{
l_int32 istiff;
PIXA *pixa;
FILE *fp;
PROCNAME("convertTiffMultipageToPdf");
if ((fp = fopenReadStream(filein)) == NULL)
return ERROR_INT("file not found", procName, 1);
istiff = fileFormatIsTiff(fp);
fclose(fp);
if (!istiff)
return ERROR_INT("file not tiff format", procName, 1);
pixa = pixaReadMultipageTiff(filein);
pixaConvertToPdf(pixa, 0, 1.0, 0, 0, "weasel2", fileout);
pixaDestroy(&pixa);
return 0;
}
/*---------------------------------------------------------------------*
* Low-level CID-based operations *
*---------------------------------------------------------------------*/
/*!
* \brief l_generateCIDataForPdf()
*
* \param[in] fname [optional] can be null
* \param[in] pix [optional] can be null
* \param[in] quality for jpeg if transcoded: 1-100; 0 for default (75)
* for jp2k if transcoded: 27-45; 0 for default (34)
* \param[out] pcid compressed data
* \return 0 if OK, 1 on error
*
* <pre>
* Notes:
* (1) You must set either filename or pix.
* (2) Given an image file and optionally a pix raster of that data,
* this provides a CID that is compatible with PDF, preferably
* without transcoding.
* (3) The pix is included for efficiency, in case transcoding
* is required and the pix is available to the caller.
* (4) We don't try to open files named "stdin" or "-" for Tesseract
* compatibility reasons. We may remove this restriction
* in the future.
* </pre>
*/
l_ok
l_generateCIDataForPdf(const char *fname,
PIX *pix,
l_int32 quality,
L_COMP_DATA **pcid)
{
l_int32 format, type;
L_COMP_DATA *cid;
PIX *pixt;
PROCNAME("l_generateCIDataForPdf");
if (!pcid)
return ERROR_INT("&cid not defined", procName, 1);
*pcid = cid = NULL;
if (!fname && !pix)
return ERROR_INT("neither fname nor pix are defined", procName, 1);
/* If a compressed file is given that is not 'stdin', see if we
* can generate the pdf output without transcoding. */
if (fname && strcmp(fname, "-") != 0 && strcmp(fname, "stdin") != 0) {
findFileFormat(fname, &format);
if (format == IFF_UNKNOWN)
L_WARNING("file %s format is unknown\n", procName, fname);
if (format == IFF_PS || format == IFF_LPDF) {
L_ERROR("file %s is unsupported format %d\n",
procName, fname, format);
return 1;
}
if (format == IFF_JFIF_JPEG) {
cid = l_generateJpegData(fname, 0);
} else if (format == IFF_JP2) {
cid = l_generateJp2kData(fname);
} else if (format == IFF_PNG) {
cid = l_generateFlateDataPdf(fname, pix);
}
}
/* Otherwise, use the pix to generate the pdf output */
if (!cid) {
if (!pix)
pixt = pixRead(fname);
else
pixt = pixClone(pix);
if (!pixt)
return ERROR_INT("pixt not made", procName, 1);
if (selectDefaultPdfEncoding(pixt, &type)) {
pixDestroy(&pixt);
return 1;
}
pixGenerateCIData(pixt, type, quality, 0, &cid);
pixDestroy(&pixt);
}
if (!cid) {
L_ERROR("totally kerflummoxed\n", procName);
return 1;
}
*pcid = cid;
return 0;
}
/*!
* \brief l_generateFlateDataPdf()
*
* \param[in] fname preferably png
* \param[in] pixs [optional] can be null
* \return cid containing png data, or NULL on error
*
* <pre>
* Notes:
* (1) If you hand this a png file, you are going to get
* png predictors embedded in the flate data. So it has
* come to this. http://xkcd.com/1022/
* (2) Exception: if the png is interlaced or if it is RGBA,
* it will be transcoded.
* (3) If transcoding is required, this will not have to read from
* file if you also input a pix.
* </pre>
*/
L_COMP_DATA *
l_generateFlateDataPdf(const char *fname,
PIX *pixs)
{
l_uint8 *pngcomp = NULL; /* entire PNG compressed file */
l_uint8 *datacomp = NULL; /* gzipped raster data */
l_uint8 *cmapdata = NULL; /* uncompressed colormap */
char *cmapdatahex = NULL; /* hex ascii uncompressed colormap */
l_uint32 i, j, n;
l_int32 format, interlaced;
l_int32 ncolors; /* in colormap */
l_int32 bps; /* bits/sample: usually 8 */
l_int32 spp; /* samples/pixel: 1-grayscale/cmap); 3-rgb; 4-rgba */
l_int32 w, h, cmapflag;
l_int32 xres, yres;
size_t nbytescomp = 0, nbytespng = 0;
FILE *fp;
L_COMP_DATA *cid;
PIX *pix;
PIXCMAP *cmap = NULL;
PROCNAME("l_generateFlateDataPdf");
if (!fname)
return (L_COMP_DATA *)ERROR_PTR("fname not defined", procName, NULL);
findFileFormat(fname, &format);
spp = 0; /* init to spp != 4 if not png */
interlaced = 0; /* initialize to no interlacing */
bps = 0; /* initialize to a nonsense value */
if (format == IFF_PNG) {
isPngInterlaced(fname, &interlaced);
if (readHeaderPng(fname, NULL, NULL, &bps, &spp, NULL))
return (L_COMP_DATA *)ERROR_PTR("bad png input", procName, NULL);
}
/* PDF is capable of inlining some types of PNG files, but not all
of them. We need to transcode anything with interlacing, an
alpha channel, or 1 bpp (which would otherwise be photo-inverted).
Be careful with spp. Any PNG image file with an alpha
channel is converted on reading to RGBA (spp == 4). This
includes the (gray + alpha) format with spp == 2. You
will get different results if you look at spp via
readHeaderPng() versus pixGetSpp() */
if (format != IFF_PNG || interlaced || bps == 1 || spp == 4 || spp == 2) {
if (!pixs)
pix = pixRead(fname);
else
pix = pixClone(pixs);
if (!pix)
return (L_COMP_DATA *)ERROR_PTR("pix not made", procName, NULL);
cid = pixGenerateFlateData(pix, 0);
pixDestroy(&pix);
return cid;
}
/* It's png. Generate the pdf data without transcoding.
* Implementation by Jeff Breidenbach.
* First, read the metadata */
if ((fp = fopenReadStream(fname)) == NULL)
return (L_COMP_DATA *)ERROR_PTR("stream not opened", procName, NULL);
freadHeaderPng(fp, &w, &h, &bps, &spp, &cmapflag);
fgetPngResolution(fp, &xres, &yres);
fclose(fp);
/* We get pdf corruption when inlining the data from 16 bpp png. */
if (bps == 16)
return l_generateFlateData(fname, 0);
/* Read the entire png file */
if ((pngcomp = l_binaryRead(fname, &nbytespng)) == NULL)
return (L_COMP_DATA *)ERROR_PTR("unable to read file",
procName, NULL);
/* Extract flate data, copying portions of it to memory, including
* the predictor information in a byte at the beginning of each
* raster line. The flate data makes up the vast majority of
* the png file, so after extraction we expect datacomp to
* be nearly full (i.e., nbytescomp will be only slightly less
* than nbytespng). Also extract the colormap if present. */
if ((datacomp = (l_uint8 *)LEPT_CALLOC(1, nbytespng)) == NULL) {
LEPT_FREE(pngcomp);
return (L_COMP_DATA *)ERROR_PTR("unable to allocate memory",
procName, NULL);
}
/* Parse the png file. Each chunk consists of:
* length: 4 bytes
* name: 4 bytes (e.g., "IDAT")
* data: n bytes
* CRC: 4 bytes
* Start at the beginning of the data section of the first chunk,
* byte 16, because the png file begins with 8 bytes of header,
* followed by the first 8 bytes of the first chunk
* (length and name). On each loop, increment by 12 bytes to
* skip over the CRC, length and name of the next chunk. */
for (i = 16; i < nbytespng; i += 12) { /* do each successive chunk */
/* Get the chunk length */
n = pngcomp[i - 8] << 24;
n += pngcomp[i - 7] << 16;
n += pngcomp[i - 6] << 8;
n += pngcomp[i - 5] << 0;
if (n >= nbytespng - i) { /* "n + i" can overflow */
LEPT_FREE(pngcomp);
LEPT_FREE(datacomp);
pixcmapDestroy(&cmap);
L_ERROR("invalid png: i = %d, n = %d, nbytes = %zu\n", procName,
i, n, nbytespng);
return NULL;
}
/* Is it a data chunk? */
if (memcmp(pngcomp + i - 4, "IDAT", 4) == 0) {
memcpy(datacomp + nbytescomp, pngcomp + i, n);
nbytescomp += n;
}
/* Is it a palette chunk? */
if (cmapflag && !cmap &&
memcmp(pngcomp + i - 4, "PLTE", 4) == 0) {
if ((n / 3) > (1 << bps)) {
LEPT_FREE(pngcomp);
LEPT_FREE(datacomp);
pixcmapDestroy(&cmap);
L_ERROR("invalid png: i = %d, n = %d, cmapsize = %d\n",
procName, i, n, (1 << bps));
return NULL;
}
cmap = pixcmapCreate(bps);
for (j = i; j < i + n; j += 3) {
pixcmapAddColor(cmap, pngcomp[j], pngcomp[j + 1],
pngcomp[j + 2]);
}
}
i += n; /* move to the end of the data chunk */
}
LEPT_FREE(pngcomp);
if (nbytescomp == 0) {
LEPT_FREE(datacomp);
pixcmapDestroy(&cmap);
return (L_COMP_DATA *)ERROR_PTR("invalid PNG file", procName, NULL);
}
/* Extract and encode the colormap data as hexascii */
ncolors = 0;
if (cmap) {
pixcmapSerializeToMemory(cmap, 3, &ncolors, &cmapdata);
pixcmapDestroy(&cmap);
if (!cmapdata) {
LEPT_FREE(datacomp);
return (L_COMP_DATA *)ERROR_PTR("cmapdata not made",
procName, NULL);
}
cmapdatahex = pixcmapConvertToHex(cmapdata, ncolors);
LEPT_FREE(cmapdata);
}
/* Note that this is the only situation where the predictor
* field of the CID is set to 1. Adobe's predictor values on
* p. 76 of pdf_reference_1-7.pdf give 1 for no predictor and
* 10-14 for inline predictors, the specifics of which are
* ignored by the pdf interpreter, which just needs to know that
* the first byte on each compressed scanline is some predictor
* whose type can be inferred from the byte itself. */
cid = (L_COMP_DATA *)LEPT_CALLOC(1, sizeof(L_COMP_DATA));
cid->datacomp = datacomp;
cid->type = L_FLATE_ENCODE;
cid->cmapdatahex = cmapdatahex;
cid->nbytescomp = nbytescomp;
cid->ncolors = ncolors;
cid->predictor = TRUE;
cid->w = w;
cid->h = h;
cid->bps = bps;
cid->spp = spp;
cid->res = xres;
return cid;
}
/*!
* \brief l_generateJpegData()
*
* \param[in] fname of jpeg file
* \param[in] ascii85flag 0 for jpeg; 1 for ascii85-encoded jpeg
* \return cid containing jpeg data, or NULL on error
*
* <pre>
* Notes:
* (1) Set ascii85flag:
* ~ 0 for binary data (not permitted in PostScript)
* ~ 1 for ascii85 (5 for 4) encoded binary data
* (not permitted in pdf)
* (2) Do not free the data. l_generateJpegDataMem() will free
* the data if the data is invalid, or if it does not use
* ascii encoding.
* </pre>
*/
L_COMP_DATA *
l_generateJpegData(const char *fname,
l_int32 ascii85flag)
{
l_uint8 *data = NULL;
size_t nbytes;
PROCNAME("l_generateJpegData");
if (!fname)
return (L_COMP_DATA *)ERROR_PTR("fname not defined", procName, NULL);
/* The returned jpeg data in memory is the entire jpeg file,
* which starts with ffd8 and ends with ffd9 */
if ((data = l_binaryRead(fname, &nbytes)) == NULL)
return (L_COMP_DATA *)ERROR_PTR("data not extracted", procName, NULL);
return l_generateJpegDataMem(data, nbytes, ascii85flag);
}
/*!
* \brief l_generateJpegDataMem()
*
* \param[in] data of jpeg file
* \param[in] nbytes of jpeg file
* \param[in] ascii85flag 0 for jpeg; 1 for ascii85-encoded jpeg
* \return cid containing jpeg data, or NULL on error
*
* <pre>
* Notes:
* (1) See l_generateJpegData().
* </pre>
*/
L_COMP_DATA *
l_generateJpegDataMem(l_uint8 *data,
size_t nbytes,
l_int32 ascii85flag)
{
char *data85 = NULL; /* ascii85 encoded jpeg compressed file */
l_int32 w, h, xres, yres, bps, spp;
l_int32 nbytes85;
L_COMP_DATA *cid;
PROCNAME("l_generateJpegDataMem");
if (!data)
return (L_COMP_DATA *)ERROR_PTR("data not defined", procName, NULL);
/* Read the metadata */
if (readHeaderMemJpeg(data, nbytes, &w, &h, &spp, NULL, NULL)) {
LEPT_FREE(data);
return (L_COMP_DATA *)ERROR_PTR("bad jpeg metadata", procName, NULL);
}
bps = 8;
readResolutionMemJpeg(data, nbytes, &xres, &yres);
/* Optionally, encode the compressed data */
if (ascii85flag == 1) {
data85 = encodeAscii85(data, nbytes, &nbytes85);
LEPT_FREE(data);
if (!data85)
return (L_COMP_DATA *)ERROR_PTR("data85 not made", procName, NULL);
else
data85[nbytes85 - 1] = '\0'; /* remove the newline */
}
cid = (L_COMP_DATA *)LEPT_CALLOC(1, sizeof(L_COMP_DATA));
if (ascii85flag == 0) {
cid->datacomp = data;
} else { /* ascii85 */
cid->data85 = data85;
cid->nbytes85 = nbytes85;
}
cid->type = L_JPEG_ENCODE;
cid->nbytescomp = nbytes;
cid->w = w;
cid->h = h;
cid->bps = bps;
cid->spp = spp;
cid->res = xres;
return cid;
}
/*!
* \brief l_generateJp2kData()
*
* \param[in] fname of jp2k file
* \return cid containing jp2k data, or NULL on error
*
* <pre>
* Notes:
* (1) This is only called after the file is verified to be jp2k.
* </pre>
*/
static L_COMP_DATA *
l_generateJp2kData(const char *fname)
{
l_int32 w, h, bps, spp, xres, yres;
size_t nbytes;
L_COMP_DATA *cid;
FILE *fp;
PROCNAME("l_generateJp2kData");
if (!fname)
return (L_COMP_DATA *)ERROR_PTR("fname not defined", procName, NULL);
if (readHeaderJp2k(fname, &w, &h, &bps, &spp))
return (L_COMP_DATA *)ERROR_PTR("bad jp2k metadata", procName, NULL);
if ((cid = (L_COMP_DATA *)LEPT_CALLOC(1, sizeof(L_COMP_DATA))) == NULL)
return (L_COMP_DATA *)ERROR_PTR("cid not made", procName, NULL);
/* The returned jp2k data in memory is the entire jp2k file */
if ((cid->datacomp = l_binaryRead(fname, &nbytes)) == NULL) {
l_CIDataDestroy(&cid);
return (L_COMP_DATA *)ERROR_PTR("data not extracted", procName, NULL);
}
xres = yres = 0;
if ((fp = fopenReadStream(fname)) != NULL) {
fgetJp2kResolution(fp, &xres, &yres);
fclose(fp);
}
cid->type = L_JP2K_ENCODE;
cid->nbytescomp = nbytes;
cid->w = w;
cid->h = h;
cid->bps = bps;
cid->spp = spp;
cid->res = xres;
return cid;
}
/*!
* \brief l_generateCIData()
*
* \param[in] fname
* \param[in] type L_G4_ENCODE, L_JPEG_ENCODE, L_FLATE_ENCODE,
* L_JP2K_ENCODE
* \param[in] quality for jpeg if transcoded: 1-100; 0 for default (75)
* for jp2k if transcoded: 27-45; 0 for default (34)
* \param[in] ascii85 0 for binary; 1 for ascii85-encoded
* \param[out] pcid compressed data
* \return 0 if OK, 1 on error
*
* <pre>
* Notes:
* (1) This can be used for both PostScript and pdf.
* (1) Set ascii85:
* ~ 0 for binary data (not permitted in PostScript)
* ~ 1 for ascii85 (5 for 4) encoded binary data
* (2) This attempts to compress according to the requested type.
* If this can't be done, it falls back to ordinary flate encoding.
* (3) This differs from l_generateCIDataPdf(), which determines
* the format and attempts to generate the CID without transcoding.
* </pre>
*/
l_ok
l_generateCIData(const char *fname,
l_int32 type,
l_int32 quality,
l_int32 ascii85,
L_COMP_DATA **pcid)
{
l_int32 format, d, bps, spp, iscmap;
L_COMP_DATA *cid;
PIX *pix;
PROCNAME("l_generateCIData");
if (!pcid)
return ERROR_INT("&cid not defined", procName, 1);
*pcid = NULL;
if (!fname)
return ERROR_INT("fname not defined", procName, 1);
if (type != L_G4_ENCODE && type != L_JPEG_ENCODE &&
type != L_FLATE_ENCODE && type != L_JP2K_ENCODE)
return ERROR_INT("invalid conversion type", procName, 1);
if (ascii85 != 0 && ascii85 != 1)
return ERROR_INT("invalid ascii85", procName, 1);
/* Sanity check on requested encoding */
pixReadHeader(fname, &format, NULL, NULL, &bps, &spp, &iscmap);
d = bps * spp;
if (d == 24) d = 32;
if (iscmap && type != L_FLATE_ENCODE) {