File: PdfFormXObject.cs

package info (click to toggle)
pdfmod 0.8.3-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 5,196 kB
  • ctags: 9,346
  • sloc: cs: 50,590; xml: 1,177; sh: 709; makefile: 640
file content (504 lines) | stat: -rw-r--r-- 17,414 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
//   Stefan Lange (mailto:Stefan.Lange@pdfsharp.com)
//
// Copyright (c) 2005-2008 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
#endregion

using System;
using System.Diagnostics;
using System.Collections;
using System.Text;
using System.IO;
#if GDI
using System.Drawing;
using System.Drawing.Imaging;
#endif
#if WPF
using System.Windows.Media;
#endif
using PdfSharp.Drawing;
using PdfSharp.Fonts.TrueType;
using PdfSharp.Internal;
using PdfSharp.Pdf.Internal;

namespace PdfSharp.Pdf.Advanced
{
  /// <summary>
  /// Represents an external form object (an imported page e.g).
  /// </summary>
  public sealed class PdfFormXObject : PdfXObject, IContentStream
  {
    internal PdfFormXObject(PdfDocument thisDocument)
      : base(thisDocument)
    {
      Elements.SetName(Keys.Type, "/XObject");
      Elements.SetName(Keys.Subtype, "/Form");
    }

    internal PdfFormXObject(PdfDocument thisDocument, XForm form)
      : base(thisDocument)
    {
      // BUG: form is not used
      Elements.SetName(Keys.Type, "/XObject");
      Elements.SetName(Keys.Subtype, "/Form");

      //if (form.IsTemplate)
      //{ }
    }

    internal double DpiX
    {
      get { return this.dpiX; }
      set { this.dpiX = value; }
    }
    double dpiX = 72;

    internal double DpiY
    {
      get { return this.dpiY; }
      set { this.dpiY = value; }
    }
    double dpiY = 72;

    internal PdfFormXObject(PdfDocument thisDocument, PdfImportedObjectTable importedObjectTable, XPdfForm form)
      : base(thisDocument)
    {
      Debug.Assert(Object.ReferenceEquals(thisDocument, importedObjectTable.Owner));
      Elements.SetName(Keys.Type, "/XObject");
      Elements.SetName(Keys.Subtype, "/Form");

      if (form.IsTemplate)
      {
        Debug.Assert(importedObjectTable == null);
        // TODO more initialization here???
        return;
      }
      Debug.Assert(importedObjectTable != null);

      XPdfForm pdfForm = (XPdfForm)form;
      // Get import page
      PdfPages importPages = importedObjectTable.ExternalDocument.Pages;
      if (pdfForm.PageNumber < 1 || pdfForm.PageNumber > importPages.Count)
        PSSR.ImportPageNumberOutOfRange(pdfForm.PageNumber, importPages.Count, form.path);
      PdfPage importPage = importPages[pdfForm.PageNumber - 1];

      // Import resources
      PdfItem res = importPage.Elements["/Resources"];
      if (res != null) // unlikely but possible
      {
#if true
        // Get root object
        PdfObject root;
        if (res is PdfReference)
          root = ((PdfReference)res).Value;
        else
          root = (PdfDictionary)res;

        root = ImportClosure(importedObjectTable, thisDocument, root);
        // If the root was a direct object, make it indirect.
        if (root.Reference == null)
          thisDocument.irefTable.Add(root);

        Debug.Assert(root.Reference != null);
        Elements["/Resources"] = root.Reference;
#else
        // Get transitive closure
        PdfObject[] resources = importPage.Owner.Internals.GetClosure(resourcesRoot);
        int count = resources.Length;
#if DEBUG_
        for (int idx = 0; idx < count; idx++)
        {
          Debug.Assert(resources[idx].XRef != null);
          Debug.Assert(resources[idx].XRef.Document != null);
          Debug.Assert(resources[idx].Document != null);
          if (resources[idx].ObjectID.ObjectNumber == 12)
            GetType();
        }
#endif
        // 1st step. Already imported objects are reused and new ones are cloned.
        for (int idx = 0; idx < count; idx++)
        {
          PdfObject obj = resources[idx];
          if (importedObjectTable.Contains(obj.ObjectID))
          {
            // external object was already imported
            PdfReference iref = importedObjectTable[obj.ObjectID];
            Debug.Assert(iref != null);
            Debug.Assert(iref.Value != null);
            Debug.Assert(iref.Document == this.Owner);
            // replace external object by the already clone counterpart
            resources[idx] = iref.Value;
          }
          else
          {
            // External object was not imported ealier and must be cloned
            PdfObject clone = obj.Clone();
            Debug.Assert(clone.Reference == null);
            clone.Document = this.Owner;
            if (obj.Reference != null)
            {
              // add it to this (the importer) document
              this.Owner.irefTable.Add(clone);
              Debug.Assert(clone.Reference != null);
              // save old object identifier
              importedObjectTable.Add(obj.ObjectID, clone.Reference);
              //Debug.WriteLine("Cloned: " + obj.ObjectID.ToString());
            }
            else
            {
              // The root object (the /Resources value) is not an indirect object
              Debug.Assert(idx == 0);
              // add it to this (the importer) document
              this.Owner.irefTable.Add(clone);
              Debug.Assert(clone.Reference != null);
            }
            // replace external object by its clone
            resources[idx] = clone;
          }
        }
#if DEBUG_
        for (int idx = 0; idx < count; idx++)
        {
          Debug.Assert(resources[idx].XRef != null);
          Debug.Assert(resources[idx].XRef.Document != null);
          Debug.Assert(resources[idx].Document != null);
          if (resources[idx].ObjectID.ObjectNumber == 12)
            GetType();
        }
#endif

        // 2nd step. Fix up indirect references that still refers to the import document.
        for (int idx = 0; idx < count; idx++)
        {
          PdfObject obj = resources[idx];
          Debug.Assert(obj.Owner != null);
          FixUpObject(importedObjectTable, importedObjectTable.Owner, obj);
        }

        // Set resources key to the root of the clones
        Elements["/Resources"] = resources[0].Reference;
#endif
      }

      // Take /Rotate into account
      PdfRectangle rect = importPage.Elements.GetRectangle(PdfPage.Keys.MediaBox);
      int rotate = importPage.Elements.GetInteger(PdfPage.Keys.Rotate);
      //rotate = 0;
      if (rotate == 0)
      {
        // Set bounding box to media box
        this.Elements["/BBox"] = rect;
      }
      else
      {
        // TODO: Have to adjust bounding box? (I think not, but I'm not sure -> wait for problem)
        this.Elements["/BBox"] = rect;

        // Rotate the image such that it is upright
        XMatrix matrix = XMatrix.Identity;
        double width = rect.Width;
        double height = rect.Height;
        matrix.RotateAtPrepend(-rotate, new XPoint(width / 2, height / 2));

        // Translate the image such that its center lies on the center of the rotated bounding box
        double offset = (height - width) / 2;
        if (height > width)
          matrix.TranslatePrepend(offset, offset);
        else
          matrix.TranslatePrepend(-offset, -offset);

        //string item = "[" + PdfEncoders.ToString(matrix) + "]";
        //Elements[Keys.Matrix] = new PdfLiteral(item);
        Elements.SetMatrix(Keys.Matrix, matrix);
      }

      // Preserve filter because the content keeps unmodified
      PdfContent content = importPage.Contents.CreateSingleContent();
#if !DEBUG
      content.Compressed = true;
#endif
      PdfItem filter = content.Elements["/Filter"];
      if (filter != null)
        this.Elements["/Filter"] = filter.Clone();

      // (no cloning needed because the bytes keep untouched)
      this.Stream = content.Stream; // new PdfStream(bytes, this);
      Elements.SetInteger("/Length", content.Stream.Value.Length);
    }

    internal PdfResources Resources
    {
      get
      {
        if (this.resources == null)
          this.resources = (PdfResources)Elements.GetValue(PdfFormXObject.Keys.Resources, VCF.Create);
        return this.resources;
      }
    }
    PdfResources resources;

    PdfResources IContentStream.Resources
    {
      get { return Resources; }
    }

    internal string GetFontName(XFont font, out PdfFont pdfFont)
    {
      pdfFont = this.document.FontTable.GetFont(font);
      Debug.Assert(pdfFont != null);
      string name = Resources.AddFont(pdfFont);
      return name;
    }

    string IContentStream.GetFontName(XFont font, out PdfFont pdfFont)
    {
      return GetFontName(font, out pdfFont);
    }

    /// <summary>
    /// Gets the resource name of the specified font data within this form XObject.
    /// </summary>
    internal string GetFontName(string idName, byte[] fontData, out PdfFont pdfFont)
    {
      pdfFont = this.document.FontTable.GetFont(idName, fontData);
      Debug.Assert(pdfFont != null);
      string name = Resources.AddFont(pdfFont);
      return name;
    }

    string IContentStream.GetFontName(string idName, byte[] fontData, out PdfFont pdfFont)
    {
      return GetFontName(idName, fontData, out pdfFont);
    }

    string IContentStream.GetImageName(XImage image)
    {
      throw new NotImplementedException();
    }

    string IContentStream.GetFormName(XForm form)
    {
      throw new NotImplementedException();
    }

#if keep_code_some_time_as_reference
    /// <summary>
    /// Replace all indirect references to external objects by their cloned counterparts
    /// owned by the importer document.
    /// </summary>
    void FixUpObject_old(PdfImportedObjectTable iot, PdfObject value)
    {
      // TODO: merge with PdfXObject.FixUpObject
      PdfDictionary dict;
      PdfArray array;
      if ((dict = value as PdfDictionary) != null)
      {
        // Set document for cloned direct objects
        if (dict.Owner == null)
          dict.Document = this.Owner;
        else
          Debug.Assert(dict.Owner == this.Owner);

        // Search for indirect references in all keys
        PdfName[] names = dict.Elements.KeyNames;
        foreach (PdfName name in names)
        {
          PdfItem item = dict.Elements[name];
          // Is item an iref?
          PdfReference iref = item as PdfReference;
          if (iref != null)
          {
            // Does the iref already belong to this document?
            if (iref.Document == this.Owner)
            {
              // Yes: fine
              continue;
            }
            else
            {
              Debug.Assert(iref.Document == iot.ExternalDocument);
              // No: replace with iref of cloned object
              PdfReference newXRef = iot[iref.ObjectID];
              Debug.Assert(newXRef != null);
              Debug.Assert(newXRef.Document == this.Owner);
              dict.Elements[name] = newXRef;
            }
          }
          else if (item is PdfObject)
          {
            // Fix up inner objects
            FixUpObject_old(iot, (PdfObject)item);
          }
        }
      }
      else if ((array = value as PdfArray) != null)
      {
        // Set document for cloned direct objects
        if (array.Owner == null)
          array.Document = this.Owner;
        else
          Debug.Assert(array.Owner == this.Owner);

        // Search for indirect references in all array elements
        int count = array.Elements.Count;
        for (int idx = 0; idx < count; idx++)
        {
          PdfItem item = array.Elements[idx];
          // Is item an iref?
          PdfReference iref = item as PdfReference;
          if (iref != null)
          {
            // Does the iref belongs to this document?
            if (iref.Document == this.Owner)
            {
              // Yes: fine
              continue;
            }
            else
            {
              Debug.Assert(iref.Document == iot.ExternalDocument);
              // No: replace with iref of cloned object
              PdfReference newXRef = iot[iref.ObjectID];
              Debug.Assert(newXRef != null);
              Debug.Assert(newXRef.Document == this.Owner);
              array.Elements[idx] = newXRef;
            }
          }
          else if (item is PdfObject)
          {
            // Fix up inner objects
            FixUpObject_old(iot, (PdfObject)item);
          }
        }
      }
    }
#endif

    //    /// <summary>
    //    /// Returns ???
    //    /// </summary>
    //    public override string ToString()
    //    {
    //      return "Form";
    //    }

    /// <summary>
    /// Predefined keys of this dictionary.
    /// </summary>
    public sealed new class Keys : PdfXObject.Keys
    {
      /// <summary>
      /// (Optional) The type of PDF object that this dictionary describes; if present,
      /// must be XObject for a form XObject.
      /// </summary>
      [KeyInfo(KeyType.Name | KeyType.Optional)]
      public const string Type = "/Type";

      /// <summary>
      /// (Required) The type of XObject that this dictionary describes; must be Form
      /// for a form XObject.
      /// </summary>
      [KeyInfo(KeyType.Name | KeyType.Required)]
      public const string Subtype = "/Subtype";

      /// <summary>
      /// (Optional) A code identifying the type of form XObject that this dictionary
      /// describes. The only valid value defined at the time of publication is 1.
      /// Default value: 1.
      /// </summary>
      [KeyInfo(KeyType.Integer | KeyType.Optional)]
      public const string FormType = "/FormType";

      /// <summary>
      /// (Required) An array of four numbers in the form coordinate system, giving the 
      /// coordinates of the left, bottom, right, and top edges, respectively, of the 
      /// form XObjects bounding box. These boundaries are used to clip the form XObject
      /// and to determine its size for caching.
      /// </summary>
      [KeyInfo(KeyType.Rectangle | KeyType.Required)]
      public const string BBox = "/BBox";

      /// <summary>
      /// (Optional) An array of six numbers specifying the form matrix, which maps
      /// form space into user space.
      /// Default value: the identity matrix [1 0 0 1 0 0].
      /// </summary>
      [KeyInfo(KeyType.Array | KeyType.Optional)]
      public const string Matrix = "/Matrix";

      /// <summary>
      /// (Optional but strongly recommended; PDF 1.2) A dictionary specifying any
      /// resources (such as fonts and images) required by the form XObject.
      /// </summary>
      [KeyInfo(KeyType.Dictionary | KeyType.Optional, typeof(PdfResources))]
      public const string Resources = "/Resources";

      /// <summary>
      /// (Optional; PDF 1.4) A group attributes dictionary indicating that the contents
      /// of the form XObject are to be treated as a group and specifying the attributes
      /// of that group (see Section 4.9.2, Group XObjects).
      /// Note: If a Ref entry (see below) is present, the group attributes also apply to the
      /// external page imported by that entry, which allows such an imported page to be
      /// treated as a group without further modification.
      /// </summary>
      [KeyInfo(KeyType.Dictionary | KeyType.Optional)]
      public const string Group = "/Group";

      // further keys:
      //Ref
      //Metadata
      //PieceInfo
      //LastModified
      //StructParent
      //StructParents
      //OPI
      //OC
      //Name

      /// <summary>
      /// Gets the KeysMeta for these keys.
      /// </summary>
      internal static DictionaryMeta Meta
      {
        get
        {
          if (Keys.meta == null)
            Keys.meta = CreateMeta(typeof(Keys));
          return Keys.meta;
        }
      }
      static DictionaryMeta meta;
    }

    /// <summary>
    /// Gets the KeysMeta of this dictionary type.
    /// </summary>
    internal override DictionaryMeta Meta
    {
      get { return Keys.Meta; }
    }
  }
}