fixed clipping bug: More than one clipping region inside a saved state
[swftools.git] / pdf2swf / SWFOutputDev.cc
1 /* pdfswf.cc
2    implements a pdf output device (OutputDev).
3
4    This file is part of swftools.
5
6    Swftools 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    Swftools 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
17    along with swftools; if not, write to the Free Software
18    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <stddef.h>
23 #include <string.h>
24 #include <unistd.h>
25 //xpdf header files
26 #include "GString.h"
27 #include "gmem.h"
28 #include "Object.h"
29 #include "Stream.h"
30 #include "Array.h"
31 #include "Dict.h"
32 #include "XRef.h"
33 #include "Catalog.h"
34 #include "Page.h"
35 #include "PDFDoc.h"
36 #include "Params.h"
37 #include "Error.h"
38 #include "config.h"
39 #include "OutputDev.h"
40 #include "GfxState.h"
41 #include "GfxFont.h"
42 #include "FontFile.h"
43 //swftools header files
44 #include "swfoutput.h"
45 extern "C" {
46 #include "../lib/log.h"
47 }
48
49 static PDFDoc*doc = 0;
50 static char* swffilename = 0;
51 int numpages;
52 int currentpage;
53
54 // swf <-> pdf pages
55 int*pages = 0;
56 int pagebuflen = 0;
57 int pagepos = 0;
58
59 static void printInfoString(Dict *infoDict, char *key, char *fmt);
60 static void printInfoDate(Dict *infoDict, char *key, char *fmt);
61
62 double fontsizes[] = 
63 {
64  0.833,0.833,0.889,0.889,
65  0.788,0.722,0.833,0.778,
66  0.600,0.600,0.600,0.600,
67  0.576,0.576,0.576,0.576,
68  0.733 //?
69 };
70 char*fontnames[]={
71 "Helvetica",             
72 "Helvetica-Bold",        
73 "Helvetica-BoldOblique", 
74 "Helvetica-Oblique",     
75 "Times-Roman",           
76 "Times-Bold",            
77 "Times-BoldItalic",      
78 "Times-Italic",          
79 "Courier",               
80 "Courier-Bold",          
81 "Courier-BoldOblique",   
82 "Courier-Oblique",       
83 "Symbol",                
84 "Symbol",                
85 "Symbol",                
86 "Symbol",
87 "ZapfDingBats"
88 };
89
90 struct mapping {
91     char*pdffont;
92     char*filename;
93     int id;
94 } pdf2t1map[] ={
95 {"Times-Roman",           "n021003l.pfb"},
96 {"Times-Italic",          "n021023l.pfb"},
97 {"Times-Bold",            "n021004l.pfb"},
98 {"Times-BoldItalic",      "n021024l.pfb"},
99 {"Helvetica",             "n019003l.pfb"},
100 {"Helvetica-Oblique",     "n019023l.pfb"},
101 {"Helvetica-Bold",        "n019004l.pfb"},
102 {"Helvetica-BoldOblique", "n019024l.pfb"},
103 {"Courier",               "n022003l.pfb"},
104 {"Courier-Oblique",       "n022023l.pfb"},
105 {"Courier-Bold",          "n022004l.pfb"},
106 {"Courier-BoldOblique",   "n022024l.pfb"},
107 {"Symbol",                "s050000l.pfb"},
108 {"ZapfDingbats",          "d050000l.pfb"}};
109
110 class GfxState;
111 class GfxImageColorMap;
112
113 class SWFOutputDev:  public OutputDev {
114   struct swfoutput output;
115   int outputstarted;
116 public:
117
118   // Constructor.
119   SWFOutputDev();
120
121   // Destructor.
122   virtual ~SWFOutputDev() ;
123
124   //----- get info about output device
125
126   // Does this device use upside-down coordinates?
127   // (Upside-down means (0,0) is the top left corner of the page.)
128   virtual GBool upsideDown();
129
130   // Does this device use drawChar() or drawString()?
131   virtual GBool useDrawChar();
132
133   //----- initialization and control
134
135   // Start a page.
136   virtual void startPage(int pageNum, GfxState *state) ;
137
138   //----- link borders
139   virtual void drawLink(Link *link, Catalog *catalog) ;
140
141   //----- save/restore graphics state
142   virtual void saveState(GfxState *state) ;
143   virtual void restoreState(GfxState *state) ;
144
145   //----- update graphics state
146
147   virtual void updateFont(GfxState *state);
148   virtual void updateFillColor(GfxState *state);
149   virtual void updateStrokeColor(GfxState *state);
150   virtual void updateLineWidth(GfxState *state);
151   
152   virtual void updateAll(GfxState *state) 
153   {
154       updateFont(state);
155       updateFillColor(state);
156       updateStrokeColor(state);
157       updateLineWidth(state);
158   };
159
160   //----- path painting
161   virtual void stroke(GfxState *state) ;
162   virtual void fill(GfxState *state) ;
163   virtual void eoFill(GfxState *state) ;
164
165   //----- path clipping
166   virtual void clip(GfxState *state) ;
167   virtual void eoClip(GfxState *state) ;
168
169   //----- text drawing
170   virtual void beginString(GfxState *state, GString *s) ;
171   virtual void endString(GfxState *state) ;
172   virtual void drawChar(GfxState *state, double x, double y,
173                         double dx, double dy, Guchar c) ;
174   virtual void drawChar16(GfxState *state, double x, double y,
175                           double dx, double dy, int c) ;
176
177   //----- image drawing
178   virtual void drawImageMask(GfxState *state, Object *ref, Stream *str,
179                              int width, int height, GBool invert,
180                              GBool inlineImg);
181   virtual void drawImage(GfxState *state, Object *ref, Stream *str,
182                          int width, int height, GfxImageColorMap *colorMap,
183                          GBool inlineImg);
184
185   private:
186   void drawGeneralImage(GfxState *state, Object *ref, Stream *str,
187                                    int width, int height, GfxImageColorMap*colorMap, GBool invert,
188                                    GBool inlineImg, int mask);
189   int clipping[64];
190   int clippos;
191
192   int setT1Font(char*name,FontEncoding*enc);
193   char* substitutefont(GfxFont*gfxFont);
194   int t1id;
195   int jpeginfo; // did we write "File contains jpegs" yet?
196   int pbminfo; // did we write "File contains jpegs" yet?
197   int linkinfo; // did we write "File contains links" yet?
198
199   GfxState *laststate;
200 };
201
202 char mybuf[1024];
203 char* gfxstate2str(GfxState *state)
204 {
205   char*bufpos = mybuf;
206   GfxRGB rgb;
207   bufpos+=sprintf(bufpos,"CTM[%.3f/%.3f/%.3f/%.3f/%.3f/%.3f] ",
208                                     state->getCTM()[0],
209                                     state->getCTM()[1],
210                                     state->getCTM()[2],
211                                     state->getCTM()[3],
212                                     state->getCTM()[4],
213                                     state->getCTM()[5]);
214   if(state->getX1()!=0.0)
215   bufpos+=sprintf(bufpos,"X1-%.1f ",state->getX1());
216   if(state->getY1()!=0.0)
217   bufpos+=sprintf(bufpos,"Y1-%.1f ",state->getY1());
218   bufpos+=sprintf(bufpos,"X2-%.1f ",state->getX2());
219   bufpos+=sprintf(bufpos,"Y2-%.1f ",state->getY2());
220   bufpos+=sprintf(bufpos,"PW%.1f ",state->getPageWidth());
221   bufpos+=sprintf(bufpos,"PH%.1f ",state->getPageHeight());
222   /*bufpos+=sprintf(bufpos,"FC[%.1f/%.1f] ",
223           state->getFillColor()->c[0], state->getFillColor()->c[1]);
224   bufpos+=sprintf(bufpos,"SC[%.1f/%.1f] ",
225           state->getStrokeColor()->c[0], state->getFillColor()->c[1]);*/
226 /*  bufpos+=sprintf(bufpos,"FC[%.1f/%.1f/%.1f/%.1f/%.1f/%.1f/%.1f/%.1f]",
227           state->getFillColor()->c[0], state->getFillColor()->c[1],
228           state->getFillColor()->c[2], state->getFillColor()->c[3],
229           state->getFillColor()->c[4], state->getFillColor()->c[5],
230           state->getFillColor()->c[6], state->getFillColor()->c[7]);
231   bufpos+=sprintf(bufpos,"SC[%.1f/%.1f/%.1f/%.1f/%.1f/%.1f/%.1f/%.1f]",
232           state->getStrokeColor()->c[0], state->getFillColor()->c[1],
233           state->getStrokeColor()->c[2], state->getFillColor()->c[3],
234           state->getStrokeColor()->c[4], state->getFillColor()->c[5],
235           state->getStrokeColor()->c[6], state->getFillColor()->c[7]);*/
236   state->getFillRGB(&rgb);
237   if(rgb.r || rgb.g || rgb.b)
238   bufpos+=sprintf(bufpos,"FR[%.1f/%.1f/%.1f] ", rgb.r,rgb.g,rgb.b);
239   state->getStrokeRGB(&rgb);
240   if(rgb.r || rgb.g || rgb.b)
241   bufpos+=sprintf(bufpos,"SR[%.1f/%.1f/%.1f] ", rgb.r,rgb.g,rgb.b);
242   if(state->getFillColorSpace()->getNComps()>1)
243   bufpos+=sprintf(bufpos,"CS[[%d]] ",state->getFillColorSpace()->getNComps());
244   if(state->getStrokeColorSpace()->getNComps()>1)
245   bufpos+=sprintf(bufpos,"SS[[%d]] ",state->getStrokeColorSpace()->getNComps());
246   if(state->getFillPattern())
247   bufpos+=sprintf(bufpos,"FP%08x ", state->getFillPattern());
248   if(state->getStrokePattern())
249   bufpos+=sprintf(bufpos,"SP%08x ", state->getStrokePattern());
250  
251   if(state->getFillOpacity()!=1.0)
252   bufpos+=sprintf(bufpos,"FO%.1f ", state->getFillOpacity());
253   if(state->getStrokeOpacity()!=1.0)
254   bufpos+=sprintf(bufpos,"SO%.1f ", state->getStrokeOpacity());
255
256   bufpos+=sprintf(bufpos,"LW%.1f ", state->getLineWidth());
257  
258   double * dash;
259   int length;
260   double start;
261   state->getLineDash(&dash, &length, &start);
262   int t;
263   if(length)
264   {
265       bufpos+=sprintf(bufpos,"DASH%.1f[",start);
266       for(t=0;t<length;t++) {
267           bufpos+=sprintf(bufpos,"D%.1f",dash[t]);
268       }
269       bufpos+=sprintf(bufpos,"]");
270   }
271
272   if(state->getFlatness()!=1)
273   bufpos+=sprintf(bufpos,"F%d ", state->getFlatness());
274   if(state->getLineJoin()!=0)
275   bufpos+=sprintf(bufpos,"J%d ", state->getLineJoin());
276   if(state->getLineJoin()!=0)
277   bufpos+=sprintf(bufpos,"C%d ", state->getLineCap());
278   if(state->getLineJoin()!=0)
279   bufpos+=sprintf(bufpos,"ML%d ", state->getMiterLimit());
280
281   if(state->getFont() && state->getFont()->getName() && state->getFont()->getName()->getCString())
282   bufpos+=sprintf(bufpos,"F\"%s\" ",((state->getFont())->getName())->getCString());
283   bufpos+=sprintf(bufpos,"FS%.1f ", state->getFontSize());
284   bufpos+=sprintf(bufpos,"MAT[%.1f/%.1f/%.1f/%.1f/%.1f/%.1f] ", state->getTextMat()[0],state->getTextMat()[1],state->getTextMat()[2],
285                                    state->getTextMat()[3],state->getTextMat()[4],state->getTextMat()[5]);
286   if(state->getCharSpace())
287   bufpos+=sprintf(bufpos,"CS%.5f ", state->getCharSpace());
288   if(state->getWordSpace())
289   bufpos+=sprintf(bufpos,"WS%.5f ", state->getWordSpace());
290   if(state->getHorizScaling()!=1.0)
291   bufpos+=sprintf(bufpos,"SC%.1f ", state->getHorizScaling());
292   if(state->getLeading())
293   bufpos+=sprintf(bufpos,"L%.1f ", state->getLeading());
294   if(state->getRise())
295   bufpos+=sprintf(bufpos,"R%.1f ", state->getRise());
296   if(state->getRender())
297   bufpos+=sprintf(bufpos,"R%d ", state->getRender());
298   bufpos+=sprintf(bufpos,"P%08x ", state->getPath());
299   bufpos+=sprintf(bufpos,"CX%.1f ", state->getCurX());
300   bufpos+=sprintf(bufpos,"CY%.1f ", state->getCurY());
301   if(state->getLineX())
302   bufpos+=sprintf(bufpos,"LX%.1f ", state->getLineX());
303   if(state->getLineY())
304   bufpos+=sprintf(bufpos,"LY%.1f ", state->getLineY());
305   bufpos+=sprintf(bufpos," ");
306   return mybuf;
307 }
308
309 void dumpFontInfo(char*loglevel, GfxFont*font);
310 int lastdumps[1024];
311 int lastdumppos = 0;
312 /* nr = 0  unknown
313    nr = 1  substituting
314    nr = 2  type 3
315  */
316 void showFontError(GfxFont*font, int nr) 
317 {  
318     Ref r=font->getID();
319     int t;
320     for(t=0;t<lastdumppos;t++)
321         if(lastdumps[t] == r.num)
322             break;
323     if(t < lastdumppos)
324       return;
325     if(lastdumppos<sizeof(lastdumps)/sizeof(int))
326     lastdumps[lastdumppos++] = r.num;
327     if(nr == 0)
328       logf("<warning> The following font caused problems:");
329     else if(nr == 1)
330       logf("<warning> The following font caused problems (substituting):");
331     else if(nr == 2)
332       logf("<warning> This document contains Type 3 Fonts: (some text may be incorrectly displayed)");
333
334     dumpFontInfo("<warning>", font);
335 }
336
337 void dumpFontInfo(char*loglevel, GfxFont*font)
338 {
339   GString *gstr;
340   char*name;
341   gstr = font->getName();
342   Ref r=font->getID();
343   logf("%s=========== %s (ID:%d,%d) ==========\n", loglevel, gstr?gstr->getCString():"(unknown font)", r.num,r.gen);
344
345   gstr  = font->getTag();
346   if(gstr) 
347    logf("%sTag: %s\n", loglevel, gstr->getCString());
348   if(font->is16Bit()) logf("%sis 16 bit\n", loglevel);
349
350   GfxFontType type=font->getType();
351   switch(type) {
352     case fontUnknownType:
353      logf("%sType: unknown\n",loglevel);
354     break;
355     case fontType0:
356      logf("%sType: 0\n",loglevel);
357     break;
358     case fontType1:
359      logf("%sType: 1\n",loglevel);
360     break;
361     case fontType1C:
362      logf("%sType: 1C\n",loglevel);
363     break;
364     case fontType3:
365      logf("%sType: 3\n",loglevel);
366     break;
367     case fontTrueType:
368      logf("%sType: TrueType\n",loglevel);
369     break;
370   }
371   
372   Ref embRef;
373   GBool embedded = font->getEmbeddedFontID(&embRef);
374   name = font->getEmbeddedFontName();
375   if(embedded)
376    logf("%sEmbedded name: %s id: %d\n",loglevel, name, embRef.num);
377
378   gstr = font->getExtFontFile();
379   if(gstr)
380    logf("%sExternal Font file: %s\n", loglevel, gstr->getCString());
381
382   // Get font descriptor flags.
383   if(font->isFixedWidth()) logf("%sis fixed width\n", loglevel);
384   if(font->isSerif()) logf("%sis serif\n", loglevel);
385   if(font->isSymbolic()) logf("%sis symbolic\n", loglevel);
386   if(font->isItalic()) logf("%sis italic\n", loglevel);
387   if(font->isBold()) logf("%sis bold\n", loglevel);
388 }
389
390 //void SWFOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str, int width, int height, GBool invert, GBool inlineImg) {printf("void SWFOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str, int width, int height, GBool invert, GBool inlineImg) \n");}
391 //void SWFOutputDev::drawImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, GBool inlineImg) {printf("void SWFOutputDev::drawImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, GBool inlineImg) \n");}
392
393 SWFOutputDev::SWFOutputDev() 
394 {
395     jpeginfo = 0;
396     linkinfo = 0;
397     pbminfo = 0;
398     clippos = 0;
399     clipping[clippos] = 0;
400     outputstarted = 0;
401 //    printf("SWFOutputDev::SWFOutputDev() \n");
402 };
403
404 T1_OUTLINE* gfxPath_to_T1_OUTLINE(GfxState*state, GfxPath*path)
405 {
406     int num = path->getNumSubpaths();
407     int s,t;
408     bezierpathsegment*start,*last;
409     bezierpathsegment*outline = start = new bezierpathsegment();
410     int cpos = 0;
411     double lastx=0,lasty=0;
412     for(t = 0; t < num; t++) {
413         GfxSubpath *subpath = path->getSubpath(t);
414         int subnum = subpath->getNumPoints();
415
416         for(s=0;s<subnum;s++) {
417            double nx,ny;
418            state->transform(subpath->getX(s),subpath->getY(s),&nx,&ny);
419            int x = (int)((nx-lastx)*0xffff);
420            int y = (int)((ny-lasty)*0xffff);
421            if(s==0) 
422            {
423                 last = outline;
424                 outline->type = T1_PATHTYPE_MOVE;
425                 outline->dest.x = x;
426                 outline->dest.y = y;
427                 outline->link = (T1_OUTLINE*)new bezierpathsegment();
428                 outline = (bezierpathsegment*)outline->link;
429                 cpos = 0;
430                 lastx = nx;
431                 lasty = ny;
432            }
433            else if(subpath->getCurve(s) && !cpos)
434            {
435                 outline->B.x = x;
436                 outline->B.y = y;
437                 cpos = 1;
438            } 
439            else if(subpath->getCurve(s) && cpos)
440            {
441                 outline->C.x = x;
442                 outline->C.y = y;
443                 cpos = 2;
444            }
445            else
446            {
447                 last = outline;
448                 outline->dest.x = x;
449                 outline->dest.y = y;
450                 outline->type = cpos?T1_PATHTYPE_BEZIER:T1_PATHTYPE_LINE;
451                 outline->link = 0;
452                 outline->link = (T1_OUTLINE*)new bezierpathsegment();
453                 outline = (bezierpathsegment*)outline->link;
454                 cpos = 0;
455                 lastx = nx;
456                 lasty = ny;
457            }
458         }
459     }
460     last->link = 0;
461     return (T1_OUTLINE*)start;
462 }
463 /*----------------------------------------------------------------------------
464  * Primitive Graphic routines
465  *----------------------------------------------------------------------------*/
466
467 void SWFOutputDev::stroke(GfxState *state) 
468 {
469     logf("<debug> stroke\n");
470     GfxPath * path = state->getPath();
471     struct swfmatrix m;
472     m.m11 = 1; m.m21 = 0; m.m22 = 1;
473     m.m12 = 0; m.m13 = 0; m.m23 = 0;
474     T1_OUTLINE*outline = gfxPath_to_T1_OUTLINE(state, path);
475     swfoutput_setdrawmode(&output, DRAWMODE_STROKE);
476     swfoutput_drawpath(&output, outline, &m);
477 }
478 void SWFOutputDev::fill(GfxState *state) 
479 {
480     logf("<debug> fill\n");
481     GfxPath * path = state->getPath();
482     struct swfmatrix m;
483     m.m11 = 1; m.m21 = 0; m.m22 = 1;
484     m.m12 = 0; m.m13 = 0; m.m23 = 0;
485     T1_OUTLINE*outline = gfxPath_to_T1_OUTLINE(state, path);
486     swfoutput_setdrawmode(&output, DRAWMODE_FILL);
487     swfoutput_drawpath(&output, outline, &m);
488 }
489 void SWFOutputDev::eoFill(GfxState *state) 
490 {
491     logf("<debug> eofill\n");
492     GfxPath * path = state->getPath();
493     struct swfmatrix m;
494     m.m11 = 1; m.m21 = 0; m.m22 = 1;
495     m.m12 = 0; m.m13 = 0; m.m23 = 0;
496     T1_OUTLINE*outline = gfxPath_to_T1_OUTLINE(state, path);
497     swfoutput_setdrawmode(&output, DRAWMODE_EOFILL);
498     swfoutput_drawpath(&output, outline, &m);
499 }
500 void SWFOutputDev::clip(GfxState *state) 
501 {
502     logf("<debug> clip\n");
503     GfxPath * path = state->getPath();
504     struct swfmatrix m;
505     m.m11 = 1; m.m22 = 1;
506     m.m12 = 0; m.m21 = 0; 
507     m.m13 = 0; m.m23 = 0;
508     T1_OUTLINE*outline = gfxPath_to_T1_OUTLINE(state, path);
509     swfoutput_startclip(&output, outline, &m);
510     clipping[clippos] ++;
511 }
512 void SWFOutputDev::eoClip(GfxState *state) 
513 {
514     logf("<debug> eoclip\n");
515     GfxPath * path = state->getPath();
516     struct swfmatrix m;
517     m.m11 = 1; m.m21 = 0; m.m22 = 1;
518     m.m12 = 0; m.m13 = 0; m.m23 = 0;
519     T1_OUTLINE*outline = gfxPath_to_T1_OUTLINE(state, path);
520     swfoutput_startclip(&output, outline, &m);
521     clipping[clippos] ++;
522 }
523
524 SWFOutputDev::~SWFOutputDev() 
525 {
526     swfoutput_destroy(&output);
527     outputstarted = 0;
528 };
529 GBool SWFOutputDev::upsideDown() 
530 {
531     logf("<debug> upsidedown?");
532     return gTrue;
533 };
534 GBool SWFOutputDev::useDrawChar() 
535 {
536     logf("<debug> usedrawchar?");
537     return gTrue;
538 }
539
540 void SWFOutputDev::beginString(GfxState *state, GString *s) 
541
542     double m11,m21,m12,m22;
543 //    logf("<debug> %s beginstring \"%s\"\n", gfxstate2str(state), s->getCString());
544     state->getFontTransMat(&m11, &m12, &m21, &m22);
545     m11 *= state->getHorizScaling();
546     m21 *= state->getHorizScaling();
547     swfoutput_setfontmatrix(&output, m11, -m12, m21, -m22);
548 }
549
550 int charcounter = 0;
551 void SWFOutputDev::drawChar(GfxState *state, double x, double y, double dx, double dy, Guchar c) 
552 {
553     logf("<debug> drawChar(%f,%f,%f,%f,'%c')\n",x,y,dx,dy,c);
554     // check for invisible text -- this is used by Acrobat Capture
555     if ((state->getRender() & 3) != 3)
556     {
557        FontEncoding*enc=state->getFont()->getEncoding();
558
559        double x1,y1;
560        x1 = x;
561        y1 = y;
562        state->transform(x, y, &x1, &y1);
563
564        if(enc->getCharName(c))
565           swfoutput_drawchar(&output, x1, y1, enc->getCharName(c));
566        else
567           logf("<warning> couldn't get name for character %02x from Encoding", c);
568     }
569 }
570
571 void SWFOutputDev::drawChar16(GfxState *state, double x, double y, double dx, double dy, int c) 
572 {
573     printf("<error> drawChar16(%f,%f,%f,%f,%08x)\n",x,y,dx,dy,c);
574     exit(1);
575 }
576
577 void SWFOutputDev::endString(GfxState *state) 
578
579     logf("<debug> endstring\n");
580 }    
581
582 void SWFOutputDev::startPage(int pageNum, GfxState *state) 
583 {
584   double x1,y1,x2,y2;
585   laststate = state;
586   logf("<debug> startPage %d\n", pageNum);
587   logf("<notice> processing page %d", pageNum);
588
589   state->transform(state->getX1(),state->getY1(),&x1,&y1);
590   state->transform(state->getX2(),state->getY2(),&x2,&y2);
591   if(!outputstarted) {
592     swfoutput_init(&output, swffilename, abs((int)(x2-x1)),abs((int)(y2-y1)));
593     outputstarted = 1;
594   }
595   else
596     swfoutput_newpage(&output);
597 }
598
599 void SWFOutputDev::drawLink(Link *link, Catalog *catalog) 
600 {
601   double x1, y1, x2, y2, w;
602   GfxRGB rgb;
603   swfcoord points[5];
604   int x, y;
605
606   link->getBorder(&x1, &y1, &x2, &y2, &w);
607 //  if (w > 0) 
608   {
609     rgb.r = 0;
610     rgb.g = 0;
611     rgb.b = 1;
612     cvtUserToDev(x1, y1, &x, &y);
613     points[0].x = points[4].x = (int)x;
614     points[0].y = points[4].y = (int)y;
615     cvtUserToDev(x2, y1, &x, &y);
616     points[1].x = (int)x;
617     points[1].y = (int)y;
618     cvtUserToDev(x2, y2, &x, &y);
619     points[2].x = (int)x;
620     points[2].y = (int)y;
621     cvtUserToDev(x1, y2, &x, &y);
622     points[3].x = (int)x;
623     points[3].y = (int)y;
624
625     LinkAction*action=link->getAction();
626     char buf[128];
627     char*s = "-?-";
628     char*type = "-?-";
629     char*url = 0;
630     int page = -1;
631     switch(action->getKind())
632     {
633         case actionGoTo: {
634             type = "GoTo";
635             LinkGoTo *ha=(LinkGoTo *)link->getAction();
636             LinkDest *dest=NULL;
637             if (ha->getDest()==NULL) 
638                 dest=catalog->findDest(ha->getNamedDest());
639             else dest=ha->getDest();
640             if (dest){ 
641               if (dest->isPageRef()){
642                 Ref pageref=dest->getPageRef();
643                 page=catalog->findPage(pageref.num,pageref.gen);
644               }
645               else  page=dest->getPageNum();
646               sprintf(buf, "%d", page);
647               s = buf;
648             }
649         }
650         break;
651         case actionGoToR: {
652             type = "GoToR";
653             LinkGoToR*l = (LinkGoToR*)action;
654             GString*g = l->getNamedDest();
655             if(g)
656              s = g->getCString();
657         }
658         break;
659         case actionNamed: {
660             type = "Named";
661             LinkNamed*l = (LinkNamed*)action;
662             GString*name = l->getName();
663             if(name) {
664               s = name->lowerCase()->getCString();
665               if(strstr(s, "next") || strstr(s, "forward"))
666               {
667                   page = currentpage + 1;
668               }
669               else if(strstr(s, "prev") || strstr(s, "back"))
670               {
671                   page = currentpage - 1;
672               }
673               else if(strstr(s, "last") || strstr(s, "end"))
674               {
675                   page = pages[pagepos-1]; //:)
676               }
677               else if(strstr(s, "first") || strstr(s, "top"))
678               {
679                   page = 1;
680               }
681             }
682         }
683         break;
684         case actionLaunch: {
685             type = "Launch";
686             LinkLaunch*l = (LinkLaunch*)action;
687             GString * str = new GString(l->getFileName());
688             str->append(l->getParams());
689             s = str->getCString();
690         }
691         break;
692         case actionURI: {
693             type = "URI";
694             LinkURI*l = (LinkURI*)action;
695             GString*g = l->getURI();
696             if(g) {
697              url = g->getCString();
698              s = url;
699             }
700         }
701         break;
702         case actionUnknown: {
703             type = "Unknown";
704             LinkUnknown*l = (LinkUnknown*)action;
705             s = "";
706         }
707         break;
708         default: {
709             logf("<error> Unknown link type!\n");
710             break;
711         }
712     }
713     if(!linkinfo && (page || url))
714     {
715         logf("<notice> File contains links");
716         linkinfo = 1;
717     }
718     if(page>0)
719     {
720         int t;
721         for(t=0;t<pagepos;t++)
722             if(pages[t]==page)
723                 break;
724         if(t!=pagepos)
725         swfoutput_linktopage(&output, t, points);
726     }
727     else if(url)
728     {
729         swfoutput_linktourl(&output, url, points);
730     }
731     logf("<verbose> \"%s\" link to \"%s\" (%d)\n", type, s, page);
732   }
733 }
734
735 void SWFOutputDev::saveState(GfxState *state) {
736   logf("<debug> saveState\n");
737   updateAll(state);
738   if(clippos<64)
739     clippos ++;
740   else
741     logf("<error> Too many nested states in pdf.");
742   clipping[clippos] = 0;
743 };
744
745 void SWFOutputDev::restoreState(GfxState *state) {
746   logf("<debug> restoreState\n");
747   updateAll(state);
748   while(clipping[clippos]) {
749       swfoutput_endclip(&output);
750       clipping[clippos]--;
751   }
752   clippos--;
753 }
754
755 char type3Warning=0;
756
757 int SWFOutputDev::setT1Font(char*name, FontEncoding*encoding) 
758 {       
759     int i;
760     
761     int id=-1;
762     int mapid=-1;
763     char*filename=0;
764     for(i=0;i<sizeof(pdf2t1map)/sizeof(mapping);i++) 
765     {
766         if(!strcmp(name, pdf2t1map[i].pdffont))
767         {
768             filename = pdf2t1map[i].filename;
769             mapid = i;
770         }
771     }
772     if(filename)
773     for(i=0; i<T1_Get_no_fonts(); i++)
774     {
775         char*fontfilename = T1_GetFontFileName (i);
776         if(strstr(fontfilename, filename))
777         {
778                 id = i;
779                 pdf2t1map[i].id = mapid;
780         }
781     }
782     if(id<0)
783      return 0;
784
785     this->t1id = id;
786     return 1;
787 }
788
789 void SWFOutputDev::updateLineWidth(GfxState *state)
790 {
791     double width = state->getTransformedLineWidth();
792     swfoutput_setlinewidth(&output, width);
793 }
794
795 void SWFOutputDev::updateFillColor(GfxState *state) 
796 {
797     GfxRGB rgb;
798     double opaq = state->getFillOpacity();
799     state->getFillRGB(&rgb);
800
801     swfoutput_setfillcolor(&output, (char)(rgb.r*255), (char)(rgb.g*255), 
802                                     (char)(rgb.b*255), (char)(opaq*255));
803 }
804
805 void SWFOutputDev::updateStrokeColor(GfxState *state) 
806 {
807     GfxRGB rgb;
808     double opaq = state->getStrokeOpacity();
809     state->getStrokeRGB(&rgb);
810
811     swfoutput_setstrokecolor(&output, (char)(rgb.r*255), (char)(rgb.g*255), 
812                                       (char)(rgb.b*255), (char)(opaq*255));
813 }
814
815 char*writeEmbeddedFontToFile(GfxFont*font)
816 {
817       char*tmpFileName = NULL;
818       char*fileName = NULL;
819       FILE *f;
820       int c;
821       char *fontBuf;
822       int fontLen;
823       Type1CFontConverter *cvt;
824       Ref embRef;
825       Object refObj, strObj;
826       tmpFileName = "/tmp/tmpfont";
827       font->getEmbeddedFontID(&embRef);
828
829       f = fopen(tmpFileName, "wb");
830       if (!f) {
831         logf("<error> Couldn't create temporary Type 1 font file");
832         return 0;
833       }
834       if (font->getType() == fontType1C) {
835         if (!(fontBuf = font->readEmbFontFile(&fontLen))) {
836           fclose(f);
837           logf("<error> Couldn't read embedded font file");
838           return 0;
839         }
840         cvt = new Type1CFontConverter(fontBuf, fontLen, f);
841         cvt->convert();
842         delete cvt;
843         gfree(fontBuf);
844       } else {
845         font->getEmbeddedFontID(&embRef);
846         refObj.initRef(embRef.num, embRef.gen);
847         refObj.fetch(&strObj);
848         refObj.free();
849         strObj.streamReset();
850         while ((c = strObj.streamGetChar()) != EOF) {
851           fputc(c, f);
852         }
853         strObj.streamClose();
854         strObj.free();
855       }
856       fclose(f);
857       fileName = tmpFileName;
858       if(!fileName) {
859           logf("<error> Embedded font writer didn't create a file");
860           return 0;
861       }
862       return fileName;
863 }
864
865 char* gfxFontName(GfxFont* gfxFont)
866 {
867       GString *gstr;
868       gstr = gfxFont->getName();
869       if(gstr) {
870           return gstr->getCString();
871       }
872       else {
873           char buf[32];
874           Ref r=gfxFont->getID();
875           sprintf(buf, "UFONT%d", r.num);
876           return strdup(buf);
877       }
878 }
879
880 char* SWFOutputDev::substitutefont(GfxFont*gfxFont)
881 {
882       //substitute font
883       char* fontname = 0;
884       double m11, m12, m21, m22;
885       int index;
886       int code;
887       double w,w1,w2;
888       double*fm;
889       double v;
890       if(gfxFont->getName()) {
891         fontname = gfxFont->getName()->getCString();
892       }
893
894 //        printf("%d %s\n", t, gfxFont->getCharName(t));
895       showFontError(gfxFont, 1);
896       if (!gfxFont->is16Bit()) {
897         if(gfxFont->isSymbolic()) {
898           if(fontname && (strstr(fontname,"ing"))) //Dingbats, Wingdings etc.
899            index = 16;
900           else 
901            index = 12;
902         } else if (gfxFont->isFixedWidth()) {
903           index = 8;
904         } else if (gfxFont->isSerif()) {
905           index = 4;
906         } else {
907           index = 0;
908         }
909         if (gfxFont->isBold() && index!=16)
910           index += 2;
911         if (gfxFont->isItalic() && index!=16)
912           index += 1;
913         fontname = fontnames[index];
914         // get width of 'm' in real font and substituted font
915         if ((code = gfxFont->getCharCode("m")) >= 0)
916           w1 = gfxFont->getWidth(code);
917         else
918           w1 = 0;
919         w2 = fontsizes[index];
920         if (gfxFont->getType() == fontType3) {
921           // This is a hack which makes it possible to substitute for some
922           // Type 3 fonts.  The problem is that it's impossible to know what
923           // the base coordinate system used in the font is without actually
924           // rendering the font.  This code tries to guess by looking at the
925           // width of the character 'm' (which breaks if the font is a
926           // subset that doesn't contain 'm').
927           if (w1 > 0 && (w1 > 1.1 * w2 || w1 < 0.9 * w2)) {
928             w1 /= w2;
929             m11 *= w1;
930             m12 *= w1;
931             m21 *= w1;
932             m22 *= w1;
933           }
934           fm = gfxFont->getFontMatrix();
935           v = (fm[0] == 0) ? 1 : (fm[3] / fm[0]);
936           m21 *= v;
937           m22 *= v;
938         } else if (!gfxFont->isSymbolic()) {
939           // if real font is substantially narrower than substituted
940           // font, reduce the font size accordingly
941           if (w1 > 0.01 && w1 < 0.9 * w2) {
942             w1 /= w2;
943             if (w1 < 0.8) {
944               w1 = 0.8;
945             }
946             m11 *= w1;
947             m12 *= w1;
948             m21 *= w1;
949             m22 *= w1;
950           }
951         }
952       }
953       if(fontname)
954         setT1Font(fontname, gfxFont->getEncoding());
955       return fontname;
956 }
957
958 void SWFOutputDev::updateFont(GfxState *state) 
959 {
960   char * fontname = 0;
961   GfxFont*gfxFont = state->getFont();
962   char * fileName = 0;
963     
964   if (!gfxFont) {
965     return;
966   }  
967   
968   if(gfxFont->getName()) {
969     fontname = gfxFont->getName()->getCString();
970   }
971
972   if(swfoutput_queryfont(&output, gfxFontName(gfxFont)))
973   {
974       swfoutput_setfont(&output, gfxFontName(gfxFont), -1, 0);
975       return;
976   }
977
978   // look for Type 3 font
979   if (!type3Warning && gfxFont->getType() == fontType3) {
980     type3Warning = gTrue;
981     showFontError(gfxFont, 2);
982   }
983   //dumpFontInfo ("<notice>", gfxFont);
984
985   Ref embRef;
986   GBool embedded = gfxFont->getEmbeddedFontID(&embRef);
987   if(embedded) {
988     if (!gfxFont->is16Bit() &&
989         (gfxFont->getType() == fontType1 ||
990          gfxFont->getType() == fontType1C)) {
991         
992         fileName = writeEmbeddedFontToFile(gfxFont);
993         if(!fileName)
994           return ;
995         this->t1id = T1_AddFont(fileName);
996     }
997     else {
998         showFontError(gfxFont,0);
999         fontname = substitutefont(gfxFont);
1000     }
1001   } else {
1002     if(!fontname || !setT1Font(state->getFont()->getName()->getCString(), gfxFont->getEncoding()))
1003         fontname = substitutefont(gfxFont);
1004   }
1005
1006   swfoutput_setfont(&output,gfxFontName(gfxFont),this->t1id, fileName);
1007   if(fileName)
1008       unlink(fileName);
1009 }
1010
1011 int pic_xids[1024];
1012 int pic_yids[1024];
1013 int pic_ids[1024];
1014 int picpos = 0;
1015 int pic_id = 0;
1016
1017 void SWFOutputDev::drawGeneralImage(GfxState *state, Object *ref, Stream *str,
1018                                    int width, int height, GfxImageColorMap*colorMap, GBool invert,
1019                                    GBool inlineImg, int mask)
1020 {
1021   FILE *fi;
1022   int c;
1023   char fileName[128];
1024   double x1,y1,x2,y2,x3,y3,x4,y4;
1025   ImageStream *imgStr;
1026   Guchar pixBuf[4];
1027   GfxRGB rgb;
1028   if(!width || !height || (height<=1 && width<=1))
1029   {
1030       logf("<verbose> Ignoring %d by %d image", width, height);
1031       int i,j;
1032       if (inlineImg) {
1033         j = height * ((width + 7) / 8);
1034         str->reset();
1035         for (i = 0; i < j; ++i) {
1036           str->getChar();
1037         }
1038       }
1039       return;
1040   }
1041   
1042   state->transform(0, 1, &x1, &y1);
1043   state->transform(0, 0, &x2, &y2);
1044   state->transform(1, 0, &x3, &y3);
1045   state->transform(1, 1, &x4, &y4);
1046
1047   if (str->getKind() == strDCT &&
1048       (colorMap->getNumPixelComps() == 3 || !mask) )
1049   {
1050     sprintf(fileName, "/tmp/tmp%08x.jpg",lrand48());
1051     logf("<verbose> Found jpeg. Temporary storage is %s", fileName);
1052     if(!jpeginfo)
1053     {
1054         logf("<notice> file contains jpeg pictures");
1055         jpeginfo = 1;
1056     }
1057     if (!(fi = fopen(fileName, "wb"))) {
1058       logf("<error> Couldn't open temporary image file '%s'", fileName);
1059       return;
1060     }
1061     str = ((DCTStream *)str)->getRawStream();
1062     str->reset();
1063     int xid = 0;
1064     int yid = 0;
1065     int count = 0;
1066     while ((c = str->getChar()) != EOF)
1067     {
1068       fputc(c, fi);
1069       xid += count*c;
1070       yid += (~count)*c;
1071       count++;
1072     }
1073     fclose(fi);
1074     
1075     int t,found = -1;
1076     for(t=0;t<picpos;t++)
1077     {
1078         if(pic_xids[t] == xid &&
1079            pic_yids[t] == yid) {
1080             found = t;break;
1081         }
1082     }
1083     if(found<0) {
1084         pic_ids[picpos] = swfoutput_drawimagejpeg(&output, fileName, width, height, 
1085                 x1,y1,x2,y2,x3,y3,x4,y4);
1086         pic_xids[picpos] = xid;
1087         pic_yids[picpos] = yid;
1088         if(picpos<1024)
1089             picpos++;
1090     } else {
1091         swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1092                 x1,y1,x2,y2,x3,y3,x4,y4);
1093     }
1094     unlink(fileName);
1095   } else {
1096
1097     if(!pbminfo) {
1098         logf("<notice> file contains pbm pictures %s",mask?"(masked)":"");
1099         if(mask)
1100         logf("<verbose> drawing %d by %d masked picture\n", width, height);
1101         pbminfo = 1;
1102     }
1103
1104     if(mask) {
1105         imgStr = new ImageStream(str, width, 1, 1);
1106         imgStr->reset();
1107         return;
1108         int yes=0,i,j;
1109         unsigned char buf[8];
1110         int xid = 0;
1111         int yid = 0;
1112         int x,y;
1113         int width2 = (width+3)&(~3);
1114         unsigned char*pic = new unsigned char[width2*height];
1115         RGBA pal[256];
1116         GfxRGB rgb;
1117         state->getFillRGB(&rgb);
1118         pal[0].r = (int)(rgb.r*255); pal[0].g = (int)(rgb.g*255); 
1119         pal[0].b = (int)(rgb.b*255); pal[0].a = 255;
1120         pal[1].r = 0; pal[1].g = 0; pal[1].b = 0; pal[1].a = 0;
1121         xid += pal[1].r*3 + pal[1].g*11 + pal[1].b*17;
1122         yid += pal[1].r*7 + pal[1].g*5 + pal[1].b*23;
1123         for (y = 0; y < height; ++y)
1124         for (x = 0; x < width; ++x)
1125         {
1126               imgStr->getPixel(buf);
1127               pic[width*y+x] = buf[0];
1128               xid+=x*buf[0]+1;
1129               yid+=y*buf[0]+1;
1130         }
1131         int t,found = -1;
1132         for(t=0;t<picpos;t++)
1133         {
1134             if(pic_xids[t] == xid &&
1135                pic_yids[t] == yid) {
1136                 found = t;break;
1137             }
1138         }
1139         if(found<0) {
1140             pic_ids[picpos] = swfoutput_drawimagelossless256(&output, pic, pal, width, height, 
1141                     x1,y1,x2,y2,x3,y3,x4,y4);
1142             pic_xids[picpos] = xid;
1143             pic_yids[picpos] = yid;
1144             if(picpos<1024)
1145                 picpos++;
1146         } else {
1147             swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1148                     x1,y1,x2,y2,x3,y3,x4,y4);
1149         }
1150         free(pic);
1151     } else {
1152         int x,y;
1153         int width2 = (width+3)&(~3);
1154         imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(),
1155                                    colorMap->getBits());
1156         imgStr->reset();
1157
1158         if(colorMap->getNumPixelComps()!=1)
1159         {
1160             RGBA*pic=new RGBA[width*height];
1161             int xid = 0;
1162             int yid = 0;
1163             for (y = 0; y < height; ++y) {
1164               for (x = 0; x < width; ++x) {
1165                 int r,g,b,a;
1166                 imgStr->getPixel(pixBuf);
1167                 colorMap->getRGB(pixBuf, &rgb);
1168                 pic[width*y+x].r = r = (U8)(rgb.r * 255 + 0.5);
1169                 pic[width*y+x].g = g = (U8)(rgb.g * 255 + 0.5);
1170                 pic[width*y+x].b = b = (U8)(rgb.b * 255 + 0.5);
1171                 pic[width*y+x].a = a = 255;//(U8)(rgb.a * 255 + 0.5);
1172                 xid += x*r+x*b*3+x*g*7+x*a*11;
1173                 yid += y*r*3+y*b*17+y*g*19+y*a*11;
1174               }
1175             }
1176             int t,found = -1;
1177             for(t=0;t<picpos;t++)
1178             {
1179                 if(pic_xids[t] == xid &&
1180                    pic_yids[t] == yid) {
1181                     found = t;break;
1182                 }
1183             }
1184             if(found<0) {
1185                 pic_ids[picpos] = swfoutput_drawimagelossless(&output, pic, width, height, 
1186                         x1,y1,x2,y2,x3,y3,x4,y4);
1187                 pic_xids[picpos] = xid;
1188                 pic_yids[picpos] = yid;
1189                 if(picpos<1024)
1190                     picpos++;
1191             } else {
1192                 swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1193                         x1,y1,x2,y2,x3,y3,x4,y4);
1194             }
1195             delete pic;
1196         }
1197         else
1198         {
1199             U8*pic = new U8[width2*height];
1200             RGBA pal[256];
1201             int t;
1202             int xid=0,yid=0;
1203             for(t=0;t<256;t++)
1204             {
1205                 int r,g,b,a;
1206                 pixBuf[0] = t;
1207                 colorMap->getRGB(pixBuf, &rgb);
1208                 pal[t].r = r = (U8)(rgb.r * 255 + 0.5);
1209                 pal[t].g = g = (U8)(rgb.g * 255 + 0.5);
1210                 pal[t].b = b = (U8)(rgb.b * 255 + 0.5);
1211                 pal[t].a = a = 255;//(U8)(rgb.b * 255 + 0.5);
1212                 xid += t*r+t*b*3+t*g*7+t*a*11;
1213                 xid += (~t)*r+t*b*3+t*g*7+t*a*11;
1214             }
1215             for (y = 0; y < height; ++y) {
1216               for (x = 0; x < width; ++x) {
1217                 imgStr->getPixel(pixBuf);
1218                 pic[width2*y+x] = pixBuf[0];
1219                 xid += x*pixBuf[0]*7;
1220                 yid += y*pixBuf[0]*3;
1221               }
1222             }
1223             int found = -1;
1224             for(t=0;t<picpos;t++)
1225             {
1226                 if(pic_xids[t] == xid &&
1227                    pic_yids[t] == yid) {
1228                     found = t;break;
1229                 }
1230             }
1231             if(found<0) {
1232                 pic_ids[picpos] = swfoutput_drawimagelossless256(&output, pic, pal, width, height, 
1233                         x1,y1,x2,y2,x3,y3,x4,y4);
1234                 pic_xids[picpos] = xid;
1235                 pic_yids[picpos] = yid;
1236                 if(picpos<1024)
1237                     picpos++;
1238             } else {
1239                 swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1240                         x1,y1,x2,y2,x3,y3,x4,y4);
1241             }
1242             delete pic;
1243         }
1244         delete imgStr;
1245     }
1246
1247   }
1248 }
1249
1250 void SWFOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str,
1251                                    int width, int height, GBool invert,
1252                                    GBool inlineImg) 
1253 {
1254   drawGeneralImage(state,ref,str,width,height,0,invert,inlineImg,1);
1255 }
1256
1257 void SWFOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
1258                                int width, int height,
1259                                GfxImageColorMap *colorMap, GBool inlineImg) 
1260 {
1261   drawGeneralImage(state,ref,str,width,height,colorMap,0,inlineImg,0);
1262 }
1263
1264 SWFOutputDev*output = 0; 
1265
1266 static void printInfoString(Dict *infoDict, char *key, char *fmt) {
1267   Object obj;
1268   GString *s1, *s2;
1269   int i;
1270
1271   if (infoDict->lookup(key, &obj)->isString()) {
1272     s1 = obj.getString();
1273     if ((s1->getChar(0) & 0xff) == 0xfe &&
1274         (s1->getChar(1) & 0xff) == 0xff) {
1275       s2 = new GString();
1276       for (i = 2; i < obj.getString()->getLength(); i += 2) {
1277         if (s1->getChar(i) == '\0') {
1278           s2->append(s1->getChar(i+1));
1279         } else {
1280           delete s2;
1281           s2 = new GString("<unicode>");
1282           break;
1283         }
1284       }
1285       printf(fmt, s2->getCString());
1286       delete s2;
1287     } else {
1288       printf(fmt, s1->getCString());
1289     }
1290   }
1291   obj.free();
1292 }
1293
1294 static void printInfoDate(Dict *infoDict, char *key, char *fmt) {
1295   Object obj;
1296   char *s;
1297
1298   if (infoDict->lookup(key, &obj)->isString()) {
1299     s = obj.getString()->getCString();
1300     if (s[0] == 'D' && s[1] == ':') {
1301       s += 2;
1302     }
1303     printf(fmt, s);
1304   }
1305   obj.free();
1306 }
1307
1308 void pdfswf_init(char*filename, char*userPassword) 
1309 {
1310   GString *fileName = new GString(filename);
1311   GString *userPW;
1312   Object info;
1313   // init error file
1314   errorInit();
1315
1316   // read config file
1317   initParams(xpdfConfigFile);
1318
1319   // open PDF file
1320   xref = NULL;
1321   if (userPassword && userPassword[0]) {
1322     userPW = new GString(userPassword);
1323   } else {
1324     userPW = NULL;
1325   }
1326   doc = new PDFDoc(fileName, userPW);
1327   if (userPW) {
1328     delete userPW;
1329   }
1330   if (!doc->isOk()) {
1331     exit(1);
1332   }
1333
1334   // print doc info
1335   doc->getDocInfo(&info);
1336   if (info.isDict()) {
1337     printInfoString(info.getDict(), "Title",        "Title:        %s\n");
1338     printInfoString(info.getDict(), "Subject",      "Subject:      %s\n");
1339     printInfoString(info.getDict(), "Keywords",     "Keywords:     %s\n");
1340     printInfoString(info.getDict(), "Author",       "Author:       %s\n");
1341     printInfoString(info.getDict(), "Creator",      "Creator:      %s\n");
1342     printInfoString(info.getDict(), "Producer",     "Producer:     %s\n");
1343     printInfoDate(info.getDict(),   "CreationDate", "CreationDate: %s\n");
1344     printInfoDate(info.getDict(),   "ModDate",      "ModDate:      %s\n");
1345   }
1346   info.free();
1347
1348   // print page count
1349   printf("Pages:        %d\n", doc->getNumPages());
1350   numpages = doc->getNumPages();
1351   
1352   // print linearization info
1353   printf("Linearized:   %s\n", doc->isLinearized() ? "yes" : "no");
1354
1355   // print encryption info
1356   printf("Encrypted:    ");
1357   if (doc->isEncrypted()) {
1358     printf("yes (print:%s copy:%s change:%s addNotes:%s)\n",
1359            doc->okToPrint() ? "yes" : "no",
1360            doc->okToCopy() ? "yes" : "no",
1361            doc->okToChange() ? "yes" : "no",
1362            doc->okToAddNotes() ? "yes" : "no");
1363         /*ERROR: This pdf is encrypted, and disallows copying.
1364           Due to the DMCA, paragraph 1201, (2) A-C, circumventing
1365           a technological measure that efficively controls access to
1366           a protected work is violating American law. 
1367           See www.eff.org for more information about DMCA issues.
1368          */
1369         if(!doc->okToCopy()) {
1370             printf("PDF disallows copying. Bailing out.\n");
1371             exit(1); //bail out
1372         }
1373         if(!doc->okToChange() || !doc->okToAddNotes())
1374             swfoutput_setprotected();
1375     }
1376   else {
1377     printf("no\n");
1378   }
1379
1380
1381   output = new SWFOutputDev();
1382 }
1383
1384 void pdfswf_drawonlyshapes()
1385 {
1386     drawonlyshapes = 1;
1387 }
1388
1389 void pdfswf_ignoredraworder()
1390 {
1391     ignoredraworder = 1;
1392 }
1393
1394 void pdfswf_linksopennewwindow()
1395 {
1396     opennewwindow = 1;
1397 }
1398
1399 void pdfswf_storeallcharacters()
1400 {
1401     storeallcharacters = 1;
1402 }
1403
1404 void pdfswf_jpegquality(int val)
1405 {
1406     if(val<0) val=0;
1407     if(val>100) val=100;
1408     jpegquality = val;
1409 }
1410
1411 void pdfswf_setoutputfilename(char*_filename)
1412 {
1413     swffilename = _filename;
1414 }
1415
1416
1417 void pdfswf_convertpage(int page)
1418 {
1419     if(!pages)
1420     {
1421         pages = (int*)malloc(1024*sizeof(int));
1422         pagebuflen = 1024;
1423     } else {
1424         if(pagepos == pagebuflen)
1425         {
1426             pagebuflen+=1024;
1427             pages = (int*)realloc(pages, pagebuflen);
1428         }
1429     }
1430     pages[pagepos++] = page;
1431 }
1432
1433 void pdfswf_performconversion()
1434 {
1435     int t;
1436     for(t=0;t<pagepos;t++)
1437     {
1438        currentpage = pages[t];
1439        doc->displayPage((OutputDev*)output, currentpage, /*zoom*/100, /*rotate*/0, /*doLinks*/(int)1);
1440     }
1441 }
1442
1443 int pdfswf_numpages()
1444 {
1445   return doc->getNumPages();
1446 }
1447
1448 int closed=0;
1449 void pdfswf_close()
1450 {
1451     logf("<debug> pdfswf.cc: pdfswf_close()");
1452     delete output;
1453     delete doc;
1454     freeParams();
1455     // check for memory leaks
1456     Object::memCheck(stderr);
1457     gMemReport(stderr);
1458 }
1459