Debian Codegraph @

texk/web2c/luatexdir/image/pdftoepdf.c

raw
1 /*
2 pdftoepdf.w
3
4 Copyright 1996-2006 Han The Thanh <[email protected]>
5 Copyright 2006-2015 Taco Hoekwater <[email protected]>
6
7 This file is part of LuaTeX.
8
9 LuaTeX is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 2 of the License, or (at your
12 option) any later version.
13
14 LuaTeX is distributed in the hope that it will be useful, but WITHOUT
15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
17 License for more details.
18
19 You should have received a copy of the GNU General Public License along
20 with LuaTeX; if not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #define __STDC_FORMAT_MACROS /* for PRId64 etc. */
24
25 #include "image/epdf.h"
26 #include "luatexcallbackids.h"
27
28 /* to be sorted out, we cannot include */
29
30 #define xfree(a) do { free(a); a = NULL; } while (0)
31
32 /* Conflict with pdfgen.h */
33
34 #ifndef pdf_out
35
36 #define pdf_out(pdf, A) do { pdf_room(pdf, 1); *(pdf->buf->p++) = A; } while (0)
37
38 #define pdf_check_space(pdf) do { \
39 if (pdf->cave > 0) { \
40 pdf_out(pdf, ' '); \
41 pdf->cave = 0; \
42 } \
43 } while (0)
44
45 #define pdf_set_space(pdf) \
46 pdf->cave = 1;
47
48 #define pdf_reset_space(pdf) \
49 pdf->cave = 0;
50
51 #endif
52
53 /* Maintain AVL tree of all PDF files for embedding */
54
55 static avl_table *PdfDocumentTree = NULL;
56
57 /* AVL sort PdfDocument into PdfDocumentTree by file_path */
58
59 static int CompPdfDocument(const void *pa, const void *pb, void *p )
60 {
61 return strcmp(((const PdfDocument *) pa)->file_path, ((const PdfDocument *) pb)->file_path);
62 }
63
64 /* Returns pointer to PdfDocument structure for PDF file. */
65
66 static PdfDocument *findPdfDocument(char *file_path)
67 {
68 PdfDocument *pdf_doc, tmp;
69 if (file_path == NULL) {
70 normal_error("pdf backend","empty filename when loading pdf file");
71 } else if (PdfDocumentTree == NULL) {
72 return NULL;
73 }
74 tmp.file_path = file_path;
75 pdf_doc = (PdfDocument *) avl_find(PdfDocumentTree, &tmp);
76 return pdf_doc;
77 }
78
79 #define PDF_CHECKSUM_SIZE 32
80
81 static char *get_file_checksum(const char *a, file_error_mode fe)
82 {
83 struct stat finfo;
84 char *ck = NULL;
85 if (stat(a, &finfo) == 0) {
86 off_t size = finfo.st_size;
87 time_t mtime = finfo.st_mtime;
88 ck = (char *) malloc(PDF_CHECKSUM_SIZE);
89 if (ck == NULL)
90 formatted_error("pdf inclusion","out of memory while processing '%s'", a);
91 snprintf(ck, PDF_CHECKSUM_SIZE, "%" PRIu64 "_%" PRIu64, (uint64_t) size,(uint64_t) mtime);
92 } else {
93 switch (fe) {
94 case FE_FAIL:
95 formatted_error("pdf inclusion","could not stat() file '%s'", a);
96 break;
97 case FE_RETURN_NULL:
98 if (ck != NULL)
99 free(ck);
100 ck = NULL;
101 break;
102 default:
103 assert(0);
104 }
105 }
106 return ck;
107 }
108
109 static char *get_stream_checksum (const char *str, unsigned long long str_size){
110 /* http://www.cse.yorku.ca/~oz/hash.html */
111 /* djb2 */
112 unsigned long hash ;
113 char *ck = NULL;
114 unsigned int i;
115 hash = 5381;
116 ck = (char *) malloc(STRSTREAM_CHECKSUM_SIZE+1);
117 if (ck == NULL)
118 normal_error("pdf inclusion","out of memory while processing a memstream");
119 for(i=0; i<(unsigned int)(str_size); i++) {
120 hash = ((hash << 5) + hash) + str[i]; /* hash * 33 + str[i] */
121 }
122 snprintf(ck,STRSTREAM_CHECKSUM_SIZE+1,"%lx",hash);
123 ck[STRSTREAM_CHECKSUM_SIZE]='\0';
124 return ck;
125 }
126
127 /*
128 Returns pointer to PdfDocument structure for PDF file.
129 Creates a new PdfDocument structure if it doesn't exist yet.
130 When fe = FE_RETURN_NULL, the function returns NULL in error case.
131 */
132
133 PdfDocument *refPdfDocument(const char *file_path, file_error_mode fe, const char *userpassword, const char *ownerpassword)
134 {
135 char *checksum, *path_copy;
136 PdfDocument *pdf_doc;
137 ppdoc *pdfe = NULL;
138 int new_flag = 0;
139 if ((checksum = get_file_checksum(file_path, fe)) == NULL) {
140 return (PdfDocument *) NULL;
141 }
142 path_copy = xstrdup(file_path);
143 if ((pdf_doc = findPdfDocument(path_copy)) == NULL) {
144 new_flag = 1;
145 pdf_doc = (PdfDocument*) xmalloc(sizeof( PdfDocument));
146 pdf_doc->file_path = path_copy;
147 pdf_doc->checksum = checksum;
148 pdf_doc->pdfe = NULL;
149 pdf_doc->inObjList = NULL;
150 pdf_doc->ObjMapTree = NULL;
151 pdf_doc->occurences = 0; /* 0 = unreferenced */
152 pdf_doc->pc = 0;
153 pdf_doc->is_mem = 0;
154 } else {
155 if (strncmp(pdf_doc->checksum, checksum, PDF_CHECKSUM_SIZE) != 0) {
156 formatted_error("pdf inclusion","file has changed '%s'", file_path);
157 }
158 free(checksum);
159 free(path_copy);
160 }
161 if (pdf_doc->pdfe == NULL) {
162 pdfe = ppdoc_load(file_path);
163 pdf_doc->pc++;
164 /* todo: check if we might print the document */
165 if (pdfe == NULL) {
166 switch (fe) {
167 case FE_FAIL:
168 normal_error("pdf inclusion","reading image failed");
169 break;
170 case FE_RETURN_NULL:
171 if (pdf_doc->pdfe != NULL) {
172 ppdoc_free(pdfe);
173 pdf_doc->pdfe = NULL;
174 }
175 /* delete docName */
176 if (new_flag == 1) {
177 if (pdf_doc->file_path != NULL)
178 free(pdf_doc->file_path);
179 if (pdf_doc->checksum != NULL)
180 free(pdf_doc->checksum);
181 free(pdf_doc);
182 }
183 return (PdfDocument *) NULL;
184 break;
185 default:
186 assert(0);
187 }
188 }
189 if (pdfe != NULL) {
190 if (ppdoc_crypt_status(pdfe) < 0 && userpassword==NULL) {
191 formatted_error("pdf inclusion","the pdf file '%s' is encrypted, passwords wrong",file_path);
192 }
193 if (ppdoc_crypt_status(pdfe) < 0) {
194 ppdoc_crypt_pass(pdfe,userpassword,strlen(userpassword),NULL,0);
195 }
196 if (ppdoc_crypt_status(pdfe) < 0) {
197 ppdoc_crypt_pass(pdfe,NULL,0,ownerpassword,strlen(ownerpassword));
198 }
199 if (ppdoc_crypt_status(pdfe) < 0) {
200 formatted_error("pdf inclusion","the pdf file '%s' is encrypted, provide proper passwords",file_path);
201 }
202 }
203 pdf_doc->pdfe = pdfe;
204 }
205 /* PDF file could be opened without problems, checksum ok. */
206 if (PdfDocumentTree == NULL)
207 PdfDocumentTree = avl_create(CompPdfDocument, NULL, &avl_xallocator);
208 if ((PdfDocument *) avl_find(PdfDocumentTree, pdf_doc) == NULL) {
209 avl_probe(PdfDocumentTree, pdf_doc);
210 }
211 pdf_doc->occurences++;
212 return pdf_doc;
213 }
214
215 /*
216 Returns pointer to PdfDocument structure for a PDF stream in memory of streamsize
217 dimension. As before, creates a new PdfDocument structure if it doesn't exist yet
218 with file_path = file_id
219 */
220
221 PdfDocument *refMemStreamPdfDocument(char *docstream, unsigned long long streamsize,const char *file_id)
222 {
223 char *checksum;
224 char *file_path;
225 PdfDocument *pdf_doc;
226 ppdoc *pdfe = NULL;
227 size_t cnt = 0;
228 checksum = get_stream_checksum(docstream, streamsize);
229 cnt = strlen(file_id);
230 file_path = (char *) malloc(cnt+STREAM_URI_LEN+STRSTREAM_CHECKSUM_SIZE+1); /* 1 for \0 */
231 strcpy(file_path,STREAM_URI);
232 strcat(file_path,file_id);
233 strcat(file_path,checksum);
234 file_path[cnt+STREAM_URI_LEN+STRSTREAM_CHECKSUM_SIZE]='\0';
235 if ((pdf_doc = findPdfDocument(file_path)) == NULL) {
236 /*new_flag = 1;*/
237 pdf_doc = (PdfDocument*) xmalloc(sizeof( PdfDocument));
238 pdf_doc->file_path = file_path;
239 pdf_doc->checksum = checksum;
240 pdf_doc->pdfe = NULL;
241 pdf_doc->inObjList = NULL;
242 pdf_doc->ObjMapTree = NULL;
243 pdf_doc->occurences = 0; /* 0 = unreferenced */
244 pdf_doc->pc = 0;
245 pdf_doc->is_mem = 1;
246 pdf_doc->memstream = docstream;
247 } else {
248 /* As is now, checksum is in file_path, so this check should be useless. */
249 if (strncmp(pdf_doc->checksum, checksum, STRSTREAM_CHECKSUM_SIZE) != 0) {
250 formatted_error("pdf inclusion","stream has changed '%s'", file_path);
251 }
252 free(file_path);
253 free(checksum);
254 }
255 if (pdf_doc->pdfe == NULL) {
256 pdfe = ppdoc_mem(docstream, (size_t) streamsize);
257 pdf_doc->pc++;
258 if (pdfe == NULL) {
259 normal_error("pdf inclusion","reading pdf Stream failed");
260 }
261 pdf_doc->pdfe = pdfe;
262 }
263 /* PDF file could be opened without problems, checksum ok. */
264 if (PdfDocumentTree == NULL)
265 PdfDocumentTree = avl_create(CompPdfDocument, NULL, &avl_xallocator);
266 if ((PdfDocument *) avl_find(PdfDocumentTree, pdf_doc) == NULL) {
267 avl_probe(PdfDocumentTree, pdf_doc);
268 }
269 pdf_doc->occurences++;
270 return pdf_doc;
271 }
272
273 /*
274 AVL sort ObjMap into ObjMapTree by object number and generation keep the ObjMap
275 struct small, as these are accumulated until the end
276 */
277
278 typedef struct ObjMap ObjMap ;
279
280 struct ObjMap {
281 /* int version; */ /* not really needed */
282 int objnum;
283 int out_num;
284 };
285
286 static int CompObjMap(const void *pa, const void *pb, void *p)
287 {
288 const ObjMap *a = (((const ObjMap *) pa));
289 const ObjMap *b = (((const ObjMap *) pb));
290 if (a->objnum > b->objnum)
291 return 1;
292 else if (a->objnum < b->objnum)
293 return -1;
294 /*
295 else if (a->version == b->version)
296 return 0;
297 else if (a->version < b->version)
298 return -1;
299 return 1;
300 */
301 return 0;
302 }
303
304 static ObjMap *findObjMap(PdfDocument * pdf_doc, ppref * in)
305 {
306 ObjMap *obj_map, tmp;
307 if (pdf_doc->ObjMapTree == NULL) {
308 return NULL;
309 }
310 tmp.objnum = in->number;
311 /* tmp.version = in->version; */
312 obj_map = (ObjMap *) avl_find(pdf_doc->ObjMapTree, &tmp);
313 return obj_map;
314 }
315
316 static void addObjMap(PdfDocument * pdf_doc, ppref * in, int out_num)
317 {
318 ObjMap *obj_map = NULL;
319 if (pdf_doc->ObjMapTree == NULL) {
320 pdf_doc->ObjMapTree = avl_create(CompObjMap, NULL, &avl_xallocator);
321 }
322 obj_map = (ObjMap*)xmalloc(sizeof(ObjMap));
323 /* obj_map->version = in->version; */
324 obj_map->objnum = in->number;
325 obj_map->out_num = out_num;
326 avl_probe(pdf_doc->ObjMapTree, obj_map);
327 }
328
329 /*
330 When copying the Resources of the selected page, all objects are
331 copied recursively top-down. The findObjMap() function checks if an
332 object has already been copied; if so, instead of copying just the
333 new object number will be referenced. The ObjMapTree guarantees,
334 that during the entire LuaTeX run any object from any embedded PDF
335 file will end up max. once in the output PDF file. Indirect objects
336 are not fetched during copying, but get a new object number from
337 LuaTeX and then will be appended into a linked list.
338 */
339
340 static int addInObj(PDF pdf, PdfDocument * pdf_doc, ppref * ref)
341 {
342 ObjMap *obj_map;
343 InObj *p, *q, *n;
344 if (ref->number == 0) {
345 normal_error("pdf inclusion","reference to invalid object (broken pdf)");
346 }
347 if ((obj_map = findObjMap(pdf_doc, ref)) != NULL) {
348 return obj_map->out_num;
349 }
350 n = (InObj*)xmalloc(sizeof(InObj));
351 n->objnum = ref->number;
352 /* n->version = ref->version; */
353 n->next = NULL;
354 n->num = pdf_create_obj(pdf, obj_type_others, 0);
355 addObjMap(pdf_doc, ref, n->num);
356 if (pdf_doc->inObjList == NULL) {
357 pdf_doc->inObjList = n;
358 } else {
359 /*
360 It is important to add new objects at the end of the list,
361 because new objects are being added while the list is being
362 written out by writeRefs().
363 */
364 q = NULL;
365 for (p = pdf_doc->inObjList; p != NULL; p = p->next)
366 q = p;
367 if (q)
368 q->next = n;
369 }
370 return n->num;
371 }
372
373 static void copyObject(PDF, PdfDocument *, ppobj *);
374
375 static void copyString(PDF pdf, ppstring *str)
376 {
377 pdf_check_space(pdf);
378 switch (ppstring_type(str)) {
379 case PPSTRING_PLAIN:
380 pdf_out(pdf, '(');
381 pdf_out_block(pdf, ppstring_data(str), ppstring_size(str));
382 pdf_out(pdf, ')');
383 break;
384 case PPSTRING_BASE16:
385 pdf_out(pdf, '<');
386 pdf_out_block(pdf, ppstring_data(str), ppstring_size(str));
387 pdf_out(pdf, '>');
388 break;
389 case PPSTRING_BASE85:
390 pdf_out(pdf, '<');
391 pdf_out(pdf, '~');
392 pdf_out_block(pdf, ppstring_data(str), ppstring_size(str));
393 pdf_out(pdf, '~');
394 pdf_out(pdf, '>');
395 break;
396 }
397 pdf_set_space(pdf);
398 }
399
400 static void copyName(PDF pdf, ppname *name)
401 {
402 pdf_add_name(pdf, ppname_data(name));
403 }
404
405 static void copyArray(PDF pdf, PdfDocument * pdf_doc, pparray * array)
406 {
407 int i;
408 int n = array->size;
409 pdf_begin_array(pdf);
410 for (i=0; i<n; ++i) {
411 copyObject(pdf, pdf_doc, pparray_at(array,i));
412 }
413 pdf_end_array(pdf);
414 }
415
416 static void copyDict(PDF pdf, PdfDocument * pdf_doc, ppdict *dict)
417 {
418 int i;
419 int n = dict->size;
420 pdf_begin_dict(pdf);
421 for (i=0; i<n; ++i) {
422 ppname *key = ppdict_key(dict,i);
423 pdf_add_name(pdf,ppname_data(key));
424 copyObject(pdf, pdf_doc, ppdict_at(dict,i));
425 }
426 pdf_end_dict(pdf);
427 }
428
429 static void copyStreamStream(PDF pdf, ppstream * stream, int decode, int callback_id)
430 {
431 uint8_t *data = NULL;
432 size_t size = 0;
433 if (0) {
434 for (data = ppstream_first(stream, &size, decode); data != NULL; data = ppstream_next(stream, &size)) {
435 pdf_out_block(pdf, (const char *) data, size);
436 }
437 } else {
438 data = ppstream_all(stream,&size,decode);
439 if (data != NULL) {
440 /*tex We only do this when we recompress in which case we fetch the whole stream. */
441 if (callback_id == 1) {
442 callback_id = callback_defined(process_pdf_image_content_callback);
443 }
444 if (callback_id) {
445 char *result = NULL;
446 run_callback(callback_id, "S->S",(char *) data,&result);
447 pdf_out_block(pdf, (const char *) (uint8_t *) result, size);
448 xfree(result);
449 } else {
450 pdf_out_block(pdf, (const char *) data, size);
451 }
452 }
453 }
454 ppstream_done(stream);
455 }
456
457 static void copyStream(PDF pdf, PdfDocument * pdf_doc, ppstream * stream)
458 {
459 ppdict *dict = stream->dict; /* bug in: stream_dict(stream) */
460 if (pdf->compress_level == 0 || pdf->recompress) {
461 ppobj * obj = ppdict_get_obj (dict, "Filter");
462 int known = 0;
463 if (obj != NULL && obj->type == PPNAME) {
464 const char *codecs[] = {
465 "ASCIIHexDecode", "ASCII85Decode", "RunLengthDecode",
466 "FlateDecode", "LZWDecode", NULL
467 };
468 int k;
469 for (k = 0; codecs[k] != NULL; k++) {
470 if (strcmp(ppname_data(obj->name),codecs[k]) == 0) {
471 known = 1;
472 break;
473 }
474 }
475 }
476 if (known) {
477 /*tex recompress or keep uncompressed */
478 const char *ignoredkeys[] = {
479 "Filter", "DecodeParms", "Length", "DL", NULL
480 };
481 int i;
482 pdf_begin_dict(pdf);
483 for (i=0; i<dict->size; ++i) {
484 ppname *key = ppdict_key(dict,i);
485 int copy = 1;
486 int k;
487 for (k = 0; ignoredkeys[k] != NULL; k++) {
488 if (strcmp(ppname_data(key),ignoredkeys[k]) == 0) {
489 copy = 0;
490 break;
491 }
492 }
493 if (copy) {
494 pdf_add_name(pdf, ppname_data(key));
495 copyObject(pdf, pdf_doc, ppdict_at(dict,i));
496 }
497 }
498 pdf_dict_add_streaminfo(pdf);
499 pdf_end_dict(pdf);
500 pdf_begin_stream(pdf);
501 copyStreamStream(pdf, stream, 1, 0);
502 pdf_end_stream(pdf);
503 return ;
504 }
505 }
506 /* copy as-is */
507 copyDict(pdf, pdf_doc, dict);
508 pdf_begin_stream(pdf);
509 copyStreamStream(pdf, stream, 0, 0);
510 pdf_end_stream(pdf);
511 }
512
513 static void copyObject(PDF pdf, PdfDocument * pdf_doc, ppobj * obj)
514 {
515 switch (obj->type) {
516 case PPNULL:
517 pdf_add_null(pdf);
518 break;
519 case PPBOOL:
520 pdf_add_bool(pdf,obj->integer); /* ppobj_get_bool_value(obj) */
521 break;
522 case PPINT:
523 pdf_add_int(pdf,obj->integer); /* ppobj_get_int_value(obj) */
524 break;
525 case PPNUM:
526 pdf_add_real(pdf,obj->number); /* ppobj_get_num_value(obj) */
527 break;
528 case PPNAME:
529 copyName(pdf, obj->name);
530 break;
531 case PPSTRING:
532 copyString(pdf, obj->string); /* ppobj_get_string(obj) */
533 break;
534 case PPARRAY:
535 copyArray(pdf, pdf_doc, obj->array); /* ppobj_get_array(obj) */
536 break;
537 case PPDICT:
538 copyDict(pdf, pdf_doc, obj->dict); /* ppobj_get_dict(obj) */
539 break;
540 case PPSTREAM:
541 copyStream(pdf, pdf_doc, obj->stream); /* ppobj_get_stream(obj) */
542 break;
543 case PPREF:
544 pdf_add_ref(pdf, addInObj(pdf, pdf_doc, obj->ref)); /* ppobj_get_ref(obj) */
545 break;
546 default:
547 break;
548 }
549 }
550
551 static void writeRefs(PDF pdf, PdfDocument * pdf_doc)
552 {
553 InObj *r, *n;
554 ppobj * obj;
555 ppref * ref ;
556 ppxref * xref = ppdoc_xref (pdf_doc->pdfe);
557 for (r = pdf_doc->inObjList; r != NULL;) {
558 if (xref != NULL) {
559 ref = ppxref_find(xref, (ppuint) r->objnum);
560 if (ref != NULL) {
561 obj = ppref_obj(ref);
562 if (obj->type == PPSTREAM) {
563 pdf_begin_obj(pdf, r->num, OBJSTM_NEVER);
564 } else {
565 pdf_begin_obj(pdf, r->num, 2);
566 }
567 copyObject(pdf, pdf_doc, obj);
568 pdf_end_obj(pdf);
569 } else {
570 formatted_warning("pdf inclusion","ignoring missing object %i, case 1\n",(int) r->objnum);
571 }
572 } else {
573 formatted_warning("pdf inclusion","ignoring missing object %i, case 2\n",(int) r->objnum);
574 }
575 n = r->next;
576 free(r);
577 r = n;
578 pdf_doc->inObjList = n;
579 }
580 }
581
582
583 /* get the pagebox coordinates according to the pagebox_spec */
584
585 static void somebox(ppdict *page, const char * key, pprect * box)
586 {
587 pprect * r = ppdict_get_box(page, key, box);
588 if (r != NULL) {
589 box->lx = r->lx;
590 box->ly = r->ly;
591 box->rx = r->rx;
592 box->ry = r->ry;
593 }
594 }
595
596 static void get_pagebox(ppdict * page, int pagebox_spec, pprect * box)
597 {
598 box->lx = box->rx = box->ly = box->ry = 0;
599 somebox(page,"MediaBox",box);
600 if (pagebox_spec == PDF_BOX_SPEC_MEDIA) {
601 return;
602 }
603 somebox(page,"CropBox",box);
604 if (pagebox_spec == PDF_BOX_SPEC_CROP) {
605 return;
606 }
607 switch (pagebox_spec) {
608 case PDF_BOX_SPEC_BLEED:
609 somebox(page,"BleedBox",box);
610 break;
611 case PDF_BOX_SPEC_TRIM:
612 somebox(page,"TrimBox",box);
613 break;
614 case PDF_BOX_SPEC_ART:
615 somebox(page,"ArtBox",box);
616 break;
617 default:
618 break;
619 }
620 }
621
622 /*
623 Reads various information about the PDF and sets it up for later inclusion.
624 This will fail if the PDF version of the PDF is higher than minor_pdf_version_wanted
625 or page_name is given and can not be found. It makes no sense to give page_name and
626 page_num. Returns the page number.
627 */
628
629 static ppdict * get_pdf_page_dict(ppdoc *pdfe, int n)
630 {
631 ppref *r;
632 int i;
633 for (r=ppdoc_first_page(pdfe), i=1; r != NULL; r = ppdoc_next_page(pdfe), ++i) {
634 if (i == n) {
635 return ppref_obj(r)->dict;
636 }
637 }
638 return NULL;
639 }
640
641 void read_pdf_info(image_dict * idict)
642 {
643 PdfDocument *pdf_doc = NULL;
644 ppdoc * pdfe = NULL;
645 ppdict *pageDict, *groupDict;
646 pprect pagebox;
647 ppint rotate = 0;
648 int pdf_major_version_found = 1;
649 int pdf_minor_version_found = 3;
650 double xsize, ysize, xorig, yorig;
651 if (img_type(idict) == IMG_TYPE_PDF) {
652 pdf_doc = refPdfDocument(img_filepath(idict), FE_FAIL, img_userpassword(idict), img_ownerpassword(idict));
653 } else if (img_type(idict) == IMG_TYPE_PDFMEMSTREAM) {
654 pdf_doc = findPdfDocument(img_filepath(idict)) ;
655 if (pdf_doc == NULL )
656 normal_error("pdf inclusion", "memstream not initialized");
657 if (pdf_doc->pdfe == NULL)
658 normal_error("pdf inclusion", "memstream document is empty");
659 pdf_doc->occurences++;
660 } else {
661 normal_error("pdf inclusion","unknown document");
662 }
663 pdfe = pdf_doc->pdfe;
664 /*
665 Check PDF version. This works only for PDF 1.x but since any versions of
666 PDF newer than 1.x will not be backwards compatible to PDF 1.x, we will
667 then have to changed drastically anyway.
668 */
669 pdf_major_version_found = ppdoc_version_number(pdfe,&pdf_minor_version_found);
670 if ((100 * pdf_major_version_found + pdf_minor_version_found) > (100 * img_pdfmajorversion(idict) + img_pdfminorversion(idict))) {
671 const char *msg = "PDF inclusion: found PDF version '%d.%d', but at most version '%d.%d' allowed";
672 if (img_errorlevel(idict) > 0) {
673 formatted_error("pdf inclusion",msg, pdf_major_version_found, pdf_minor_version_found, img_pdfmajorversion(idict), img_pdfminorversion(idict));
674 } else {
675 formatted_warning("pdf inclusion",msg, pdf_major_version_found, pdf_minor_version_found, img_pdfmajorversion(idict), img_pdfminorversion(idict));
676 }
677 }
678 img_totalpages(idict) = ppdoc_page_count(pdfe);
679 if (img_pagename(idict)) {
680 /*
681 get page by name is obsolete
682 */
683 normal_error("pdf inclusion","named pages are not supported");
684 } else {
685 /*
686 get page by number
687 */
688 if (img_pagenum(idict) <= 0
689 || img_pagenum(idict) > img_totalpages(idict))
690 formatted_error("pdf inclusion","required page '%i' does not exist",(int) img_pagenum(idict));
691 }
692 /*
693 get the required page
694 */
695 pageDict = get_pdf_page_dict(pdfe,img_pagenum(idict));
696 if (pageDict==NULL) {
697 formatted_error("pdf inclusion","unable to retrive dictionary for page '%i'",(int) img_pagenum(idict));
698 }
699 /*
700 get the pagebox coordinates (media, crop,...) to use
701 */
702 get_pagebox(pageDict, img_pagebox(idict), &pagebox);
703 if (pagebox.rx > pagebox.lx) {
704 xorig = pagebox.lx;
705 xsize = pagebox.rx - pagebox.lx;
706 } else {
707 xorig = pagebox.rx;
708 xsize = pagebox.lx - pagebox.rx;
709 }
710 if (pagebox.ry > pagebox.ly) {
711 yorig = pagebox.ly;
712 ysize = pagebox.ry - pagebox.ly;
713 } else {
714 yorig = pagebox.ry;
715 ysize = pagebox.ly - pagebox.ry;
716 }
717 /*
718 The following 4 parameters are raw. Do _not_ modify by /Rotate!
719 */
720 img_xsize(idict) = bp2sp(xsize);
721 img_ysize(idict) = bp2sp(ysize);
722 img_xorig(idict) = bp2sp(xorig);
723 img_yorig(idict) = bp2sp(yorig);
724 /*
725 Handle /Rotate parameter. Only multiples of 90 deg. are allowed (PDF Ref. v1.3,
726 p. 78). We also accept negative angles. Beware: PDF counts clockwise!
727 */
728 if (ppdict_get_int(pageDict, "Rotate", &rotate)) {
729 switch ((((int)rotate % 360) + 360) % 360) {
730 case 0:
731 img_rotation(idict) = 0;
732 break;
733 case 90:
734 img_rotation(idict) = 3;
735 break;
736 case 180:
737 img_rotation(idict) = 2;
738 break;
739 case 270:
740 img_rotation(idict) = 1;
741 break;
742 default:
743 formatted_warning("pdf inclusion","/Rotate parameter in PDF file not multiple of 90 degrees");
744 }
745 }
746 /*
747 currently unused info whether PDF contains a /Group
748 */
749 groupDict = ppdict_get_dict(pageDict, "Group");
750 if (groupDict != NULL) {
751 img_set_group(idict);
752 }
753 /*
754 LuaTeX pre 0.85 versions did this:
755
756 if (readtype == IMG_CLOSEINBETWEEN) {
757 unrefPdfDocument(img_filepath(idict));
758 }
759
760 and also unref'd in the finalizer so we got an extra unrefs when garbage was
761 collected. However it is more efficient to keep the file open so we do that
762 now. The (slower) alternative is to unref here (which in most cases forcing a
763 close of the file) but then we must not call flush_pdf_info.
764
765 A close (unref) can be forced by nilling the dict object at the lua end and
766 forcing a collectgarbage("collect") after that.
767
768 */
769 if (! img_keepopen(idict)) {
770 unrefPdfDocument(img_filepath(idict));
771 }
772 }
773
774 void flush_pdf_info(image_dict * idict)
775 {
776 if (img_keepopen(idict)) {
777 unrefPdfDocument(img_filepath(idict));
778 }
779 }
780
781 /*
782 Write the current epf_doc. Here the included PDF is copied, so most errors
783 that can happen during PDF inclusion will arise here.
784 */
785
786 void write_epdf(PDF pdf, image_dict * idict, int suppress_optional_info)
787 {
788 PdfDocument *pdf_doc = NULL;
789 ppdoc *pdfe = NULL;
790 ppdict *pageDict, *infoDict;
791 ppobj *obj, *content, *resources;
792 pprect pagebox;
793 int i;
794 double bbox[4];
795 const char *pagedictkeys[] = {
796 "Group", "LastModified", "Metadata", "PieceInfo", "SeparationInfo", NULL
797 };
798 /*
799 open PDF file
800 */
801 if (img_type(idict) == IMG_TYPE_PDF) {
802 pdf_doc = refPdfDocument(img_filepath(idict), FE_FAIL, img_userpassword(idict), img_ownerpassword(idict));
803 } else if (img_type(idict) == IMG_TYPE_PDFMEMSTREAM) {
804 pdf_doc = findPdfDocument(img_filepath(idict)) ;
805 pdf_doc->occurences++;
806 } else {
807 normal_error("pdf inclusion","unknown document");
808 }
809 pdfe = pdf_doc->pdfe;
810 pageDict = get_pdf_page_dict(pdfe,img_pagenum(idict));
811 if (pageDict==NULL) {
812 formatted_error("pdf inclusion","unable to retrive dictionary for page '%i'",(int) img_pagenum(idict));
813 }
814 /*
815 write the Page header
816 */
817 pdf_begin_obj(pdf, img_objnum(idict), OBJSTM_NEVER);
818 pdf_begin_dict(pdf);
819 pdf_dict_add_name(pdf, "Type", "XObject");
820 pdf_dict_add_name(pdf, "Subtype", "Form");
821 pdf_dict_add_int(pdf, "FormType", 1);
822 /*
823 write additional information
824 */
825 pdf_dict_add_img_filename(pdf, idict);
826 if ((suppress_optional_info & 4) == 0) {
827 pdf_dict_add_int(pdf, pdf_pdf_prefix_str("PTEX_PageNumber", "PTEX.PageNumber"), (int) img_pagenum(idict));
828 }
829 if ((suppress_optional_info & 8) == 0) {
830 infoDict = ppdoc_info(pdfe);
831 if (infoDict != NULL) {
832 pdf_add_name(pdf,pdf_pdf_prefix_str("PTEX_InfoDict", "PTEX.InfoDict"));
833 copyDict(pdf, pdf_doc, infoDict);
834 }
835 }
836 if (img_is_bbox(idict)) {
837 bbox[0] = sp2bp(img_bbox(idict)[0]);
838 bbox[1] = sp2bp(img_bbox(idict)[1]);
839 bbox[2] = sp2bp(img_bbox(idict)[2]);
840 bbox[3] = sp2bp(img_bbox(idict)[3]);
841 } else {
842 /*
843 get the pagebox coordinates (media, crop,...) to use.
844 */
845 get_pagebox(pageDict, img_pagebox(idict), &pagebox);
846 bbox[0] = pagebox.lx;
847 bbox[1] = pagebox.ly;
848 bbox[2] = pagebox.rx;
849 bbox[3] = pagebox.ry;
850 }
851 pdf_add_name(pdf, "BBox");
852 pdf_begin_array(pdf);
853 pdf_add_real(pdf, bbox[0]);
854 pdf_add_real(pdf, bbox[1]);
855 pdf_add_real(pdf, bbox[2]);
856 pdf_add_real(pdf, bbox[3]);
857 pdf_end_array(pdf);
858 /*
859 Now all relevant parts of the Page dictionary are copied. Metadata validity
860 check is needed(as a stream it must be indirect).
861 */
862 obj = ppdict_get_obj(pageDict, "Metadata");
863 if (obj != NULL && obj->type != PPREF) {
864 formatted_warning("pdf inclusion","/Metadata must be indirect object");
865 }
866 /*
867 copy selected items in Page dictionary
868 */
869 for (i = 0; pagedictkeys[i] != NULL; i++) {
870 obj = ppdict_get_obj(pageDict, pagedictkeys[i]);
871 if (obj != NULL) {
872 pdf_add_name(pdf, pagedictkeys[i]);
873 /*
874 preserves indirection
875 */
876 copyObject(pdf, pdf_doc, obj);
877 }
878 }
879 resources = ppdict_rget_obj(pageDict, "Resources");
880 if (resources == NULL) {
881 /*
882 If there are no Resources in the Page dict of the embedded page,
883 try to inherit the Resources from the Pages tree of the embedded
884 PDF file, climbing up the tree until the Resources are found.
885 (This fixes a problem with Scribus 1.3.3.14.)
886 */
887 obj = ppdict_rget_obj(pageDict, "Parent");
888 while (obj != NULL && obj->type == PPDICT) {
889 resources = ppdict_rget_obj(obj->dict, "Resources");
890 if (resources != NULL) {
891 break;
892 }
893 obj = ppdict_get_obj(obj->dict, "Parent");
894 }
895 }
896 if (resources != NULL) {
897 pdf_add_name(pdf, "Resources");
898 copyObject(pdf, pdf_doc, resources);
899 } else {
900 formatted_warning("pdf inclusion","Page /Resources missing");
901 }
902 /*
903 User supplied entries.
904 */
905 if (img_attr(idict) != NULL && strlen(img_attr(idict)) > 0) {
906 pdf_printf(pdf, "\n%s\n", img_attr(idict));
907 }
908 /*
909 Write the Page contents.
910 */
911 content = ppdict_rget_obj(pageDict, "Contents");
912 if (content && content->type == PPSTREAM) {
913 if (pdf->compress_level == 0 || pdf->recompress) {
914 pdf_dict_add_streaminfo(pdf);
915 pdf_end_dict(pdf);
916 pdf_begin_stream(pdf);
917 copyStreamStream(pdf, content->stream, 1, 1); /* decompress */
918 } else {
919 /* copies compressed stream */
920 ppstream * stream = content->stream;
921 ppdict *streamDict = stream->dict; /* */
922 obj = ppdict_rget_obj(streamDict, "Length");
923 if (obj != NULL) {
924 pdf_add_name(pdf, "Length");
925 copyObject(pdf, pdf_doc, obj);
926 obj = ppdict_rget_obj(streamDict, "Filter");
927 if (obj != NULL) {
928 pdf_add_name(pdf, "Filter");
929 copyObject(pdf, pdf_doc, obj);
930 /* the next one is irrelevant, only for inline images: */
931 /*
932 obj = ppdict_rget_obj(streamDict, "DecodeParms");
933 if (obj != NULL) {
934 pdf_add_name(pdf, "DecodeParms");
935 copyObject(pdf, pdf_doc, obj);
936 }
937 */
938 }
939 pdf_end_dict(pdf);
940 pdf_begin_stream(pdf);
941 copyStreamStream(pdf, stream, 0, 0);
942 } else {
943 pdf_dict_add_streaminfo(pdf);
944 pdf_end_dict(pdf);
945 pdf_begin_stream(pdf);
946 copyStreamStream(pdf, stream, 1, 0);
947 }
948 }
949 pdf_end_stream(pdf);
950 } else if (content && content->type == PPARRAY) {
951 /* listens to compresslevel */
952 pdf_dict_add_streaminfo(pdf);
953 pdf_end_dict(pdf);
954 pdf_begin_stream(pdf);
955 {
956 int i;
957 int b = 0;
958 int n = content->array->size;
959 for (i=0; i<n; ++i) {
960 ppobj *o = pparray_at(content->array,i);
961 while (o != NULL && o->type == PPREF) {
962 o = ppref_obj((ppref *) o->ref);
963 }
964 if (o != NULL && o->type == PPSTREAM) {
965 if (b) {
966 /*
967 Put a space between streams to be on the safe side (streams
968 should have a trailing space here, but one never knows)
969 */
970 pdf_out(pdf, ' ');
971 } else {
972 b = 1;
973 }
974 copyStreamStream(pdf, (ppstream *) o->stream, 1, 0);
975 }
976 }
977 }
978 pdf_end_stream(pdf);
979 } else {
980 /*
981 the contents are optional, but we need to include an empty stream
982 */
983 pdf_dict_add_streaminfo(pdf);
984 pdf_end_dict(pdf);
985 pdf_begin_stream(pdf);
986 pdf_end_stream(pdf);
987 }
988 pdf_end_obj(pdf);
989 /*
990 write out all indirect objects
991 */
992 writeRefs(pdf, pdf_doc);
993 /*
994 unrefPdfDocument() must come after freeing whatever is used
995
996 */
997 if (! img_keepopen(idict)) {
998 unrefPdfDocument(img_filepath(idict));
999 }
1000 }
1001
1002 /* a special simple case of inclusion, e.g. an appearance stream */
1003
1004 int write_epdf_object(PDF pdf, image_dict * idict, int n)
1005 {
1006 int num = 0 ;
1007 if (img_type(idict) != IMG_TYPE_PDF) {
1008 normal_error("pdf inclusion","unknown document");
1009 } else {
1010 PdfDocument * pdf_doc = refPdfDocument(img_filepath(idict), FE_FAIL, img_userpassword(idict), img_ownerpassword(idict));
1011 ppdoc * pdfe = pdf_doc->pdfe;
1012 if (ppdoc_xref(pdfe)) {
1013 ppref * ref = ppxref_find(ppdoc_xref(pdfe), (ppuint) n);
1014 if (ref != NULL) {
1015 ppobj *obj;
1016 num = pdf->obj_count++;
1017 obj = ppref_obj(ref);
1018 if (obj->type == PPSTREAM) {
1019 pdf_begin_obj(pdf, num, OBJSTM_NEVER);
1020 } else {
1021 pdf_begin_obj(pdf, num, 2);
1022 }
1023 copyObject(pdf, pdf_doc, obj);
1024 pdf_end_obj(pdf);
1025 writeRefs(pdf, pdf_doc);
1026 } else {
1027 formatted_warning("pdf inclusion","ignoring missing image %i, case 1\n",(int) n);
1028 }
1029 } else {
1030 formatted_warning("pdf inclusion","ignoring missing image %i, case 2\n",(int) n);
1031 }
1032 if (! img_keepopen(idict)) {
1033 unrefPdfDocument(img_filepath(idict));
1034 }
1035 }
1036 return num;
1037 }
1038
1039 /* Deallocate a PdfDocument with all its resources. */
1040
1041 static void deletePdfDocumentPdfDoc(PdfDocument * pdf_doc)
1042 {
1043 InObj *r, *n;
1044 /* this may be probably needed for an emergency destroyPdfDocument() */
1045 for (r = pdf_doc->inObjList; r != NULL; r = n) {
1046 n = r->next;
1047 free(r);
1048 }
1049 if (pdf_doc->pdfe != NULL) {
1050 ppdoc_free(pdf_doc->pdfe);
1051 pdf_doc->pdfe = NULL;
1052 }
1053 if (pdf_doc->memstream != NULL) {
1054 /* pplib does this: free(pdf_doc->memstream); */
1055 pdf_doc->memstream = NULL;
1056 }
1057 /* pdf_doc->pc++; */
1058 pdf_doc->pc = 0;
1059 }
1060
1061 static void destroyPdfDocument(void *pa, void * p)
1062 {
1063 PdfDocument *pdf_doc = (PdfDocument *) pa;
1064 deletePdfDocumentPdfDoc(pdf_doc);
1065 /* TODO: delete rest of pdf_doc */
1066 }
1067
1068 /*
1069 Called when an image has been written and its resources in image_tab are
1070 freed and it's not referenced anymore.
1071 */
1072
1073 void unrefPdfDocument(char *file_path)
1074 {
1075 PdfDocument *pdf_doc = findPdfDocument(file_path);
1076 if (pdf_doc == NULL) {
1077 /* we're ok */
1078 } else if (pdf_doc->occurences > 0) {
1079 pdf_doc->occurences--;
1080 if (pdf_doc->occurences == 0) {
1081 deletePdfDocumentPdfDoc(pdf_doc);
1082 }
1083 } else {
1084 /*
1085 We either have a mismatch in ref and unref or we're somehow out of sync
1086 which can happen when we mess with the same file in lua and tex.
1087 */
1088 formatted_warning("pdf inclusion","there can be a mismatch in opening and closing file '%s'",file_path);
1089 }
1090 }
1091
1092 /*
1093 For completeness, but it isn't currently used (unreferencing is done by mean
1094 of file_path.
1095 */
1096
1097 void unrefMemStreamPdfDocument(char *file_id)
1098 {
1099 (void) unrefPdfDocument(file_id);
1100
1101 }
1102
1103 /*
1104 Called when PDF embedding system is finalized. We now deallocate all remaining
1105 PdfDocuments.
1106 */
1107
1108 void epdf_free(void)
1109 {
1110 if (PdfDocumentTree != NULL)
1111 avl_destroy(PdfDocumentTree, destroyPdfDocument);
1112 PdfDocumentTree = NULL;
1113 }