pdf_rbld.ps 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. % Copyright (C) 2002 artofcode LLC. All rights reserved.
  2. %
  3. % This software is provided AS-IS with no warranty, either express or
  4. % implied.
  5. %
  6. % This software is distributed under license and may not be copied,
  7. % modified or distributed except as expressly authorized under the terms
  8. % of the license contained in the file LICENSE in this distribution.
  9. %
  10. % For more information about licensing, please refer to
  11. % http://www.ghostscript.com/licensing/. For information on
  12. % commercial licensing, go to http://www.artifex.com/licensing/ or
  13. % contact Artifex Software, Inc., 101 Lucas Valley Road #110,
  14. % San Rafael, CA 94903, U.S.A., +1(415)492-9861.
  15. % $Id: pdf_rbld.ps,v 1.8 2005/02/07 06:38:02 dan Exp $
  16. % pdf_rbld.ps - Rebuilding of broken PDF files (xref errors)
  17. % This module contains routines that are used if we detect an error
  18. % while reading the xref tables. These routines will scan the file and
  19. % build an xref table by finding the objects. We also need to find the
  20. % appropriate trailer dictionary. Note: One procedure is also used
  21. % even if we do not need to rebuild a PDF file.
  22. %
  23. % This module cannot rebuild a PDF file which has had errors created inside
  24. % of objects or binary data streams. It often succeeds with files that
  25. % have had its end of lines converted between unix and dos versions.
  26. % if true --> we have an object with duplicate object and generation numbers.
  27. /dup_obj_gen_num false def
  28. % Note: This routine is also used by non-rebuild code.
  29. % Store a line in the xref array (Actually Objects and Generations arrays)
  30. % <obj num> (strm num> <obj loc> <gen num> setxrefentry <obj num> strm num>
  31. % <obj loc> <gen num>
  32. /setxrefentry
  33. { % We store generation numbers as value + 1
  34. % We reserve 0 to indicate an free xref entry
  35. 1 add % increment generation number
  36. % To save space, generations numbers are stored in a lstring unless we
  37. % find a generation number greater than 255. If so then transfer to
  38. % an larray.
  39. dup 255 gt {
  40. Generations ltype /stringtype eq { % Convert Generations to an larray.
  41. larray Generations llength lgrowto dup % Create new larray
  42. 0 1 2 index llength 1 sub { % Copy from old lstring to new larray
  43. Generations 1 index lget lput dup
  44. } for
  45. pop
  46. /Generations exch store % Save new Generations larray
  47. } if
  48. } if
  49. % Verify that the new values are for a new object. If the current
  50. % entry is null then we have a new entry.
  51. Objects 4 index lget null eq {
  52. ObjectStream 4 index 4 index cvx lput % Save ObjectStream object number
  53. Objects 4 index 3 index cvx lput % Save object location
  54. Generations 4 index 2 index lput % Save geenration number
  55. } {
  56. % Verify that the new entry has at least as high a generaton number
  57. % We accept equal entry number because we have found PDF files in
  58. % which there are multiple objects with the same object and entry
  59. % numbers. The normal xref logic only accepts the first such
  60. % entry that it finds. However the 'rebuild PDF' logic can find
  61. % both such entries. The correct one is usually the last one.
  62. Generations 4 index lget 1 index le {
  63. ObjectStream 4 index 4 index cvx lput % Save ObjectStream object number
  64. Objects 4 index 3 index cvx lput % Save object location
  65. Generations 4 index 2 index lput % Save geenration number
  66. } if
  67. % Set error flag if we have equal object and generation numbers
  68. Generations 4 index lget 1 index eq { /dup_obj_gen_num true def } if
  69. } ifelse
  70. } bind def
  71. % Print the contents of the xref array. This actually consists of two
  72. % arrays (Objects and Generations). Both are larrays. larrays are a
  73. % special Ghostscript object which can be arrays with more than 64k
  74. % elements.
  75. /print_xref % - print_xref -
  76. { 0 1 Objects llength 1 sub % stack: 0 1 <number of objects - 1>
  77. { dup =only % print object number
  78. ( ) print
  79. dup Generations exch lget 1 sub =only % print Generation number
  80. ( ) print
  81. dup ObjectStream exch lget ==only % print ObjectStream object number
  82. ( ) print
  83. Objects exch lget === % print object location
  84. } for
  85. flush
  86. } bind def
  87. % This is the same as the postscript token operator except that
  88. % errors are ignored.
  89. /token_nofail
  90. {
  91. { token } .internalstopped
  92. { pop false } if
  93. } bind odef
  94. % Get token from string and check its type
  95. % <string> <type> typed_token <false> % no token or not match
  96. % <string> <type> typed_token <obj> <last> <true> % matching token type
  97. % Where last is the string remainder
  98. /typed_token
  99. { exch
  100. token_nofail % get token
  101. {
  102. dup type % stack: type last token type
  103. 4 -1 roll eq { % stack: last token bool
  104. exch true % desired object found - set exit status
  105. } {
  106. pop pop false % not type - clear stack, set exit status
  107. } ifelse
  108. } {
  109. pop false % no token - pop type, set exit status
  110. } ifelse % check if we got token
  111. } bind def
  112. % Allocate space for post_eof_count to be bound into procedures below.
  113. /post_eof_count 0 def
  114. % We want the location of the trailer dictionary at the start of file.
  115. % First we will find the xref. Then we will skip over the xref entries
  116. % to the trailer.
  117. /search_start_trailer % - search_start_trailer <trailer loc>
  118. { % Read the first 300 bytes and check for xref
  119. PDFfile 0 setfileposition
  120. 300 string 0 1 299 { 2 copy PDFfile read pop put pop } for
  121. (xref) search {
  122. % found 'xref'
  123. exch pop exch pop length 4 add PDFfile exch setfileposition
  124. PDFfile token pop % get starting entry - or 'trailer'
  125. (trailer) ne { % if we do not already have 'trailer'
  126. PDFfile token pop % get number of entries
  127. PDFfile token pop pop % this moves us into the middle of the first entry
  128. 25 string exch % define working string for readline
  129. { PDFfile 1 index readline pop pop
  130. } repeat % skip entries
  131. pop % pop working string
  132. PDFfile token pop pop % get 'trailer'
  133. PDFfile fileposition % get file position
  134. } if
  135. } {
  136. pop 0 % no xref - should not happen
  137. } ifelse
  138. } bind def
  139. % We want the location of the trailer dictionary at the end of file.
  140. % We will read the last block of data and search for the final occurance
  141. % of the word 'trailer'
  142. /search_end_trailer % - search_end_trailer <trailer loc>
  143. { % Position to read block of data from the end of the file. Note: We ignore
  144. % anything past the last %%EOF since this is not PDF data.
  145. PDFfile 0 setfileposition
  146. PDFfile bytesavailable post_eof_count sub % location of end of data
  147. dup 4096 .min % block size to read
  148. % stack: <file end pos> <block size>
  149. % move file position to the start of the block
  150. 2 copy sub PDFfile exch setfileposition
  151. % read block of data
  152. dup string 0 1 4 -1 roll 1 sub { 2 copy PDFfile read pop put pop } for
  153. % search for last occurance of 'trailer'
  154. (trailer) { search not { exit } if pop } loop
  155. % determine where the trailer is in the file
  156. % trailer loc = end loc - remaing string length
  157. length sub
  158. } bind def
  159. % We want to find the trailer dictionary. There is a trailer dictionary
  160. % for each xref object list. We only want the trailer dictionary associated
  161. % with the first xref object list. In theory this can be anywhere in the
  162. % file. However since we are trying to repair a broken file, we cannot simply
  163. % follow the xref links. So we are falling back to a simple strategy. We
  164. % find the specified location of the first xref list. If its location is in
  165. % the first half of the file then we search for the first trailer dictionary
  166. % at the start of the file. Otherwise we search for the last trailer at the
  167. % end of the file.
  168. /search_trailer % - search_trailer -
  169. { % Find the 'startxref' and associated position at the end of the file.
  170. % Position to read block of data from the end of the file. Note: We
  171. % actually end at the end of the last %%EOF since this is the end of the
  172. % useful PDF data. (Some files contain trailing garbage.)
  173. PDFfile 0 setfileposition
  174. PDFfile bytesavailable % size of file
  175. post_eof_count sub dup % location of end of last %%EOF
  176. dup 4096 .min % block size to read
  177. % stack: <useful file size> <useful file size file> <block size>
  178. % move file position to the start of the block
  179. 2 copy sub PDFfile exch setfileposition
  180. % read block of data
  181. dup string 0 1 4 -1 roll 1 sub { 2 copy PDFfile read pop put pop } for
  182. % search for last occurance of 'startxref'
  183. (startxref) { search not { exit } if pop } loop
  184. % determine where the trailer is in the file
  185. % trailer loc = end loc - remaing string length
  186. length sub 9 sub
  187. % move the file to this position and read startxref and position
  188. PDFfile exch setfileposition
  189. PDFfile token pop pop PDFfile token pop
  190. % compare xref position to 1/2 the length of the file and search for trailer
  191. exch 2 div lt { search_start_trailer } { search_end_trailer } ifelse
  192. % get the trailer
  193. PDFfile exch setfileposition % set to the specified trailer location
  194. PDFfile traileropdict .pdfrun % read trailer info
  195. /Trailer exch def
  196. } bind def
  197. % This routine will determine if there is stuff after the %%EOF. There is
  198. % supposed to be only a line termination. However many real life files
  199. % contain some garbage. This routine checks how much. We then ignore this
  200. % stuff when we are scanning for objects.
  201. /determine_post_eof_count % - determine_post_eof_count <count>
  202. { % Position to read block of data from the end of the file.
  203. PDFfile 0 setfileposition
  204. PDFfile bytesavailable % size of file
  205. dup 4096 .min % block size to read
  206. % stack: <file size> <file size> <block size>
  207. % move file position to the start of the block
  208. 2 copy sub PDFfile exch setfileposition
  209. % read block of data
  210. dup string 0 1 4 -1 roll 1 sub { 2 copy PDFfile read pop put pop } for
  211. % search for last occurance of '%%EOF'
  212. (%%EOF) { search not { exit } if pop } loop
  213. % how much is left = remaining string length
  214. length exch pop % pop /%%EOF
  215. } bind def
  216. % This routine will scan a file searaching for object locations to build
  217. % an alternate version of the data in the xref tables.
  218. % Its purpose is to provide a basis for an xref fixing facility.
  219. /search_objects % - search_objects -
  220. { % Initialize the Objects, Generations, etc. larrays
  221. initPDFobjects
  222. % reset duplicate object and generation numbers error flag
  223. /dup_obj_gen_num false def
  224. % Determine how many bytes are in the file after the final %%EOF
  225. /post_eof_count determine_post_eof_count def
  226. % Start at the beginning of the file
  227. PDFfile 0 setfileposition
  228. % Create a working string (and also store its length on stack). We are
  229. % using a maximum size string size the logic below wants a recovered object
  230. % to fit into our working string.
  231. 65535 dup string
  232. { % Now loop through the entire file lloking for objects
  233. PDFfile fileposition % save current file position
  234. % When we get near the end of the file, we use a smaller interval of
  235. % our working string to prevent reading past the end. (See comments on
  236. % EOF testing below.)
  237. PDFfile bytesavailable post_eof_count sub 10 sub dup 4 index lt {
  238. 2 index 0 3 -1 roll getinterval % near EOF, use interval of string
  239. } { pop 1 index % not near end, use full working string
  240. }ifelse
  241. % Read a line from file. If the line does not fit into our working string,
  242. % or any other error, then we will discard it.
  243. PDFfile exch { readline } .internalstopped
  244. { pop pop false } if % indicate no string if we stopped
  245. { % stack: <length> <working_str> <loc> <string>
  246. % Now that we have line, get obj num, ref num, and 'obj'. Verify that each
  247. % of these is correct type.
  248. /integertype typed_token { % get obj number
  249. /integertype typed_token { % get ref number
  250. /nametype typed_token { % get 'obj' text
  251. pop % pop remaining string
  252. /obj eq { % verify name is 'obj'
  253. % make sure we have room in the arrays. We work in increments
  254. % of 20 each time we increase the size.
  255. 1 index 20 add 20 idiv 20 mul
  256. growPDFobjects
  257. % save xref parameters into ObjectStream, Objects and Generations
  258. 1 index 0 4 index 3 index % rearrange parms for setxrefentry
  259. setxrefentry % save parameters
  260. pop pop pop pop % clear parameters
  261. } if % check if name is 'obj'
  262. } if % check if we got 'obj" string
  263. pop % remove ref number
  264. } if % check if we got ref number
  265. pop % remove obj number
  266. } if % check if we got object number
  267. } if % check if got a string from readline
  268. pop % remove location
  269. % Check if we are approaching the end of the file. We do not want to
  270. % read past the end of the file since that closes it. We actually stop
  271. % 10-20 bytes early since there cannot be an object that close to the end.
  272. % (There is a Trailer dictionary, etc. at the end of the file.)
  273. PDFfile bytesavailable post_eof_count sub 20 lt { exit } if
  274. } loop % loop through the entire file
  275. pop pop % remove working string and its length
  276. % Output warning if we have two objects with the same object and generation
  277. % numbers.
  278. dup_obj_gen_num {
  279. ( **** Warning: There are objects with matching object and generation\n)
  280. pdfformaterror
  281. ( **** numbers. The accuracy of the resulting image is unknown.\n)
  282. pdfformaterror
  283. } if
  284. } bind def
  285. % Print warning message because we found a problem while reading the xref
  286. % tables
  287. /print_xref_warning
  288. { ( **** Warning: An error occurred while reading an XREF table.\n)
  289. pdfformaterror
  290. ( **** The file has been damaged. This may have been caused\n)
  291. pdfformaterror
  292. ( **** by a problem while converting or transfering the file.\n)
  293. pdfformaterror
  294. ( **** Ghostscript will attempt to recover the data.\n)
  295. pdfformaterror
  296. } bind def
  297. % Attempt to recover the XRef data. This is called if we have a failure
  298. % while reading the normal XRef tables. This routine usually works
  299. % only for pre PDF1.5 versions of PDF files.
  300. /recover_xref_data % - recover_xref_data -
  301. { print_xref_warning % Print warning message
  302. count pdfemptycount sub { pop } repeat % remove anything left by readxref
  303. search_objects % Search for objects
  304. } bind def