Debian Codegraph @

texk/web2c/pdftexdir/pdftoepdf.cc

raw
1 /*
2 Copyright 1996-2024 Han The Thanh, <[email protected]>
3
4 This file is part of pdfTeX.
5
6 pdfTeX is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 pdfTeX is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License along
17 with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 /* Do this early in order to avoid a conflict between
21 MINGW32 <rpcndr.h> defining 'boolean' as 'unsigned char' and
22 <kpathsea/types.h> defining Pascal's boolean as 'int'.
23 */
24 #include <w2c/config.h>
25 #include <kpathsea/lib.h>
26
27 #include <stdlib.h>
28 #include <math.h>
29 #include <stddef.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <ctype.h>
33
34 #include <aconf.h>
35 #include <GString.h>
36 #include <gmem.h>
37 #include <gfile.h>
38 #include <assert.h>
39
40 #include "Object.h"
41 #include "Stream.h"
42 #include "Array.h"
43 #include "Dict.h"
44 #include "XRef.h"
45 #include "Catalog.h"
46 #include "Link.h"
47 #include "Page.h"
48 #include "GfxFont.h"
49 #include "PDFDoc.h"
50 #include "GlobalParams.h"
51 #include "Error.h"
52
53 // This file is mostly C and not very much C++; it's just used to interface
54 // the functions of xpdf, which are written in C++.
55
56 extern "C" {
57 #include <pdftexdir/ptexmac.h>
58 #include <pdftexdir/pdftex-common.h>
59
60 // These functions from pdftex.web gets declared in pdftexcoerce.h in the
61 // usual web2c way, but we cannot include that file here because C++
62 // does not allow it.
63 extern int getpdfsuppresswarningpagegroup(void);
64 extern integer getpdfsuppressptexinfo(void);
65 extern integer getptexuseunderscore(void);
66 extern integer zround(double);
67 }
68
69 // The prefix "PTEX" for the PDF keys is special to pdfTeX;
70 // this has been registered with Adobe by Hans Hagen.
71
72 #define pdfkeyprefix "PTEX"
73
74 #define MASK_SUPPRESS_PTEX_FULLBANNER 0x01
75 #define MASK_SUPPRESS_PTEX_FILENAME 0x02
76 #define MASK_SUPPRESS_PTEX_PAGENUMBER 0x04
77 #define MASK_SUPPRESS_PTEX_INFODICT 0x08
78
79 // PdfObject encapsulates the xpdf Object type,
80 // and properly frees its resources on destruction.
81 // Use obj-> to access members of the Object,
82 // and &obj to get a pointer to the object.
83 // It is no longer necessary to call Object::free explicitely.
84
85 class PdfObject {
86 public:
87 PdfObject() { // nothing
88 } ~PdfObject() {
89 iObject.free();
90 }
91 Object *operator->() {
92 return &iObject;
93 }
94 Object *operator&() {
95 return &iObject;
96 }
97 private: // no copying or assigning
98 PdfObject(const PdfObject &);
99 void operator=(const PdfObject &);
100 public:
101 Object iObject;
102 };
103
104 // When copying the Resources of the selected page, all objects are copied
105 // recusively top-down. Indirect objects however are not fetched during
106 // copying, but get a new object number from pdfTeX and then will be
107 // appended into a linked list. Duplicates are checked and removed from the
108 // list of indirect objects during appending.
109
110 enum InObjType {
111 objFont,
112 objFontDesc,
113 objOther
114 };
115
116 struct InObj {
117 Ref ref; // ref in original PDF
118 InObjType type; // object type
119 InObj *next; // next entry in list of indirect objects
120 int num; // new object number in output PDF
121 fd_entry *fd; // pointer to /FontDescriptor object structure
122 int enc_objnum; // Encoding for objFont
123 int written; // has it been written to output PDF?
124 };
125
126 struct UsedEncoding {
127 int enc_objnum;
128 GfxFont *font;
129 UsedEncoding *next;
130 };
131
132 static InObj *inObjList;
133 static UsedEncoding *encodingList;
134 static GBool isInit = gFalse;
135
136 // --------------------------------------------------------------------
137 // Maintain list of open embedded PDF files
138 // --------------------------------------------------------------------
139
140 struct PdfDocument {
141 char *file_name;
142 PDFDoc *doc;
143 XRef *xref;
144 InObj *inObjList;
145 int occurences; // number of references to the document; the doc can be
146 // deleted when this is negative
147 PdfDocument *next;
148 };
149
150 static PdfDocument *pdfDocuments = 0;
151
152 static XRef *xref = 0;
153
154 // Returns pointer to PdfDocument record for PDF file.
155 // Creates a new record if it doesn't exist yet.
156 // xref is made current for the document.
157
158 static PdfDocument *find_add_document(char *file_name)
159 {
160 PdfDocument *p = pdfDocuments;
161 while (p && strcmp(p->file_name, file_name) != 0)
162 p = p->next;
163 if (p) {
164 xref = p->xref;
165 (p->occurences)++;
166 return p;
167 }
168 p = new PdfDocument;
169 p->file_name = xstrdup(file_name);
170 p->xref = xref = 0;
171 p->occurences = 0;
172 GString *docName = new GString(p->file_name);
173 p->doc = new PDFDoc(docName); // takes ownership of docName
174 if (!p->doc->isOk() || !p->doc->okToPrint()) {
175 pdftex_fail("xpdf: reading PDF image failed");
176 }
177 p->inObjList = 0;
178 p->next = pdfDocuments;
179 pdfDocuments = p;
180 return p;
181 }
182
183 // Deallocate a PdfDocument with all its resources
184
185 static void delete_document(PdfDocument * pdf_doc)
186 {
187 PdfDocument **p = &pdfDocuments;
188 while (*p && *p != pdf_doc)
189 p = &((*p)->next);
190 // should not happen:
191 if (!*p)
192 return;
193 // unlink from list
194 *p = pdf_doc->next;
195 // free pdf_doc's resources
196 InObj *r, *n;
197 for (r = pdf_doc->inObjList; r != 0; r = n) {
198 n = r->next;
199 delete r;
200 }
201 xref = pdf_doc->xref;
202 delete pdf_doc->doc;
203 xfree(pdf_doc->file_name);
204 delete pdf_doc;
205 }
206
207 // Replacement for
208 // Object *initDict(Dict *dict1){ initObj(objDict); dict = dict1; return this; }
209
210 static void initDictFromDict(PdfObject & obj, Dict * dict)
211 {
212 obj->initDict(xref);
213 for (int i = 0, l = dict->getLength(); i < l; i++) {
214 Object obj1;
215 obj->dictAdd(copyString(dict->getKey(i)), dict->getValNF(i, &obj1));
216 }
217 }
218
219 // --------------------------------------------------------------------
220
221 static int addEncoding(GfxFont * gfont)
222 {
223 UsedEncoding *n;
224 n = new UsedEncoding;
225 n->next = encodingList;
226 encodingList = n;
227 n->font = gfont;
228 n->enc_objnum = pdfnewobjnum();
229 return n->enc_objnum;
230 }
231
232 #define addFont(ref, fd, enc_objnum) \
233 addInObj(objFont, ref, fd, enc_objnum)
234
235 // addFontDesc is only used to avoid writing the original FontDescriptor
236 // from the PDF file.
237
238 #define addFontDesc(ref, fd) \
239 addInObj(objFontDesc, ref, fd, 0)
240
241 #define addOther(ref) \
242 addInObj(objOther, ref, 0, 0)
243
244 static int addInObj(InObjType type, Ref ref, fd_entry * fd, int e)
245 {
246 InObj *p, *q, *n = new InObj;
247 if (ref.num == 0)
248 pdftex_fail("PDF inclusion: invalid reference");
249 n->ref = ref;
250 n->type = type;
251 n->next = 0;
252 n->fd = fd;
253 n->enc_objnum = e;
254 n->written = 0;
255 if (inObjList == 0)
256 inObjList = n;
257 else {
258 for (p = inObjList; p != 0; p = p->next) {
259 if (p->ref.num == ref.num && p->ref.gen == ref.gen) {
260 delete n;
261 return p->num;
262 }
263 q = p;
264 }
265 // it is important to add new objects at the end of the list,
266 // because new objects are being added while the list is being
267 // written out.
268 q->next = n;
269 }
270 if (type == objFontDesc)
271 n->num = get_fd_objnum(fd);
272 else
273 n->num = pdfnewobjnum();
274 return n->num;
275 }
276
277 #if 0 /* unusewd */
278 static int getNewObjectNumber(Ref ref)
279 {
280 InObj *p;
281 if (inObjList == 0) {
282 pdftex_fail("No objects copied yet");
283 } else {
284 for (p = inObjList; p != 0; p = p->next) {
285 if (p->ref.num == ref.num && p->ref.gen == ref.gen) {
286 return p->num;
287 }
288 }
289 pdftex_fail("Object not yet copied: %i %i", ref.num, ref.gen);
290 }
291 #ifdef _MSC_VER
292 /* Never reached, but without __attribute__((noreturn)) for pdftex_fail()
293 MSVC 5.0 requires an int return value. */
294 return -60000;
295 #endif
296 }
297 #endif
298
299 static void copyObject(Object *);
300
301 static void copyName(char *s)
302 {
303 pdf_puts("/");
304 for (; *s != 0; s++) {
305 if (isdigit(*s) || isupper(*s) || islower(*s) || *s == '_' ||
306 *s == '.' || *s == '-' || *s == '+')
307 pdfout(*s);
308 else
309 pdf_printf("#%.2X", *s & 0xFF);
310 }
311 }
312
313 static void copyDictEntry(Object * obj, int i)
314 {
315 PdfObject obj1;
316 copyName(obj->dictGetKey(i));
317 pdf_puts(" ");
318 obj->dictGetValNF(i, &obj1);
319 copyObject(&obj1);
320 pdf_puts("\n");
321 }
322
323 static void copyDict(Object * obj)
324 {
325 int i, l;
326 if (!obj->isDict())
327 pdftex_fail("PDF inclusion: invalid dict type <%s>",
328 obj->getTypeName());
329 for (i = 0, l = obj->dictGetLength(); i < l; ++i)
330 copyDictEntry(obj, i);
331 }
332
333 static void copyFontDict(Object * obj, InObj * r)
334 {
335 int i, l;
336 char *key;
337 if (!obj->isDict())
338 pdftex_fail("PDF inclusion: invalid dict type <%s>",
339 obj->getTypeName());
340 pdf_puts("<<\n");
341 assert(r->type == objFont); // FontDescriptor is in fd_tree
342 for (i = 0, l = obj->dictGetLength(); i < l; ++i) {
343 key = obj->dictGetKey(i);
344 if (strncmp("FontDescriptor", key, strlen("FontDescriptor")) == 0
345 || strncmp("BaseFont", key, strlen("BaseFont")) == 0
346 || strncmp("Encoding", key, strlen("Encoding")) == 0)
347 continue; // skip original values
348 copyDictEntry(obj, i);
349 }
350 // write new FontDescriptor, BaseFont, and Encoding
351 pdf_printf("/FontDescriptor %d 0 R\n", get_fd_objnum(r->fd));
352 pdf_printf("/BaseFont %d 0 R\n", get_fn_objnum(r->fd));
353 pdf_printf("/Encoding %d 0 R\n", r->enc_objnum);
354 pdf_puts(">>");
355 }
356
357 static void copyStream(Stream * str)
358 {
359 int c, c2 = 0;
360 str->reset();
361 while ((c = str->getChar()) != EOF) {
362 pdfout(c);
363 c2 = c;
364 }
365 pdflastbyte = c2;
366 }
367
368 static void copyProcSet(Object * obj)
369 {
370 int i, l;
371 PdfObject procset;
372 if (!obj->isArray())
373 pdftex_fail("PDF inclusion: invalid ProcSet array type <%s>",
374 obj->getTypeName());
375 pdf_puts("/ProcSet [ ");
376 for (i = 0, l = obj->arrayGetLength(); i < l; ++i) {
377 obj->arrayGetNF(i, &procset);
378 if (!procset->isName())
379 pdftex_fail("PDF inclusion: invalid ProcSet entry type <%s>",
380 procset->getTypeName());
381 copyName(procset->getName());
382 pdf_puts(" ");
383 }
384 pdf_puts("]\n");
385 }
386
387 #define REPLACE_TYPE1C true
388
389 static void copyFont(char *tag, Object * fontRef)
390 {
391 PdfObject fontdict, subtype, basefont, fontdescRef, fontdesc, charset,
392 fontfile, ffsubtype, stemV;
393 GfxFont *gfont;
394 fd_entry *fd;
395 fm_entry *fontmap;
396 // Check whether the font has already been embedded before analysing it.
397 InObj *p;
398 Ref ref = fontRef->getRef();
399 for (p = inObjList; p; p = p->next) {
400 if (p->ref.num == ref.num && p->ref.gen == ref.gen) {
401 copyName(tag);
402 pdf_printf(" %d 0 R ", p->num);
403 return;
404 }
405 }
406 // Only handle included Type1 (and Type1C) fonts; anything else will be copied.
407 // Type1C fonts are replaced by Type1 fonts, if REPLACE_TYPE1C is true.
408 if (!fixedinclusioncopyfont && fontRef->fetch(xref, &fontdict)->isDict()
409 && fontdict->dictLookup("Subtype", &subtype)->isName()
410 && !strcmp(subtype->getName(), "Type1")
411 && fontdict->dictLookup("BaseFont", &basefont)->isName()
412 && fontdict->dictLookupNF("FontDescriptor", &fontdescRef)->isRef()
413 && fontdescRef->fetch(xref, &fontdesc)->isDict()
414 && (fontdesc->dictLookup("FontFile", &fontfile)->isStream()
415 || (REPLACE_TYPE1C
416 && fontdesc->dictLookup("FontFile3", &fontfile)->isStream()
417 && fontfile->streamGetDict()->lookup("Subtype",
418 &ffsubtype)->isName()
419 && !strcmp(ffsubtype->getName(), "Type1C")))
420 && (fontmap = lookup_fontmap(basefont->getName())) != NULL) {
421 // round /StemV value, since the PDF input is a float
422 // (see Font Descriptors in PDF reference), but we only store an
423 // integer, since we don't want to change the struct.
424 fontdesc->dictLookup("StemV", &stemV);
425 fd = epdf_create_fontdescriptor(fontmap, zround(stemV->getNum()));
426 if (fontdesc->dictLookup("CharSet", &charset) &&
427 charset->isString() && is_subsetable(fontmap))
428 epdf_mark_glyphs(fd, charset->getString()->getCString());
429 else
430 embed_whole_font(fd);
431 addFontDesc(fontdescRef->getRef(), fd);
432 copyName(tag);
433 gfont = GfxFont::makeFont(xref, tag, fontRef->getRef(),
434 fontdict->getDict());
435 pdf_printf(" %d 0 R ", addFont(fontRef->getRef(), fd,
436 addEncoding(gfont)));
437 } else {
438 copyName(tag);
439 pdf_puts(" ");
440 copyObject(fontRef);
441 }
442 }
443
444 static void copyFontResources(Object * obj)
445 {
446 PdfObject fontRef;
447 int i, l;
448 if (!obj->isDict())
449 pdftex_fail("PDF inclusion: invalid font resources dict type <%s>",
450 obj->getTypeName());
451 pdf_puts("/Font << ");
452 for (i = 0, l = obj->dictGetLength(); i < l; ++i) {
453 obj->dictGetValNF(i, &fontRef);
454 if (fontRef->isRef())
455 copyFont(obj->dictGetKey(i), &fontRef);
456 else if (fontRef->isDict()) { // some programs generate pdf with embedded font object
457 copyName(obj->dictGetKey(i));
458 pdf_puts(" ");
459 copyObject(&fontRef);
460 }
461 else
462 pdftex_fail("PDF inclusion: invalid font in reference type <%s>",
463 fontRef->getTypeName());
464 }
465 pdf_puts(">>\n");
466 }
467
468 static void copyOtherResources(Object * obj, char *key)
469 {
470 // copies all other resources (write_epdf handles Fonts and ProcSets),
471
472 // if Subtype is present, it must be a name
473 if (strcmp("Subtype", key) == 0) {
474 if (!obj->isName()) {
475 pdftex_warn("PDF inclusion: Subtype in Resources dict is not a name"
476 " (key '%s', type <%s>); ignored.",
477 key, obj->getTypeName());
478 return;
479 }
480 } else if (!obj->isDict()) {
481 //FIXME: Write the message only to the log file
482 pdftex_warn("PDF inclusion: invalid other resource which is no dict"
483 " (key '%s', type <%s>); ignored.",
484 key, obj->getTypeName());
485 return;
486 }
487 copyName(key);
488 pdf_puts(" ");
489 copyObject(obj);
490 }
491
492 // Function onverts double to string; very small and very large numbers
493 // are NOT converted to scientific notation.
494 // n must be a number or real conforming to the implementation limits
495 // of PDF as specified in appendix C.1 of the PDF Ref.
496 // These are:
497 // maximum value of ints is +2^32
498 // maximum value of reals is +2^15
499 // smalles values of reals is 1/(2^16)
500
501 static char *convertNumToPDF(double n)
502 {
503 static const int precision = 6;
504 static const int fact = (int) 1E6; // must be 10^precision
505 static const double epsilon = 0.5E-6; // 2epsilon must be 10^-precision
506 static char buf[64];
507 // handle very small values: return 0
508 if (fabs(n) < epsilon) {
509 buf[0] = '0';
510 buf[1] = '\0';
511 } else {
512 char ints[64];
513 int bindex = 0, sindex = 0;
514 int ival, fval;
515 // handle the sign part if n is negative
516 if (n < 0) {
517 buf[bindex++] = '-';
518 n = -n;
519 }
520 n += epsilon; // for rounding
521 // handle the integer part, simply with sprintf
522 ival = (int) floor(n);
523 n -= ival;
524 sprintf(ints, "%d", ival);
525 while (ints[sindex] != 0)
526 buf[bindex++] = ints[sindex++];
527 // handle the fractional part up to 'precision' digits
528 fval = (int) floor(n * fact);
529 if (fval) {
530 // set a dot
531 buf[bindex++] = '.';
532 sindex = bindex + precision;
533 buf[sindex--] = '\0';
534 // fill up trailing zeros with the string terminator NULL
535 while (((fval % 10) == 0) && (sindex >= bindex)) {
536 buf[sindex--] = '\0';
537 fval /= 10;
538 }
539 // fill up the fractional part back to front
540 while (sindex >= bindex) {
541 buf[sindex--] = (fval % 10) + '0';
542 fval /= 10;
543 }
544 } else
545 buf[bindex++] = 0;
546 }
547 return (char *) buf;
548 }
549
550 static void copyObject(Object * obj)
551 {
552 PdfObject obj1;
553 int i, l, c;
554 Ref ref;
555 char *p;
556 GString *s;
557 if (obj->isBool()) {
558 pdf_printf("%s", obj->getBool()? "true" : "false");
559 } else if (obj->isInt()) {
560 pdf_printf("%i", obj->getInt());
561 } else if (obj->isReal()) {
562 pdf_printf("%s", convertNumToPDF(obj->getReal()));
563 } else if (obj->isNum()) {
564 pdf_printf("%s", convertNumToPDF(obj->getNum()));
565 } else if (obj->isString()) {
566 s = obj->getString();
567 p = s->getCString();
568 l = s->getLength();
569 if (strlen(p) == (unsigned int) l) {
570 pdf_puts("(");
571 for (; *p != 0; p++) {
572 c = (unsigned char) *p;
573 if (c == '(' || c == ')' || c == '\\')
574 pdf_printf("\\%c", c);
575 else if (c < 0x20 || c > 0x7F)
576 pdf_printf("\\%03o", c);
577 else
578 pdfout(c);
579 }
580 pdf_puts(")");
581 } else {
582 pdf_puts("<");
583 for (i = 0; i < l; i++) {
584 c = s->getChar(i) & 0xFF;
585 pdf_printf("%.2x", c);
586 }
587 pdf_puts(">");
588 }
589 } else if (obj->isName()) {
590 copyName(obj->getName());
591 } else if (obj->isNull()) {
592 pdf_puts("null");
593 } else if (obj->isArray()) {
594 pdf_puts("[");
595 for (i = 0, l = obj->arrayGetLength(); i < l; ++i) {
596 obj->arrayGetNF(i, &obj1);
597 if (!obj1->isName())
598 pdf_puts(" ");
599 copyObject(&obj1);
600 }
601 pdf_puts("]");
602 } else if (obj->isDict()) {
603 pdf_puts("<<\n");
604 copyDict(obj);
605 pdf_puts(">>");
606 } else if (obj->isStream()) {
607 initDictFromDict(obj1, obj->streamGetDict());
608 pdf_puts("<<\n");
609 copyDict(&obj1);
610 pdf_puts(">>\n");
611 pdf_puts("stream\n");
612 copyStream(obj->getStream()->getUndecodedStream());
613 pdf_puts("\nendstream");
614 } else if (obj->isRef()) {
615 ref = obj->getRef();
616 if (ref.num == 0) {
617 pdftex_fail
618 ("PDF inclusion: reference to invalid object"
619 " (is the included pdf broken?)");
620 } else
621 pdf_printf("%d 0 R", addOther(ref));
622 } else {
623 pdftex_fail("PDF inclusion: type <%s> cannot be copied",
624 obj->getTypeName());
625 }
626 }
627
628 static void writeRefs()
629 {
630 InObj *r;
631 for (r = inObjList; r != 0; r = r->next) {
632 if (!r->written) {
633 Object obj1;
634 r->written = 1;
635 xref->fetch(r->ref.num, r->ref.gen, &obj1);
636 if (r->type == objFont) {
637 assert(!obj1.isStream());
638 pdfbeginobj(r->num, 2); // \pdfobjcompresslevel = 2 is for this
639 copyFontDict(&obj1, r);
640 pdf_puts("\n");
641 pdfendobj();
642 } else if (r->type != objFontDesc) { // /FontDescriptor is written via write_fontdescriptor()
643 if (obj1.isStream())
644 pdfbeginobj(r->num, 0);
645 else
646 pdfbeginobj(r->num, 2); // \pdfobjcompresslevel = 2 is for this
647 copyObject(&obj1);
648 pdf_puts("\n");
649 pdfendobj();
650 }
651 obj1.free();
652 }
653 }
654 }
655
656 static void writeEncodings()
657 {
658 UsedEncoding *r, *n;
659 char *glyphNames[256], *s;
660 int i;
661 for (r = encodingList; r != 0; r = r->next) {
662 for (i = 0; i < 256; i++) {
663 if (r->font->isCIDFont()) {
664 pdftex_fail
665 ("PDF inclusion: CID fonts are not supported"
666 " (try to disable font replacement to fix this)");
667 }
668 if ((s = ((Gfx8BitFont *) r->font)->getCharName(i)) != 0)
669 glyphNames[i] = s;
670 else
671 glyphNames[i] = notdef;
672 }
673 epdf_write_enc(glyphNames, r->enc_objnum);
674 }
675 for (r = encodingList; r != 0; r = n) {
676 n = r->next;
677 delete r->font;
678 delete r;
679 }
680 }
681
682 // get the pagebox according to the pagebox_spec
683 static PDFRectangle *get_pagebox(Page * page, int pagebox_spec)
684 {
685 if (pagebox_spec == pdfboxspecmedia)
686 return page->getMediaBox();
687 else if (pagebox_spec == pdfboxspeccrop)
688 return page->getCropBox();
689 else if (pagebox_spec == pdfboxspecbleed)
690 return page->getBleedBox();
691 else if (pagebox_spec == pdfboxspectrim)
692 return page->getTrimBox();
693 else if (pagebox_spec == pdfboxspecart)
694 return page->getArtBox();
695 else
696 pdftex_fail("PDF inclusion: unknown value of pagebox spec (%i)",
697 (int) pagebox_spec);
698 return page->getMediaBox(); // to make the compiler happy
699 }
700
701
702 // Reads various information about the PDF and sets it up for later inclusion.
703 // This will fail if the PDF version of the PDF is higher than
704 // minor_pdf_version_wanted or page_name is given and can not be found.
705 // It makes no sense to give page_name _and_ page_num.
706 // Returns the page number.
707
708 int
709 read_pdf_info(char *image_name, char *page_name, int page_num,
710 int pagebox_spec, int major_pdf_version_wanted, int minor_pdf_version_wanted,
711 int pdf_inclusion_errorlevel)
712 {
713 PdfDocument *pdf_doc;
714 Page *page;
715 PDFRectangle *pagebox;
716 float pdf_version_found, pdf_version_wanted;
717 // initialize
718 if (!isInit) {
719 globalParams = new GlobalParams();
720 globalParams->setErrQuiet(gFalse);
721 isInit = gTrue;
722 }
723 // open PDF file
724 pdf_doc = find_add_document(image_name);
725 epdf_doc = (void *) pdf_doc;
726
727 // check PDF version
728 // this works only for PDF 1.x -- but since any versions of PDF newer
729 // than 1.x will not be backwards compatible to PDF 1.x, pdfTeX will
730 // then have to changed drastically anyway.
731 pdf_version_found = pdf_doc->doc->getPDFVersion();
732 pdf_version_wanted = major_pdf_version_wanted + (minor_pdf_version_wanted * 0.1);
733 if (pdf_version_found > pdf_version_wanted + 0.01) {
734 char msg[] =
735 "PDF inclusion: found PDF version <%.1f>, but at most version <%.1f> allowed";
736 if (pdf_inclusion_errorlevel > 0) {
737 pdftex_fail(msg, pdf_version_found, pdf_version_wanted);
738 } else if (pdf_inclusion_errorlevel < 0) {
739 ; /* do nothing */
740 } else { /* = 0, give warning */
741 pdftex_warn(msg, pdf_version_found, pdf_version_wanted);
742 }
743 }
744 epdf_num_pages = pdf_doc->doc->getCatalog()->getNumPages();
745 if (page_name) {
746 // get page by name
747 GString name(page_name);
748 LinkDest *link = pdf_doc->doc->findDest(&name);
749 if (link == 0 || !link->isOk())
750 pdftex_fail("PDF inclusion: invalid destination <%s>", page_name);
751 Ref ref = link->getPageRef();
752 page_num = pdf_doc->doc->getCatalog()->findPage(ref.num, ref.gen);
753 if (page_num == 0)
754 pdftex_fail("PDF inclusion: destination is not a page <%s>",
755 page_name);
756 delete link;
757 } else {
758 // get page by number
759 if (page_num <= 0 || page_num > epdf_num_pages)
760 pdftex_fail("PDF inclusion: required page does not exist <%i>",
761 epdf_num_pages);
762 }
763 // get the required page
764 page = pdf_doc->doc->getCatalog()->getPage(page_num);
765
766 // get the pagebox (media, crop...) to use.
767 pagebox = get_pagebox(page, pagebox_spec);
768 if (pagebox->x2 > pagebox->x1) {
769 epdf_orig_x = pagebox->x1;
770 epdf_width = pagebox->x2 - pagebox->x1;
771 } else {
772 epdf_orig_x = pagebox->x2;
773 epdf_width = pagebox->x1 - pagebox->x2;
774 }
775 if (pagebox->y2 > pagebox->y1) {
776 epdf_orig_y = pagebox->y1;
777 epdf_height = pagebox->y2 - pagebox->y1;
778 } else {
779 epdf_orig_y = pagebox->y2;
780 epdf_height = pagebox->y1 - pagebox->y2;
781 }
782
783 // get page rotation
784 epdf_rotate = page->getRotate() % 360;
785 if (epdf_rotate < 0)
786 epdf_rotate += 360;
787
788 // page group
789 if (page->getGroup() != NULL)
790 epdf_has_page_group = 1; // only flag that page group is present;
791 // the actual object number will be
792 // generated in pdftex.web
793 else
794 epdf_has_page_group = 0; // no page group present
795
796 pdf_doc->xref = pdf_doc->doc->getXRef();
797 return page_num;
798 }
799
800 // writes the current epf_doc.
801 // Here the included PDF is copied, so most errors that can happen during PDF
802 // inclusion will arise here.
803
804 void write_epdf(void)
805 {
806 Page *page;
807 Ref *pageRef;
808 Dict *pageDict;
809 PdfObject contents, obj1, obj2, pageObj, dictObj;
810 PdfObject groupDict;
811 bool writeSepGroup = false;
812 Object info;
813 char *key;
814 char s[256];
815 int i, l;
816 int rotate;
817 double scale[6] = { 0, 0, 0, 0, 0, 0 };
818 bool writematrix = false;
819 int suppress_ptex_info = getpdfsuppressptexinfo();
820 static const char *pageDictKeys[] = {
821 "LastModified",
822 "Metadata",
823 "PieceInfo",
824 "SeparationInfo",
825 // "Group",
826 // "Resources",
827 NULL
828 };
829 const char *sep = getptexuseunderscore() ? "_" : ".";
830
831 PdfDocument *pdf_doc = (PdfDocument *) epdf_doc;
832 (pdf_doc->occurences)--;
833 xref = pdf_doc->xref;
834 inObjList = pdf_doc->inObjList;
835 encodingList = 0;
836 page = pdf_doc->doc->getCatalog()->getPage(epdf_selected_page);
837 pageRef = pdf_doc->doc->getCatalog()->getPageRef(epdf_selected_page);
838 xref->fetch(pageRef->num, pageRef->gen, &pageObj);
839 pageDict = pageObj->getDict();
840 rotate = page->getRotate();
841 PDFRectangle *pagebox;
842 // write the Page header
843 pdf_puts("/Type /XObject\n");
844 pdf_puts("/Subtype /Form\n");
845 pdf_puts("/FormType 1\n");
846
847 // write additional information
848 if ((suppress_ptex_info & MASK_SUPPRESS_PTEX_FILENAME) == 0) {
849 pdf_printf("/%s%sFileName (%s)\n", pdfkeyprefix, sep,
850 convertStringToPDFString(pdf_doc->file_name,
851 strlen(pdf_doc->file_name)));
852 }
853 if ((suppress_ptex_info & MASK_SUPPRESS_PTEX_PAGENUMBER) == 0) {
854 pdf_printf("/%s%sPageNumber %i\n", pdfkeyprefix, sep, (int) epdf_selected_page);
855 }
856 if ((suppress_ptex_info & MASK_SUPPRESS_PTEX_INFODICT) == 0) {
857 pdf_doc->doc->getDocInfoNF(&info);
858 if (info.isRef()) {
859 // the info dict must be indirect (PDF Ref p. 61)
860 pdf_printf("/%s%sInfoDict ", pdfkeyprefix, sep);
861 pdf_printf("%d 0 R\n", addOther(info.getRef()));
862 }
863 }
864 // get the pagebox (media, crop...) to use.
865 pagebox = get_pagebox(page, epdf_page_box);
866
867 // handle page rotation
868 if (rotate != 0) {
869 if (rotate % 90 == 0) {
870 // this handles only the simple case: multiple of 90s but these
871 // are the only values allowed according to the reference
872 // (v1.3, p. 78).
873 // the image is rotated around its center.
874 // the /Rotate key is clockwise while the matrix is
875 // counterclockwise :-%
876 tex_printf(", page is rotated %d degrees", rotate);
877 switch (rotate) {
878 case 90:
879 scale[1] = -1;
880 scale[2] = 1;
881 scale[4] = pagebox->x1 - pagebox->y1;
882 scale[5] = pagebox->y1 + pagebox->x2;
883 writematrix = true;
884 break;
885 case 180:
886 scale[0] = scale[3] = -1;
887 scale[4] = pagebox->x1 + pagebox->x2;
888 scale[5] = pagebox->y1 + pagebox->y2;
889 writematrix = true;
890 break; // width and height are exchanged
891 case 270:
892 scale[1] = 1;
893 scale[2] = -1;
894 scale[4] = pagebox->x1 + pagebox->y2;
895 scale[5] = pagebox->y1 - pagebox->x1;
896 writematrix = true;
897 break;
898 }
899 if (writematrix) { // The matrix is only written if the image is rotated.
900 sprintf(s, "/Matrix [%.8f %.8f %.8f %.8f %.8f %.8f]\n",
901 scale[0],
902 scale[1], scale[2], scale[3], scale[4], scale[5]);
903 pdf_puts(stripzeros(s));
904 }
905 }
906 }
907
908 sprintf(s, "/BBox [%.8f %.8f %.8f %.8f]\n",
909 pagebox->x1, pagebox->y1, pagebox->x2, pagebox->y2);
910 pdf_puts(stripzeros(s));
911
912 // Metadata validity check (as a stream it must be indirect)
913 pageDict->lookupNF("Metadata", &dictObj);
914 if (!dictObj->isNull() && !dictObj->isRef())
915 pdftex_warn("PDF inclusion: /Metadata must be indirect object");
916
917 // copy selected items in Page dictionary except Resources & Group
918 for (i = 0; pageDictKeys[i] != NULL; i++) {
919 pageDict->lookupNF(pageDictKeys[i], &dictObj);
920 if (!dictObj->isNull()) {
921 pdf_newline();
922 pdf_printf("/%s ", pageDictKeys[i]);
923 copyObject(&dictObj); // preserves indirection
924 }
925 }
926
927 // handle page group
928 pageDict->lookupNF("Group", &dictObj);
929 if (!dictObj->isNull()) {
930 if (pdfpagegroupval == 0) {
931 // another pdf with page group was included earlier on the
932 // same page; copy the Group entry as is. See manual for
933 // info on why this is a warning.
934 if (getpdfsuppresswarningpagegroup() == 0) {
935 pdftex_warn
936 ("PDF inclusion: multiple pdfs with page group included in a single page");
937 }
938 pdf_newline();
939 pdf_puts("/Group ");
940 copyObject(&dictObj);
941 } else {
942 // write Group dict as a separate object, since the Page dict also refers to it
943 pageDict->lookup("Group", &dictObj);
944 if (!dictObj->isDict())
945 pdftex_fail("PDF inclusion: /Group dict missing");
946 writeSepGroup = true;
947 initDictFromDict(groupDict, page->getGroup());
948 pdf_printf("/Group %ld 0 R\n", (long)pdfpagegroupval);
949 }
950 }
951
952 // write the Resources dictionary
953 if (page->getResourceDict() == NULL) {
954 // Resources can be missing (files without them have been spotted
955 // in the wild); in which case the /Resouces of the /Page will be used.
956 // "This practice is not recommended".
957 pdftex_warn
958 ("PDF inclusion: /Resources missing. 'This practice is not recommended' (PDF Ref)");
959 } else {
960 initDictFromDict(obj1, page->getResourceDict());
961 if (!obj1->isDict())
962 pdftex_fail("PDF inclusion: invalid resources dict type <%s>",
963 obj1->getTypeName());
964 pdf_newline();
965 pdf_puts("/Resources <<\n");
966 for (i = 0, l = obj1->dictGetLength(); i < l; ++i) {
967 obj1->dictGetVal(i, &obj2);
968 key = obj1->dictGetKey(i);
969 if (strcmp("Font", key) == 0)
970 copyFontResources(&obj2);
971 else if (strcmp("ProcSet", key) == 0)
972 copyProcSet(&obj2);
973 else
974 copyOtherResources(&obj2, key);
975 }
976 pdf_puts(">>\n");
977 }
978
979 // write the page contents
980 page->getContents(&contents);
981 if (contents->isStream()) {
982
983 // Variant A: get stream and recompress under control
984 // of \pdfcompresslevel
985 //
986 // pdfbeginstream();
987 // copyStream(contents->getStream());
988 // pdfendstream();
989
990 // Variant B: copy stream without recompressing
991 //
992 contents->streamGetDict()->lookup("F", &obj1);
993 if (!obj1->isNull()) {
994 pdftex_fail("PDF inclusion: Unsupported external stream");
995 }
996 contents->streamGetDict()->lookup("Length", &obj1);
997 assert(!obj1->isNull());
998 pdf_puts("/Length ");
999 copyObject(&obj1);
1000 pdf_puts("\n");
1001 contents->streamGetDict()->lookup("Filter", &obj1);
1002 if (!obj1->isNull()) {
1003 pdf_puts("/Filter ");
1004 copyObject(&obj1);
1005 pdf_puts("\n");
1006 contents->streamGetDict()->lookup("DecodeParms", &obj1);
1007 if (!obj1->isNull()) {
1008 pdf_puts("/DecodeParms ");
1009 copyObject(&obj1);
1010 pdf_puts("\n");
1011 }
1012 }
1013 pdf_puts(">>\nstream\n");
1014 copyStream(contents->getStream()->getUndecodedStream());
1015 pdfendstream();
1016 } else if (contents->isArray()) {
1017 pdfbeginstream();
1018 for (i = 0, l = contents->arrayGetLength(); i < l; ++i) {
1019 Object contentsobj;
1020 copyStream((contents->arrayGet(i, &contentsobj))->getStream());
1021 contentsobj.free();
1022 if (i < l - 1)
1023 pdf_newline(); // add a newline after each stream except the last
1024 }
1025 pdfendstream();
1026 } else { // the contents are optional, but we need to include an empty stream
1027 pdfbeginstream();
1028 pdfendstream();
1029 }
1030
1031 // write out all used encodings (and delete list)
1032 writeEncodings();
1033
1034 // write the Group dict if needed
1035 if (writeSepGroup) {
1036 pdfbeginobj(pdfpagegroupval, 2);
1037 copyObject(&groupDict);
1038 pdf_puts("\n");
1039 pdfendobj();
1040 pdfpagegroupval = 0; // only the 1st included pdf on a page gets its
1041 // Group included in the Page dict
1042 }
1043
1044 // write out all indirect objects
1045 writeRefs();
1046
1047 // save object list, xref
1048 pdf_doc->inObjList = inObjList;
1049 pdf_doc->xref = xref;
1050 }
1051
1052 // Called when an image has been written and it's resources in image_tab are
1053 // freed and it's not referenced anymore.
1054
1055 void epdf_delete()
1056 {
1057 PdfDocument *pdf_doc = (PdfDocument *) epdf_doc;
1058 xref = pdf_doc->xref;
1059 if (pdf_doc->occurences < 0) {
1060 delete_document(pdf_doc);
1061 }
1062 }
1063
1064 // Called when PDF embedding system is finalized.
1065 // Now deallocate all remaining PdfDocuments.
1066
1067 void epdf_check_mem()
1068 {
1069 if (isInit) {
1070 PdfDocument *p, *n;
1071 for (p = pdfDocuments; p; p = n) {
1072 n = p->next;
1073 delete_document(p);
1074 }
1075 // see above for globalParams
1076 delete globalParams;
1077 }
1078 }