home *** CD-ROM | disk | FTP | other *** search
/ jppd.dyndns.org / jppd.dyndns.org.tar / jppd.dyndns.org / QUERYPRO / Impressora_PDF / converter.exe / GPLGS / pdf_main.ps < prev    next >
Text File  |  2004-09-01  |  35KB  |  1,064 lines

  1. %    Copyright (C) 1994, 2000 Aladdin Enterprises.  All rights reserved.
  2. % This software is provided AS-IS with no warranty, either express or
  3. % implied.
  4. % This software is distributed under license and may not be copied,
  5. % modified or distributed except as expressly authorized under the terms
  6. % of the license contained in the file LICENSE in this distribution.
  7. % For more information about licensing, please refer to
  8. % http://www.ghostscript.com/licensing/. For information on
  9. % commercial licensing, go to http://www.artifex.com/licensing/ or
  10. % contact Artifex Software, Inc., 101 Lucas Valley Road #110,
  11. % San Rafael, CA  94903, U.S.A., +1(415)492-9861.
  12.  
  13. % $Id: pdf_main.ps,v 1.71.2.5 2004/08/31 18:18:51 ray Exp $
  14. % pdf_main.ps
  15. % PDF file- and page-level operations.
  16.  
  17. /.setlanguagelevel where { pop 2 .setlanguagelevel } if
  18. .currentglobal true .setglobal
  19. /pdfdict where { pop } { /pdfdict 100 dict def } ifelse
  20. pdfdict begin
  21.  
  22. % Patch in an obsolete variable used by some third-party software.
  23. /#? false def
  24.  
  25. % Test whether the current output device handles pdfmark.
  26. /.writepdfmarkdict 1 dict dup /pdfmark null put readonly def
  27. /.writepdfmarks {    % - .writepdfmarks <bool>
  28.   currentdevice //.writepdfmarkdict .getdeviceparams
  29.   mark eq { false } { pop pop true } ifelse
  30.   systemdict /DOPDFMARKS known or 
  31. } bind def
  32.  
  33. % For simplicity, we use a single interpretation dictionary for all
  34. % PDF graphics execution, even though this is too liberal.
  35. /pdfopdict mark
  36.   objopdict { } forall
  37.   drawopdict { } forall
  38.   /endstream { exit } bind
  39.   (%%EOF) cvn { exit } bind        % for filters
  40.     % PDF 1.1 operators
  41.   /BX { /BXlevel BXlevel 1 add store } bind
  42.   /EX { /BXlevel BXlevel 1 sub store } bind
  43.   /PS { cvx exec } bind
  44.     % PDF 1.2 operators
  45.   /BMC { pop } bind
  46.   /BDC { pop pop } bind
  47.   /EMC { }
  48.   /MP { pop } bind
  49.   /DP { pop pop } bind
  50. .dicttomark readonly def
  51.  
  52. % ======================== Main program ======================== %
  53.  
  54. end            % pdfdict
  55. userdict begin
  56.  
  57. /defaultfontname /Times-Roman def
  58.  
  59. % Make sure the registered encodings are loaded, so we don't run the risk
  60. % that some of the indices for their names will overflow the packed
  61. % representation.  (Yes, this is a hack.)
  62. SymbolEncoding pop
  63. DingbatsEncoding pop
  64.  
  65. % Redefine 'run' so it recognizes PDF files.
  66. systemdict begin
  67. /.runps /run load def
  68. /run {
  69.   dup type /filetype ne { (r) file } if
  70.   dup ( ) .peekstring {
  71.     (%) eq {
  72.       dup (     ) .peekstring {
  73.     (%PDF-) eq {
  74.         dup (%stdin) (r) file eq {
  75.           % Copy PDF from stdin to temporary file then run it.
  76.           null (w+) //systemdict /.tempfile get exec exch 3 1 roll
  77.           % stack: tempname stdin tempfile
  78.           64000 string
  79.           {
  80.         % stack: tempname stdin tempfile string
  81.         2 index 1 index readstring
  82.         exch 3 index exch writestring
  83.         not { exit } if
  84.           }
  85.           loop
  86.           pop exch closefile
  87.           % stack: tempname tempfile
  88.           dup 0 setfileposition
  89.           dup runpdf
  90.           closefile deletefile
  91.         } {
  92.           runpdf
  93.         } ifelse
  94.       } {
  95.         cvx .runps % doesn't start with %PDF-
  96.       } ifelse
  97.     } {
  98.       pop cvx .runps % didn't read 5 characters
  99.     } ifelse
  100.     } {
  101.       cvx .runps % didn't start with %
  102.     } ifelse
  103.   } {
  104.     pop closefile % file was empty
  105.   } ifelse
  106. } bind odef
  107. currentdict /runpdfstring .undef
  108.  
  109.  
  110. /runpdfbegin {        % <file> runpdf -
  111.    userdict begin
  112.     % It turns out that the PDF interpreter uses memory more
  113.     % effectively if it is run under at least one level of save.
  114.     % This is counter-intuitive, and we don't understand why it happens,
  115.     % but the improvement is significant.
  116.    /PDFTopSave save def
  117.    0 setobjectformat
  118.    /Page# null def
  119.    /Page null def
  120.    /DSCPageCount 0 def
  121.    /PDFSave null def
  122.    GS_PDF_ProcSet begin
  123.    pdfdict begin
  124.    pdfopen begin
  125.    Trailer /Root oget /Pages oget /CropBox knownoget
  126.     { oforce_array mark /CropBox 3 -1 roll /PAGES pdfmark
  127.     }
  128.    if
  129.    /FirstPage where 
  130.     { pop FirstPage dup pdfpagecount gt
  131.       { (\nRequested FirstPage is greater than the number of pages in the file: ) print
  132.         pdfpagecount = flush
  133.       } if
  134.     } {
  135.       1
  136.     } ifelse
  137.    /LastPage where { pop LastPage pdfpagecount .min } { pdfpagecount } ifelse
  138.    1 index 1 index gt
  139.     { (   No pages will be processed \(FirstPage > LastPage\).) = flush }
  140.     { QUIET not
  141.       { (Processing pages ) print 1 index =only ( through ) print dup =only
  142.         (.) = flush
  143.       }
  144.      if
  145.     }
  146.    ifelse
  147. } bind def
  148.  
  149. /dopdfpages {   % firstpage# lastpage# dopdfpages -
  150.   << /PDFScanRules true >> setuserparams    % set scanning rules for PDF vs. PS
  151.   1 exch
  152.     { dup /Page# exch store
  153.       QUIET not { (Page ) print dup == flush } if
  154.       pdfgetpage pdfshowpage
  155.     } for
  156.   << /PDFScanRules null >> setuserparams    % restore scanning rules for PS
  157. } bind def
  158.  
  159. /runpdfend {
  160.    Repaired { printrepaired } if
  161.    currentdict pdfclose
  162.    end            % temporary dict
  163.    end            % pdfdict
  164.    end            % GS_PDF_ProcSet
  165.    PDFTopSave restore
  166.    end            % userdict
  167. } bind def
  168.  
  169. /runpdf {        % <file> runpdf -
  170.   runpdfbegin
  171.   dopdfpages
  172.   runpdfend
  173. } bind def
  174.  
  175. end            % systemdict
  176. % Redefine the procedure that the C code uses for running piped input.
  177. % It is OK to use { (%stdin) run } here, because a startjob cannot occur.
  178. /.runstdin {
  179.   { (%stdin) run } execute0
  180. } bind def
  181.  
  182. end            % userdict
  183. pdfdict begin
  184.  
  185. % ======================== File parsing ======================== %
  186.  
  187. % Read the cross-reference and trailer sections.
  188.  
  189. /traileropdict mark
  190.   (<<) cvn { mark } bind
  191.   (>>) cvn { { .dicttomark } stopped {
  192.           (   **** File has unbalanced >> in trailer.\n) pdfformaterror
  193.              } if } bind
  194.   ([) cvn { mark } bind        % ditto
  195.   (]) cvn dup load
  196. %  /true true        % see .pdfexectoken in pdf_base.ps
  197. %  /false false        % ibid.
  198. %  /null null        % ibid.
  199.   /R { /resolveR cvx 3 packedarray cvx } bind    % see Objects below
  200.   /startxref /exit load
  201. .dicttomark readonly def
  202.  
  203. % Because of EOL conversion, lines with fixed contents might be followed
  204. % by one or more blanks.
  205. /lineeq            % <filestr> <conststr> lineeq <bool>
  206.  { anchorsearch
  207.     { pop { ( ) anchorsearch not { () eq exit } if pop } loop }
  208.     { pop false }
  209.    ifelse
  210.  } bind def
  211. /linene { lineeq not } bind def
  212.  
  213. % Read the cross-reference table.
  214. /readxref        % <pos> readxref <trailerdict>
  215.  {
  216.    PDFoffset add PDFfile exch setfileposition
  217.         % In some PDF files, this position actually points to
  218.         % white space before the xref line.  Skip over this here.
  219.    { PDFfile fileposition PDFfile read pop 32 gt { exit } if pop
  220.    } loop
  221.    PDFfile exch setfileposition
  222.    0        % Initialize xref table error counter
  223.  
  224.         % The PDF specification says that the 'xref' must be on a line
  225.         % by itself. The code here formerly used readline and linene to
  226.         % check this. However, Acrobat Reader only requires the line to
  227.         % begin with 'xref', and there are enough applications producing
  228.         % non-compliant PDF files that we have to do this too.
  229.    PDFfile pdfstring 0 4 getinterval readstring pop
  230.    (xref) ne { /readxref cvx /syntaxerror signalerror } if
  231.         % Store the xref table entry position for each object.
  232.    { PDFfile token pop        % first object # or trailer
  233.      dup /trailer eq { pop exit } if
  234.      PDFfile pdfstring readline pop
  235.      token pop            % entry count
  236.      exch pop            % remove last
  237.         % This section might be adding new objects:
  238.         % ensure that Objects and Generations are big enough.
  239.         % stack: <err count> <first obj> <entry count>
  240.      2 copy add growPDFobjects
  241.      PDFfile fileposition
  242.      3 1 roll            % stack: <err count> <filepos> <first obj> <entry count>
  243.      {                % stack: <err count> <file pos> <obj num>
  244.         % Read xref line
  245.        PDFfile pdfstring readline pop  
  246.        token pop        % object position
  247.        exch token pop        % generation #
  248.        exch token pop        % n or f
  249.        exch pop            % Stack: <err count> <file pos> <obj#> <loc> <gen#> <tag>
  250.        dup /n eq {        % xref line tag is /n
  251.      pop            % pop dup of line tag
  252.          Objects 3 index lget null eq {    % later update might have set it
  253.        setxrefentry
  254.          } if
  255.        }
  256.        {            % xref line tag was not /n
  257.      /f ne            % verify that the tag was /f
  258.          { /setxrefentry cvx /syntaxerror signalerror
  259.      } if
  260.        } ifelse
  261.        pop pop            % pop <obj location> and <gen num>
  262.         % Check if line length is 20 chars (Adobe spec.)
  263.        exch            % stack: <err count> <obj num> <file pos>
  264.        PDFfile fileposition    % <err count> <obj#> <old pos> <new pos>
  265.        dup 4 1 roll        % <err count> <new Pos> <obj#> <old pos> <new pos>
  266.        exch sub 20 ne        % <err count> <new Pos> <obj#> <bool>
  267.        { 3 -1 roll 1 add 3 1 roll % Increment error count
  268.        } if
  269.        1 add            % increment object number
  270.      } repeat
  271.      pop pop            % pop <file pos> <obj #>
  272.    } loop
  273.    0 ne {
  274.      (   **** Warning:  length of some xref entries is not equal to 20 bytes.\n)
  275.      pdfformaterror
  276.    } if
  277.    PDFfile traileropdict .pdfrun
  278.  } bind def
  279.  
  280. % Open a PDF file and read the header, trailer, and cross-reference.
  281. /pdfopen {        % <file> pdfopen <dict>
  282.     % Color space substitution in PDF is handled somewhat differently
  283.     % than in PostScript. A given device color space will be substituted
  284.     % if the corresponding "Default..." entry exists in the Page's
  285.     % Resource dictionary (which might be inhereted); there is no
  286.     % UseCIEColor to enable/disable color mapping.
  287.     %
  288.     % This behavior is achieved by always setting UseCIEColor to true
  289.     % in the page device dictionary. If the value of this parameter was
  290.     % originally false (i.e.: the output device does not perform color
  291.     % space substitution by default), the instances DefaultGray,
  292.     % DefaultRGB, and DefaultCMYK of the (local) ColorSpace category
  293.     % are redefined to be DeviceGray, DeviceRGB, and DeviceCMYK,
  294.     % respectively. This is not done if UseCIEColor is true by default,
  295.     % as in that case color substitution is presumably desired even
  296.     % if the file does not request it.
  297.    currentpagedevice /UseCIEColor .knownget dup { pop } if not
  298.     { .currentglobal false .setglobal
  299.       /DefaultGray { /DeviceGray } cvlit /ColorSpace defineresource pop
  300.       /DefaultRGB { /DeviceRGB } cvlit /ColorSpace defineresource pop
  301.       /DefaultCMYK { /DeviceCMYK } cvlit /ColorSpace defineresource pop
  302.       .setglobal
  303.     }
  304.    if
  305.   pdfopenfile begin
  306.   pdfopencache
  307.   .writepdfmarks {
  308.     % Copy bookmarks (outline) to the output.
  309.     Trailer /Root oget /Outlines knownoget {
  310.       /First knownoget {
  311.     { dup writeoutline /Next knownoget not { exit } if } loop
  312.       } if
  313.     } if
  314.   } if        % end .writepdfmarks
  315.   currentdict end
  316. } bind def
  317.  
  318. /pdfopencache {        % - pdfopencache -
  319.     % Create and initialize some caches.
  320.   /PageCount pdfpagecount def
  321.   /PageNumbers PageCount 65534 .min dict def
  322.   /PageIndex PageCount 65534 .min array def
  323. } bind def
  324.  
  325. /pdfopenfile {        % <file> pdfopenfile <dict>
  326.    pdfdict readonly pop        % can't do it any earlier than this
  327.    15 dict begin
  328.    /LocalResources 0 dict def
  329.    /DefaultQstate //null def    % establish binding
  330.    /Printed where { pop } {
  331.         % Guess whether the output device is a printer.
  332.      /Printed currentpagedevice /OutputFile known def
  333.    } ifelse
  334.    /PSLevel1 where { pop } { /PSLevel1 false def } ifelse
  335.    % NB: PDFfile is used outside of the PDF code to determine that a
  336.    % PDF job is being processed; to not change or hide this key.
  337.    cvlit /PDFfile exch def
  338.    /PDFsource PDFfile def
  339.    /Repaired false def
  340.    PDFfile dup 0 setfileposition pdfstring readstring 
  341.    not {/pdfopen cvx /syntaxerror signalerror} if
  342.    (%PDF-) search not {/pdfopen cvx /syntaxerror signalerror} if
  343.    length /PDFoffset exch def pop cvr /PDFversion exch def
  344.     % Read the last cross-reference table.
  345.    count /pdfemptycount exch def
  346.    /Trailer << >> def        % Initialize to an emptry dict.
  347.    { initPDFobjects findxref readxref } .internalstopped {
  348.         % Read failed.  Attempt to recover xref data.
  349.      print_xref_warning 
  350.      count pdfemptycount sub { pop } repeat % remove anything left by readxref
  351.      search_objects
  352.      search_trailer
  353.    } { /Trailer exch def
  354.     % Read any previous cross-reference tables.
  355.      Trailer
  356.      { /Prev knownoget not { exit } if
  357.        { readxref } .internalstopped {
  358.          % Read failed.  Attempt to recover xref data.
  359.          print_xref_warning
  360.          count pdfemptycount sub { pop } repeat    % remove anything left by readxref
  361.      search_objects
  362.          search_trailer
  363.      exit
  364.        } if
  365.        % The PDF spec. says that each trailer dict should contain the required
  366.        % entries.  However we have seen a PDF file that only has a Prev entry in
  367.        % the initial trailer dict.  Acrobat complains but it accepts these files.
  368.        % To work with these files, we are copying any entries which we find in
  369.        % a previous trailer dict which are not present in the initial dict.
  370.        dup {
  371.          Trailer 2 index known {
  372.            pop pop              % discard if key already present
  373.          } {
  374.            Trailer 3 1 roll put % add key if not present
  375.          } ifelse
  376.        } forall
  377.      } loop
  378.    } ifelse
  379.    Trailer /Encrypt knownoget {
  380.      pop
  381.      pdf_process_Encrypt    % signal error
  382.    } if
  383.    currentdict end
  384.  } bind def
  385.  
  386. % Skip backward over the %%EOF at the end of the PDF file, and read
  387. % the preceding startxref line.  The PDF specification unambiguously
  388. % requires that the %%EOF appear on a line by itself, and that the
  389. % startxref and the following position value appear on separate lines;
  390. % however, some applications (including, apparently, Acrobat Distiller
  391. % on the Macintosh) may add up to 2K of garbage after the %%EOF, and some
  392. % other applications also truncate the %%EOF to %%EO, and/or put the
  393. % startxref and the following value on the same line.
  394. % A file reported from Distiller 3.02b for AIX 4.1.1 has 2076 bytes
  395. % of garbage. The tolerance is increased to 4K to cover future
  396. % applications and bigger allocation units.
  397. /findxref {        % - findxref <xrefpos>
  398.   PDFfile dup dup 0 setfileposition bytesavailable
  399.   dup /PDFfilelen exch def
  400.     % Find the last %%EOF string (within 4096 bytes)
  401.   4096 sub PDFoffset .max
  402.   2 copy setfileposition
  403.   PDFfilelen exch sub string 1 index exch readstring pop {
  404.     (\015%%EO) search {        % Adobe can handle truncated key string
  405.       pop pop            % if found, keep searching 'post' string
  406.     } {
  407.       (\012%%EO) search
  408.     { pop pop } { exit } ifelse    % exit if neither string found
  409.     } ifelse
  410.   } loop
  411.   PDFfilelen exch length sub 4 sub PDFoffset .max exch 1 index setfileposition
  412.     % Stack: eofpos
  413.     % Check for whether this is, in fact, a valid PDF file.
  414.   dup PDFfilelen exch sub dup dup 7 gt exch 5 lt or {
  415.     pop true
  416.   } {
  417.     string PDFfile exch readstring pop
  418.     dup (%%EOF\n) eq exch dup (%%EOF\r) eq
  419.     exch dup (%%EOF\r\n) eq exch (%%EOF) eq or or or not
  420.   } ifelse {
  421.     (   **** Warning: File has a corrupted %%EOF marker, or garbage after %%EOF.\n)
  422.     pdfformaterror
  423.   } if
  424.   PDFfile exch setfileposition
  425.     % Now read the startxref and xref start position.
  426.   prevline token not { null } if dup type /integertype eq {
  427.     exch pop cvi        % xref start position
  428.     exch PDFfile exch setfileposition
  429.     prevline dup (startxref) linene {
  430.       % startxref not on a line by itself.  We have found PDF from
  431.       % www.verypdf.com in which the startxref was on the same line as
  432.       % the end of trailer dictionary.  Check for this.  Note:  This
  433.       % violates the spec.
  434.       dup (startxref) search {
  435.     % found startxref - print warning
  436.     pop pop pop             % clear strings from search
  437.         (   **** Warning: format of the startxref line in this file is invalid.\n)
  438.         pdfformaterror
  439.       } {                % no startxref - we have a problem.
  440.         /findxref cvx /syntaxerror signalerror
  441.       } ifelse
  442.     } if
  443.     pop pop
  444.   } {    % else, this file has 'startxref #####' format
  445.     (startxref) ne { /findxref cvx /syntaxerror signalerror } if
  446.     cvi        % xref start position
  447.     (   **** Warning: format of the startxref line in this file is invalid.\n)
  448.     pdfformaterror
  449.     exch PDFfile exch setfileposition
  450.   } ifelse
  451. } bind def
  452. /stderrfile (%stderr) (w) file def
  453. /stderrprint {                % <string> stderrprint -
  454.   //stderrfile dup 3 -1 roll writestring flushfile
  455. } bind def
  456. /pdfformaterror {    % <string> pdfformaterror -
  457.   stderrprint
  458.   /Repaired true store
  459. } bind def
  460.  
  461. /knownoget_safe
  462. { knownoget
  463. } odef
  464.  
  465. /printProducer {
  466.   Trailer /Info { knownoget_safe } stopped { false } if {
  467.     /Producer knownoget not { null } if
  468.   } {
  469.     null
  470.   } ifelse
  471.   dup null eq {
  472.     pop
  473.   } {
  474.     (   **** The file was produced by: \n   **** >>>> ) stderrprint
  475.     % Handle a Unicode Producer.
  476.     (\376\377) anchorsearch {
  477.       pop dup length 2 idiv string 0 1 2 index length 1 sub {
  478.         % Stack: origstr newstr i
  479.     1 index exch 3 index 1 index 2 mul 1 add get put
  480.       } for exch pop
  481.     } if
  482.     stderrprint
  483.     ( <<<<\n) stderrprint
  484.   } ifelse
  485. } bind def
  486. /printrepaired {
  487.    (\n   **** This file had errors that were repaired or ignored.\n)
  488.   stderrprint
  489.   printProducer
  490.   (   **** Please notify the author of the software that produced this\n)
  491.   stderrprint
  492.   (   **** file that it does not conform to Adobe's published PDF\n)
  493.   stderrprint
  494.   (   **** specification.\n\n)
  495.   stderrprint
  496. } bind def
  497.  
  498. % Write the outline structure for a file.  Uses linkdest (below).
  499. /writeoutline        % <outlinedict> writeoutline -
  500.  { mark
  501.    0 2 index /First knownoget
  502.     { { exch 1 add exch /Next knownoget not { exit } if } loop }
  503.    if
  504.         % stack: dict mark count
  505.    dup 0 eq
  506.     { pop 1 index
  507.     }
  508.     { 2 index /Count knownoget { 0 lt { neg } if } if
  509.       /Count exch 3 index
  510.     }
  511.    ifelse linkdest /Title oget /Title exch /OUT pdfmark
  512.    /First knownoget
  513.     { { dup writeoutline /Next knownoget not { exit } if } loop }
  514.    if
  515.  } bind def
  516.  
  517. % Close a PDF file.
  518. /pdfclose        % <dict> pdfclose -
  519.  { begin
  520.    PDFfile closefile
  521.    end
  522.  } bind def
  523.  
  524. % ======================== Page accessing ======================== %
  525.  
  526. % Get a (possibly inherited) attribute of a page.
  527. /pget            % <pagedict> <key> pget <value> -true-
  528.             % <pagedict> <key> pget -false-
  529.  { 2 copy knownoget
  530.     { exch pop exch pop true
  531.     }
  532.     { exch /Parent knownoget
  533.        { exch pget }
  534.        { pop false }
  535.       ifelse
  536.     }
  537.    ifelse
  538.  } bind def
  539.  
  540. % Get the value of a resource on a given page.
  541. /rget {            % <resname> <pagedict> <restype> rget <value> -true-
  542.             % <resname> <pagedict> <restype> rget -false-
  543.   LocalResources 1 index knownoget {
  544.      3 index knownoget
  545.   } {
  546.     false
  547.   } ifelse {
  548.     exch pop exch pop exch pop true
  549.   } {
  550.     exch /Resources pget {
  551.       exch knownoget { exch knownoget } { pop false } ifelse
  552.     } {
  553.       pop pop false
  554.     } ifelse
  555.   } ifelse
  556. } bind def
  557.  
  558. % Get the total number of pages in the document.
  559. /pdfpagecount        % - pdfpagecount <int>
  560.  { Trailer /Root oget /Pages oget /Count oget
  561.  } bind def
  562.  
  563. % Find the N'th page of the document by iterating through the Pages tree.
  564. % The first page is numbered 1.
  565. /pdffindpageref {        % <int> pdffindpage <objref>
  566.   dup Trailer /Root oget /Pages get
  567.     {        % We should be able to tell when we reach a leaf
  568.         % by finding a Type unequal to /Pages.  Unfortunately,
  569.         % some files distributed by Adobe lack the Type key
  570.         % in some of the Pages nodes!  Instead, we check for Kids.
  571.       dup oforce /Kids knownoget not { exit } if
  572.       exch pop null
  573.       0 1 3 index length 1 sub {
  574.          2 index exch get
  575.      dup oforce dup /Kids known { /Count oget } { pop 1 } ifelse
  576.         % Stack: index kids null noderef count
  577.      dup 5 index ge { pop exch pop exit } if
  578.      5 -1 roll exch sub 4 1 roll pop
  579.       } for exch pop
  580.         % Stack: index null|noderef
  581.       dup null eq { pop pop 1 null exit } if
  582.     } loop
  583.         % Stack: index countleft noderef
  584.    1 index 1 ne { pop pop /pdffindpage cvx /rangecheck signalerror } if
  585.    exch pop
  586.    PageIndex 2 index 1 sub 65533 .min 2 index oforce put
  587.    PageNumbers 1 index oforce 3 index dup 65534 le
  588.     { put }
  589.     { pop pop pop }    % don't store more than 65534 pagenumbers
  590.    ifelse
  591.    exch pop
  592. } bind def
  593. /pdffindpage {        % <int> pdffindpage <pagedict>
  594.   pdffindpageref oforce
  595. } bind def
  596.  
  597. % Find the N'th page of the document.
  598. % The first page is numbered 1.
  599. /pdfgetpage        % <int> pdfgetpage <pagedict>
  600.  { PageIndex 1 index 1 sub dup 65533 lt
  601.     { get }
  602.     { pop pop null }
  603.    ifelse
  604.    dup null ne
  605.     { exch pop oforce }
  606.     { pop pdffindpage }
  607.    ifelse
  608.  } bind def
  609.  
  610. % Find the page number of a page object (inverse of pdfgetpage).
  611. /pdfpagenumber        % <pagedict> pdfpagenumber <int>
  612.  {    % We use the simplest and stupidest of all possible algorithms....
  613.    PageNumbers 1 index .knownget
  614.     { exch pop
  615.     }
  616.     { 1 1 PageCount 1 add    % will give a rangecheck if not found
  617.        { dup pdfgetpage oforce 2 index eq { exit } if pop
  618.        }
  619.       for exch pop
  620.     }
  621.    ifelse
  622.  } bind def
  623.  
  624. % Display a given page.
  625. /boxrect        % <llx> <lly> <urx> <ury> boxrect <x> <y> <w> <h>
  626.  { exch 3 index sub exch 2 index sub
  627.  } bind def
  628. /resolvedest {        % <name|string|other> resolvedest <other|null>
  629.   dup type /nametype eq {
  630.     Trailer /Root oget /Dests knownoget {
  631.       exch knownoget not { null } if
  632.     } {
  633.       pop null
  634.     } ifelse
  635.   } {
  636.     dup type /stringtype eq {
  637.       Trailer /Root oget /Names knownoget {
  638.     /Dests knownoget {
  639.       exch nameoget
  640.     } {
  641.       pop null
  642.     } ifelse
  643.       } {
  644.     pop null
  645.       } ifelse
  646.     } if
  647.   } ifelse
  648. } bind def
  649. /linkdest {        % <link|outline> linkdest
  650.             %   ([/Page <n>] /View <view> | ) <link|outline>
  651.   dup /Dest knownoget
  652.     { resolvedest
  653.       dup type /dicttype eq { /D knownoget not { null } if } if
  654.       dup null eq
  655.        { pop }
  656.        { dup 0 oget
  657.          dup type /dicttype eq {
  658.            dup /Type knownoget {
  659.              /Page eq {
  660.                pdfpagenumber
  661.              } if
  662.            } if
  663.          } if
  664.          dup type /integertype ne 
  665.            { pop }
  666.            { /Page exch 4 -2 roll }
  667.          ifelse
  668.      dup length 1 sub 1 exch getinterval /View exch 3 -1 roll
  669.        }
  670.       ifelse
  671.     }
  672.    if
  673. } bind def
  674. % <pagedict> mark ... -proc- -
  675. /namedactions 8 dict dup begin
  676.   /FirstPage {
  677.     /Page 1 3 -1 roll
  678.   } def
  679.   /LastPage {
  680.     counttomark 2 add index pdfpagecount /Page exch 3 -1 roll
  681.   } def
  682.   /NextPage {
  683.     counttomark 2 add index pdfpagenumber 1 add /Page exch 3 -1 roll
  684.   } def
  685.   /PrevPage {
  686.     counttomark 2 add index pdfpagenumber 1 sub /Page exch 3 -1 roll
  687.   } def
  688. end readonly def
  689. % <pagedict> <annotdict> -proc- -
  690. /annottypes 5 dict dup begin
  691.   /Text {
  692.     mark exch
  693.      { /Rect /Open /Contents }
  694.      { 2 copy knownoget { 3 -1 roll } { pop } ifelse }
  695.     forall pop /ANN pdfmark
  696.   } bind def
  697.   /Link {
  698.     mark exch
  699.     dup /C knownoget { /Color exch 3 -1 roll } if
  700.      { /Rect /Border }
  701.      { 2 copy knownoget { 3 -1 roll } { pop } ifelse }
  702.     forall dup /A knownoget {
  703.       dup /URI known {
  704.         /A mark 3 2 roll    % <<>> /A [ <<action>>
  705.         { oforce } forall
  706.         .dicttomark
  707.         3 2 roll
  708.       } {
  709.         dup /D knownoget {
  710.       exch pop exch dup length dict copy dup /Dest 4 -1 roll put
  711.         } {
  712.       /N knownoget {        % Assume /S /Named
  713.          namedactions exch .knownget { exec } if
  714.       } if
  715.         } ifelse
  716.       } ifelse
  717.     } if
  718.     linkdest pop /LNK pdfmark
  719.   } bind def
  720. end readonly def
  721.  
  722. % **** The following procedure should not be changed to allow clients
  723. % **** to directly interface with the constituent procedures. GSview
  724. % **** and some Artifex customers rely on the pdfshowpage_init,
  725. % **** pdfshowpage_setpage, pdfshowpage_finish so all logic should be
  726. % **** implemented in one of those three procedures.
  727. /pdfshowpage        % <pagedict> pdfshowpage -
  728.  { dup /Page exch store
  729.    pdfshowpage_init 
  730.    pdfshowpage_setpage 
  731.    pdfshowpage_finish
  732.  } bind def
  733.  
  734. /pdfpagecontents    % <pagedict> pdfpagecontents <contents>
  735.  { } bind def
  736.  
  737. /pdfshowpage_init     % <pagedict> pdfshowpage_init <pagedict>
  738.  { /DSCPageCount DSCPageCount 1 add store
  739.  } bind def
  740.  
  741. /.pdfshowpage_Install {    % <pagedict> [<prevproc>] .pdfshowpage_Install -
  742.   exch
  743.     % We would like to clip to the CropBox here, but the subsequent
  744.     % initgraphics would override it.  Instead, we have to handle it
  745.     % in graphicsbeginpage.
  746.   dup /CropBox pget dup {exch pop} if systemdict /UseCropBox known and {
  747.     dup /CropBox pget pop
  748.   } {
  749.     dup /MediaBox pget pop    % There has to be a MediaBox
  750.   } ifelse
  751.   % stack: [<prevproc>] <pagedict> <Crop|Media Box>
  752.   exch pop oforce_array            % done with the pagedict
  753.   systemdict /PDFFitPage known {
  754.     PDFDEBUG { (Fiting PDF to imageable area of the page.) = flush } if
  755.     currentpagedevice /.HWMargins get aload pop
  756.     currentpagedevice /PageSize get aload pop
  757.     3 -1 roll sub 3 1 roll exch sub exch
  758.     % stack: [<prevproc>] <pagedict> <Crop|Media Box> Xmin Ymin Xmax Ymax
  759.     PDFDEBUG { (    Translate up by [ ) print 3 index =print (, ) print 2 index =print ( ]) = flush } if
  760.     3 index 3 index translate        % move origin up to imageable area
  761.     2 index sub exch 3 index sub exch 4 2 roll pop pop
  762.         % stack: [Box] XImageable YImageable
  763.     2 index aload pop 2 index sub exch 3 index sub exch 4 2 roll pop pop
  764.         % stack: [Box] XImageable YImageable XBox YBox
  765.     3 -1 roll exch div 3 1 roll div .min
  766.     PDFDEBUG { (    Scale by ) print dup = flush } if
  767.     dup scale
  768.   } if
  769.   % Now translate to the origin given in the Crop|Media Box
  770.   dup 0 get neg exch 1 get neg translate
  771.   0 get
  772.   exec
  773. } bind def
  774.  
  775. /pdfshowpage_setpage {    % <pagedict> pdfshowpage_setpage <pagedict>
  776.   5 dict begin        % for setpagedevice
  777.     % Stack: pagedict
  778.   % UseCIEColor is always true for PDF; see the comment in runpdf above
  779.   /UseCIEColor true def
  780.   currentpagedevice /Orientation 2 index /Rotate pget not { 0 } if 90 idiv
  781.     % Rotate specifies *clockwise* rotation!
  782.     neg 3 and def
  783.     % Stack: pagedict currentpagedict
  784.   1 index /CropBox pget dup {exch pop} if systemdict /UseCropBox known and {
  785.             % Set the page size.
  786.     1 index /CropBox pget pop oforce_elems
  787.     boxrect 2 array astore /PageSize exch def pop pop
  788.   } {
  789.     1 index /MediaBox pget {
  790.             % Set the page size.
  791.       oforce_elems boxrect 2 array astore /PageSize exch def pop pop
  792.     } if
  793.   } ifelse
  794.   % Don't change the page size if we are going to fit the PDF to the page
  795.   systemdict /PDFFitPage known { currentdict /PageSize undef } if
  796.   dup /Install .knownget {
  797.             % Don't let the Install procedure get more deeply
  798.             % nested after every page.
  799.       dup type dup /arraytype eq exch /packedarraytype eq or {
  800.     dup length 4 eq {
  801.       dup 2 get /.pdfshowpage_Install load eq {
  802.         1 get 0 get    % previous procedure
  803.       } if
  804.     } if
  805.       } if
  806.   } {
  807.     { }
  808.   } ifelse 1 array astore
  809.   2 index exch /.pdfshowpage_Install load /exec load
  810.   4 packedarray cvx
  811.     % Stack: pagedict currentpagedict installproc
  812.   /Install exch def
  813.     % Stack: pagedict currentpagedict
  814.   pop currentdict end setpagedevice
  815. } bind def
  816.  
  817. /pdfshowpage_finish {    % <pagedict> pdfshowpage_finish -
  818.    save /PDFSave exch store
  819.    /PDFdictstackcount countdictstack store
  820.    (before exec) VMDEBUG
  821.  
  822.    % set up color space substitution (this must be inside the page save)
  823.    pdfshowpage_setcspacesub
  824.  
  825.   .writepdfmarks {
  826.  
  827.     % Copy the crop box.
  828.     dup /CropBox knownoget {
  829.       oforce_array
  830.  
  831.         % .pdfshowpage_Install translates the origin -
  832.         % do same here with the CropBox.
  833.  
  834.       1 index /CropBox pget dup {exch pop} if systemdict /UseCropBox known and {
  835.         1 index /CropBox pget pop
  836.       } {
  837.         1 index /MediaBox pget pop    % There has to be a MediaBox
  838.       } ifelse
  839.       oforce_array
  840.       dup 0 get exch 1 get   % [] tx ty
  841.       2 index 0 get 2 index sub 3 index exch 0 exch put
  842.       2 index 2 get 2 index sub 3 index exch 2 exch put
  843.       2 index 1 get 1 index sub 3 index exch 1 exch put
  844.       2 index 3 get 1 index sub 3 index exch 3 exch put
  845.       pop pop
  846.  
  847.     % If the page has been rotated, rotate the CropBox.
  848.       mark /CropBox 3 -1 roll
  849.       3 index /Rotate pget {
  850.     90 idiv 1 and 0 ne {
  851.       aload pop 4 -2 roll exch 4 2 roll exch 4 array astore
  852.     } if
  853.       } if
  854.       /PAGE pdfmark
  855.     } if
  856.  
  857.     % Copy annotations and links.
  858.     dup /Annots knownoget {
  859.       0 1 2 index length 1 sub
  860.        { 1 index exch oget
  861.          dup /Subtype oget annottypes exch .knownget { exec } { pop } ifelse
  862.        }
  863.       for pop
  864.     } if
  865.  
  866.   } if        % end .writepdfmarks
  867.  
  868.     % Display the actual page contents.
  869.    6 dict begin
  870.    /BXlevel 0 def
  871.    /BGDefault currentblackgeneration def
  872.    /UCRDefault currentundercolorremoval def
  873.     %****** DOESN'T HANDLE COLOR TRANSFER YET ******
  874.    /TRDefault currenttransfer def
  875.   matrix currentmatrix 2 dict
  876.   2 index /CropBox knownoget {
  877.     oforce_elems boxrect 4 array astore 1 index /ClipRect 3 -1 roll put
  878.   } if
  879.   dictbeginpage setmatrix
  880.   /DefaultQstate qstate store
  881.  
  882.   dup          % for showing annotations below
  883.   count 1 sub /pdfemptycount exch store
  884.     % If the page uses any transparency features, show it within
  885.     % a transparency group.
  886.   dup pageusestransparency dup /PDFusingtransparency exch def {
  887.     % Show the page within a PDF 1.4 device filter.
  888.     0 .pushpdf14devicefilter {
  889.       % If the page has a Group, enclose contents in transparency group.
  890.       % (Adobe Tech Note 5407, sec 9.2)
  891.       dup /Group knownoget {
  892.     1 index /CropBox knownoget not {
  893.       1 index /MediaBox pget pop
  894.     } if oforce_array .beginformgroup {
  895.       showpagecontents
  896.     } .internalstopped {
  897.       .discardtransparencygroup stop
  898.     } if .endtransparencygroup
  899.       } {
  900.     showpagecontents
  901.       } ifelse
  902.     } .internalstopped {
  903.       % todo: discard
  904.       .popdevicefilter stop
  905.     } if .popdevicefilter
  906.   } {
  907.     showpagecontents
  908.   } ifelse
  909.   % check for extra garbage on the ostack and clean it up
  910.   count pdfemptycount sub dup 0 ne {
  911.     (   **** File did not complete the page properly and may be damaged.\n)
  912.     pdfformaterror
  913.     { pop } repeat
  914.   } {
  915.     pop
  916.   } ifelse
  917.   % todo: mixing drawing ops outside the device filter could cause
  918.   % problems, for example with the pnga device.
  919.   /Annots knownoget { { oforce drawannot } forall } if
  920.   endpage
  921.   end            % scratch dict
  922.   % Some PDF files don't have matching q/Q (gsave/grestore) so we need
  923.   % to clean up any left over dicts from the dictstack
  924.   countdictstack PDFdictstackcount sub dup 0 ne { 
  925.     (   **** Warning: File has imbalanced q/Q operators \(too many q's\)\n)
  926.     pdfformaterror
  927.     { end } repeat
  928.   } {
  929.     pop
  930.   } ifelse
  931.   (after exec) VMDEBUG
  932.   Repaired        % pass Repaired state around the restore
  933.   PDFSave restore
  934.   /Repaired exch def
  935. } bind def
  936. /showpagecontents {    % <pagedict> showpagecontents -
  937.   gsave        % preserve gstate for Annotations later
  938.   /Contents knownoget not { 0 array } if
  939.   dup type /arraytype ne { 1 array astore } if {
  940.     oforce false resolvestream pdfopdict .pdfrun
  941.   } forall
  942.   grestore
  943. } bind def
  944. /processcolorspace {    % - processcolorspace <colorspace>
  945.     % The following is per the PLRM3.
  946.   currentdevice 1 dict dup /ProcessColorModel dup put .getdeviceparams
  947.   exch pop exch pop
  948.   dup type /nametype ne { cvn } if
  949.   dup { setcolorspace } .internalstopped { pop /DeviceRGB } if
  950. } bind def
  951.  
  952. % ------ Transparency support ------ %
  953.  
  954. % Define minimum PDF version for checking for transparency features.
  955. % Transparency is a 1.4 feature however we have seen files that claimed
  956. % to be PDF 1.3 with transparency features.
  957. /PDFtransparencyversion 1.3 def
  958.  
  959. % Determine whether a page might invoke any transparency features:
  960. %    - Non-default BM, ca, CA, or SMask in an ExtGState
  961. %    - Image XObject with SMask
  962. % Note: we deliberately don't check to see whether a Group is defined,
  963. % because Adobe Illustrator 10 (and possibly other applications) define
  964. % a page-level group whether transparency is actually used or not.
  965. % Ignoring the presence of Group is justified because, in the absence
  966. % of any other transparency features, they have no effect.
  967. /pageusestransparency {        % <pagedict> pageusestransparency <bool>
  968.   PDFversion PDFtransparencyversion lt NOTRANSPARENCY or {
  969.     pop false
  970.   } {
  971.     false exch {
  972.       dup resourceusestransparency { pop not exit } if
  973.       /Parent knownoget not { exit } if
  974.     } loop
  975.   } ifelse
  976. } bind def
  977. % Check the Resources of a page or Form.
  978. /resourceusestransparency {    % <dict> resourceusestransparency <bool>
  979.   {    % Use loop to provide an exitable context.
  980.     /Resources knownoget not { 0 dict } if
  981.     dup /ExtGState knownoget {
  982.       false exch {
  983.     exch pop oforce
  984.     dup /BM knownoget { dup /Normal ne exch /Compatible ne and
  985.                         { pop not exit } if
  986.                           } if
  987.     dup /ca knownoget { 1 ne { pop not exit } if } if
  988.     dup /CA knownoget { 1 ne { pop not exit } if } if
  989.     dup /SMask knownoget { /None ne { pop not exit } if } if
  990.     pop
  991.       } forall { pop true exit } if
  992.     } if
  993.     dup /XObject knownoget {
  994.       false exch {
  995.     exch pop oforce dup /Subtype get
  996.     dup /Image eq { 1 index /SMask known { pop pop not exit } if } if
  997.     /Form eq {
  998.       resourceusestransparency { not exit } if
  999.     } {
  1000.       pop
  1001.     } ifelse
  1002.       } forall { pop true exit } if
  1003.     } if
  1004.     pop false exit
  1005.   } loop
  1006. } bind def
  1007.  
  1008. % ------ ColorSpace substitution support ------ %
  1009.  
  1010. %
  1011. %  <pagedict>   pdfshowpage_setcspacesub   <pagedict>
  1012. %
  1013. % Set up color space substitution for a page. Invocations of this procedure
  1014. % must be bracketed by the save/restore operation for the page, to avoid
  1015. % unintended effects on other pages.
  1016. %
  1017. % If any color space substitution is used, and the current color space is a
  1018. % device dependent color space, make sure the current color space is updated.
  1019. % There is an optimization in the setcolorspace pseudo-operator that does
  1020. % nothing if both the current and operand color spaces are the same. For
  1021. % PostScript this optimization is disabled if the UseCIEColor page device
  1022. % parameter is true. This is not the case for PDF, as performance suffers
  1023. % significantly on some PDF files if color spaces are set repeatedly. Hence,
  1024. % if color space substitution is to be used, and the current color space
  1025. % is a device dependent color space, we must make sure to "transition" the
  1026. % current color space.
  1027. %
  1028. /pdfshowpage_setcspacesub
  1029.   {
  1030.     false
  1031.       { /DefaultGray /DefaultRGB /DefaultCMYK }
  1032.       {
  1033.         dup 3 index /ColorSpace //rget exec
  1034.           { resolvecolorspace /ColorSpace defineresource pop }
  1035.           { pop }
  1036.         ifelse
  1037.       }
  1038.     forall
  1039.  
  1040.     % if using color space substitution, "transition" the current color space
  1041.       {
  1042.         currentcolorspace dup length 1 eq   % always an array
  1043.           {
  1044.             0 get
  1045.             dup /DeviceGray eq 1 index /DeviceRGB eq or 1 index /DeviceCMYK or
  1046.               { /Pattern setcolorspace setcolorspace }
  1047.               { pop }
  1048.             ifelse
  1049.           }
  1050.           { pop }
  1051.         if
  1052.       }
  1053.     if
  1054.   }
  1055. bind def
  1056.  
  1057.  
  1058.  
  1059. end            % pdfdict
  1060. .setglobal
  1061.