1 ! Copyright (C) 2010 John Benediktsson
2 ! See http://factorcode.org/license.txt for BSD license
4 USING: assocs calendar environment formatting grouping io.files
5 kernel make math ranges sequences splitting xml.entities ;
11 : pdf-string ( str -- str' )
21 } escape-string-by "(" ")" surround ;
23 : pdf-object ( str n -- str' )
24 "%d 0 obj\n" sprintf "\nendobj" surround ;
26 : pdf-stream ( str -- str' )
27 [ length 1 + "<<\n/Length %d\n>>" sprintf ]
28 [ "\nstream\n" "\nendstream" surround ] bi append ;
33 "/CreationDate D:" now "%Y%m%d%H%M%S" strftime append ,
34 "/Producer (Factor)" ,
35 "/Author " "USER" os-env "unknown" or pdf-string append ,
36 "/Creator (created with Factor)" ,
38 ] { } make join-lines ;
40 : pdf-catalog ( -- str )
57 : pdf-pages ( n -- str )
61 "/MediaBox [ 0 0 612 792 ]" ,
62 [ "/Count %d" sprintf , ]
65 [ "%d 0 R " sprintf ] map concat
66 "/Kids [ " "]" surround ,
69 ] { } make join-lines ;
71 : pdf-text ( lines -- str )
77 [ pdf-string "'" append , ] each
79 ] { } make join-lines pdf-stream ;
81 : pdf-page ( n -- page )
86 1 + "/Contents %d 0 R" sprintf ,
87 "/Resources << /Font << /F1 3 0 R >> >>" ,
89 ] { } make join-lines ;
91 : pdf-trailer ( objects -- str )
94 dup length 1 + "0 %d" sprintf ,
95 "0000000000 65535 f" ,
97 over "%010X 00000 n" sprintf , length 1 + +
101 dup length 1 + "/Size %d" sprintf ,
106 [ length 1 + ] map-sum 9 + "%d" sprintf ,
108 ] { } make join-lines ;
110 : string>lines ( str -- lines )
111 "\t" split " " join split-lines
112 [ [ " " ] when-empty ] map ;
114 : lines>pages ( lines -- pages )
115 [ 84 <groups> ] map concat 57 <groups> ;
117 : pages>objects ( pages -- objects )
122 dup length pdf-pages ,
123 dup length 5 swap 2 range boa zip
124 [ pdf-page , pdf-text , ] assoc-each
126 dup length [1..b] zip [ first2 pdf-object ] map ;
128 : objects>pdf ( objects -- str )
129 [ join-lines "\n" append "%PDF-1.4\n" ]
130 [ pdf-trailer ] bi surround ;
134 : text-to-pdf ( str -- str' )
135 string>lines lines>pages pages>objects objects>pdf ;
137 : file-to-pdf ( path encoding -- )
138 [ file-contents text-to-pdf ]
139 [ [ ".pdf" append ] dip set-file-contents ] 2bi ;