Example #1
1
 /**
 * Processes a dictionary.
 * In case of font dictionaries, the dictionary is processed.
 */
 public void UnembedTTF(PdfDictionary dict)
 {
     // we ignore all dictionaries that aren't font dictionaries
     if (!dict.IsFont())
         return;
     // we only remove TTF fonts
     if (dict.GetAsDict(PdfName.FONTFILE2) != null)
     {
         return;
     }
     // check if a subset was used (in which case we remove the prefix)
     PdfName baseFont = dict.GetAsName(PdfName.BASEFONT);
     if (baseFont.GetBytes()[7] == '+')
     {
         baseFont = new PdfName(baseFont.ToString().Substring(8));
         dict.Put(PdfName.BASEFONT, baseFont);
     }
     // we check if there's a font descriptor
     PdfDictionary fontDescriptor = dict.GetAsDict(PdfName.FONTDESCRIPTOR);
     if (fontDescriptor == null)
         return;
     // is there is, we replace the fontname and remove the font file
     fontDescriptor.Put(PdfName.FONTNAME, baseFont);
     fontDescriptor.Remove(PdfName.FONTFILE2);
 }
 private ImageRenderInfo(Matrix ctm, InlineImageInfo inlineImageInfo, PdfDictionary colorSpaceDictionary)
 {
     this.ctm = ctm;
     this.refi = null;
     this.inlineImageInfo = inlineImageInfo;
     this.colorSpaceDictionary = colorSpaceDictionary;
 }
Example #3
0
 /**
  * Shows the detail of a dictionary.
  * @param dic   the dictionary of which you want the detail
  * @param depth the depth of the current dictionary (for nested dictionaries)
  * @return  a String representation of the dictionary
  */
 public static  String GetDictionaryDetail(PdfDictionary dic, int depth){
     StringBuilder builder = new StringBuilder();
     builder.Append('(');
     IList<PdfName> subDictionaries = new List<PdfName>();
     foreach (PdfName key in dic.Keys) {
         PdfObject val = dic.GetDirectObject(key);
         if (val.IsDictionary())
             subDictionaries.Add(key);
         builder.Append(key);
         builder.Append('=');
         builder.Append(val);
         builder.Append(", ");
     }
     builder.Length = builder.Length-2;
     builder.Append(')');
     foreach (PdfName pdfSubDictionaryName in subDictionaries) {
         builder.Append('\n');
         for (int i = 0; i < depth+1; i++){
             builder.Append('\t');
         }
         builder.Append("Subdictionary ");
         builder.Append(pdfSubDictionaryName);
         builder.Append(" = ");
         builder.Append(GetDictionaryDetail(dic.GetAsDict(pdfSubDictionaryName), depth+1));
     }
     return builder.ToString();
 }
Example #4
0
 public static Hashtable ReadTree(PdfDictionary dic)
 {
     Hashtable items = new Hashtable();
     if (dic != null)
         IterateItems(dic, items);
     return items;
 }
 private ImageRenderInfo(Matrix ctm, PdfIndirectReference refi, PdfDictionary colorSpaceDictionary)
 {
     this.ctm = ctm;
     this.refi = refi;
     this.inlineImageInfo = null;
     this.colorSpaceDictionary = colorSpaceDictionary;
 }
Example #6
0
// ---------------------------------------------------------------------------
    public byte[] CreatePdf() {
      using (MemoryStream ms = new MemoryStream()) {    
        // step 1
        using (Document document = new Document(new Rectangle(850, 600))) {
          // step 2
          PdfWriter writer = PdfWriter.GetInstance(document, ms);
          // step 3
          document.Open();
          // step 4
          PdfContentByte canvas = writer.DirectContent;
          // add the clipped image
          Image img = Image.GetInstance(
            Path.Combine(Utility.ResourceImage, RESOURCE)
          );
          float w = img.ScaledWidth;
          float h = img.ScaledHeight;
          canvas.Ellipse(1, 1, 848, 598);
          canvas.Clip();
          canvas.NewPath();
          canvas.AddImage(img, w, 0, 0, h, 0, -600);

          // Create a transparent PdfTemplate
          PdfTemplate t2 = writer.DirectContent.CreateTemplate(850, 600);
          PdfTransparencyGroup transGroup = new PdfTransparencyGroup();
          transGroup.Put( PdfName.CS, PdfName.DEVICEGRAY);
          transGroup.Isolated = true;
          transGroup.Knockout = false;
          t2.Group = transGroup;

          // Add transparent ellipses to the template
          int gradationStep = 30;
          float[] gradationRatioList = new float[gradationStep];
          for(int i = 0; i < gradationStep; i++) {
/*
* gotta love .NET, guess they forgot to copy java.lang.Math.toRadians
*/
            double radians = (Math.PI / 180) * 90.0f / gradationStep * (i + 1);
            gradationRatioList[i] = 1 - (float) Math.Sin(radians);
          }
          for(int i = 1; i < gradationStep + 1; i++) {
              t2.SetLineWidth(5 * (gradationStep + 1 - i));
              t2.SetGrayStroke(gradationRatioList[gradationStep - i]);
              t2.Ellipse(0, 0, 850, 600);
              t2.Stroke();
          }
          
          // Create an image mask for the direct content
          PdfDictionary maskDict = new PdfDictionary();
          maskDict.Put(PdfName.TYPE, PdfName.MASK);
          maskDict.Put(PdfName.S, new PdfName("Luminosity"));
          maskDict.Put(new PdfName("G"), t2.IndirectReference);
          PdfGState gState = new PdfGState();
          gState.Put(PdfName.SMASK, maskDict );
          canvas.SetGState(gState);
          
          canvas.AddTemplate(t2, 0, 0);        
        }
        return ms.ToArray();
      }
    }
Example #7
0
 /**
 * Maps the user tags to the standard tags. The mapping will allow a standard application to make some sense of the tagged
 * document whatever the user tags may be.
 * @param used the user tag
 * @param standard the standard tag
 */    
 public void MapRole(PdfName used, PdfName standard) {
     PdfDictionary rm = (PdfDictionary)Get(PdfName.ROLEMAP);
     if (rm == null) {
         rm = new PdfDictionary();
         Put(PdfName.ROLEMAP, rm);
     }
     rm.Put(used, standard);
 }
Example #8
0
        // ---------------------------------------------------------------------------
        public void Write(Stream stream)
        {
            // step 1
              using (Document document = new Document()) {
            // step 2
            PdfWriter writer = PdfWriter.GetInstance(document, stream);
            // step 3
            document.Open();
            // step 4
            Rectangle rect = new Rectangle(100, 400, 500, 800);
            rect.Border = Rectangle.BOX;
            rect.BorderWidth = 0.5f;
            rect.BorderColor = new BaseColor(0xFF, 0x00, 0x00);
            document.Add(rect);

            PdfIndirectObject streamObject = null;
            using (FileStream fs =
              new FileStream(RESOURCE, FileMode.Open, FileAccess.Read))
            {
              PdfStream stream3D = new PdfStream(fs, writer);

              stream3D.Put(PdfName.TYPE, new PdfName("3D"));
              stream3D.Put(PdfName.SUBTYPE, new PdfName("U3D"));
              stream3D.FlateCompress();
              streamObject = writer.AddToBody(stream3D);
              stream3D.WriteLength();
            }

            PdfDictionary dict3D = new PdfDictionary();
            dict3D.Put(PdfName.TYPE, new PdfName("3DView"));
            dict3D.Put(new PdfName("XN"), new PdfString("Default"));
            dict3D.Put(new PdfName("IN"), new PdfString("Unnamed"));
            dict3D.Put(new PdfName("MS"), PdfName.M);
            dict3D.Put(
              new PdfName("C2W"),
              new PdfArray(
            new float[] { 1, 0, 0, 0, 0, -1, 0, 1, 0, 3, -235, 28 }
              )
            );
            dict3D.Put(PdfName.CO, new PdfNumber(235));

            PdfIndirectObject dictObject = writer.AddToBody(dict3D);

            PdfAnnotation annot = new PdfAnnotation(writer, rect);
            annot.Put(PdfName.CONTENTS, new PdfString("3D Model"));
            annot.Put(PdfName.SUBTYPE, new PdfName("3D"));
            annot.Put(PdfName.TYPE, PdfName.ANNOT);
            annot.Put(new PdfName("3DD"), streamObject.IndirectReference);
            annot.Put(new PdfName("3DV"), dictObject.IndirectReference);
            PdfAppearance ap = writer.DirectContent.CreateAppearance(
              rect.Width, rect.Height
            );
            annot.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, ap);
            annot.SetPage();

            writer.AddAnnotation(annot);
              }
        }
Example #9
0
     // methods
 
     internal void Add(PdfName key, PdfDictionary resource) {
         if (resource.Size == 0)
             return;
         PdfDictionary dic = GetAsDict(key);
         if (dic == null)
             Put(key, resource);
         else
             dic.Merge(resource);
     }
Example #10
0
        /**
         * Creates and XMP writer that adds info about the PDF/A conformance level.
         * @param os
         * @param info
         * @param conformanceLevel
         * @throws IOException
         */

        public PdfAXmpWriter(Stream os, PdfDictionary info, PdfAConformanceLevel conformanceLevel)
            : base(os, info) {
            try {
                AddRdfDescription(conformanceLevel);
            }
            catch (XmpException xmpExc) {
                throw new IOException(xmpExc.Message);
            }
        }
Example #11
0
 internal void AddPage(PdfDictionary page) {
     if ((pages.Count % leafSize) == 0)
         parents.Add(writer.PdfIndirectReference);
     PdfIndirectReference parent = parents[parents.Count - 1];
     page.Put(PdfName.PARENT, parent);
     PdfIndirectReference current = writer.CurrentPage;
     writer.AddToBody(page, current);
     pages.Add(current);
 }
 internal PdfMediaClipData(String file, PdfFileSpecification fs, String mimeType) {
     Put(PdfName.TYPE,new PdfName("MediaClip"));
     Put(PdfName.S, new PdfName("MCD"));
     Put(PdfName.N, new PdfString("Media clip for "+file));
     Put(new PdfName("CT"), new PdfString(mimeType));
     PdfDictionary dic = new PdfDictionary();
     dic.Put(new PdfName("TF"), new PdfString("TEMPACCESS"));
     Put(new PdfName("P"), dic);
     Put(PdfName.D, fs.Reference);
 }
Example #13
0
 // methods
 internal void Add(PdfName key, PdfDictionary resource)
 {
     if (resource.Size == 0)
         return;
     PdfDictionary dic = (PdfDictionary)PdfReader.GetPdfObject(Get(key));
     if (dic == null)
         Put(key, resource);
     else
         dic.Merge(resource);
 }
Example #14
0
        /**
         * Creates an instance of a CMapAwareFont based on an indirect reference to a font.
         * @param refFont   the indirect reference to a font
         */
        public CMapAwareDocumentFont(PRIndirectReference refFont) : base(refFont){
            fontDic = (PdfDictionary)PdfReader.GetPdfObjectRelease(refFont);

            ProcessToUnicode();
            //if (toUnicodeCmap == null)
                ProcessUni2Byte();
            
            spaceWidth = base.GetWidth(' ');
            if (spaceWidth == 0){
                spaceWidth = ComputeAverageWidth();
            }
            
        }
Example #15
0
        private void addAsAttachment(IDataExporter exporter, byte[] data)
        {
            if (string.IsNullOrEmpty(exporter.FileName))
                throw new InvalidOperationException("Please fill the exporter.FileName.");

            if (string.IsNullOrEmpty(exporter.Description))
                exporter.Description = "Exported data";

            var pdfDictionary = new PdfDictionary();
            pdfDictionary.Put(PdfName.MODDATE, new PdfDate(DateTime.Now));
            var fs = PdfFileSpecification.FileEmbedded(_sharedData.PdfWriter, null, exporter.FileName, data, true, null, pdfDictionary);
            _sharedData.PdfWriter.AddFileAttachment(exporter.Description, fs);
        }
Example #16
0
 protected internal void SetReader(PdfReader reader){
     this.reader = reader;
     PdfObject obj = reader.Catalog.Get(PdfName.STRUCTTREEROOT);
     obj = GetDirectObject(obj);
     if ((obj == null) || (!obj.IsDictionary()))
         throw new BadPdfFormatException(MessageLocalization.GetComposedMessage("no.structtreeroot.found"));
     structTreeRoot = (PdfDictionary)obj;
     obj = PdfStructTreeController.GetDirectObject(structTreeRoot.Get(PdfName.PARENTTREE));
     if (!obj.IsDictionary())
         throw new BadPdfFormatException(MessageLocalization.GetComposedMessage("the.document.does.not.contain.parenttree"));
     parentTree = (PdfDictionary)obj;
     sourceRoleMap = null;
     sourceClassMap = null;
 }
Example #17
0
 internal PdfStructureElement(PdfDictionary parent, PdfName structureType) {
     if (parent is PdfStructureElement) {
         top = ((PdfStructureElement) parent).top;
         Init(parent, structureType);
         this.parent = (PdfStructureElement) parent;
         Put(PdfName.P, ((PdfStructureElement) parent).reference);
         Put(PdfName.TYPE, PdfName.STRUCTELEM);
     } else if (parent is PdfStructureTreeRoot) {
         top = (PdfStructureTreeRoot) parent;
         Init(parent, structureType);
         Put(PdfName.P, ((PdfStructureTreeRoot) parent).Reference);
         Put(PdfName.TYPE, PdfName.STRUCTELEM);
     } else {}
 }
Example #18
0
 public PRStream(PRStream stream, PdfDictionary newDic) {
     reader = stream.reader;
     offset = stream.offset;
     length = stream.Length;
     compressed = stream.compressed;
     compressionLevel = stream.compressionLevel;
     streamBytes = stream.streamBytes;
     bytes = stream.bytes;
     objNum = stream.objNum;
     objGen = stream.objGen;
     if (newDic != null)
         Merge(newDic);
     else
         Merge(stream);
 }
        /// <summary>
        /// Sets PDF/A Conformance ColorProfile.
        /// </summary>
        public void SetColorProfile()
        {
            if (PageSetup.ConformanceLevel == PdfXConformance.PDFXNONE) return;

            var pdfDictionary = new PdfDictionary(PdfName.OUTPUTINTENT);
            pdfDictionary.Put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString("sRGB IEC61966-2.1"));
            pdfDictionary.Put(PdfName.INFO, new PdfString("sRGB IEC61966-2.1"));
            pdfDictionary.Put(PdfName.S, PdfName.GTS_PDFA1);

            var profileStream = StreamHelper.GetResourceByName("PdfRpt.Core.Helper.srgb.profile");
            var pdfICCBased = new PdfICCBased(ICC_Profile.GetInstance(profileStream));
            pdfICCBased.Remove(PdfName.ALTERNATE);
            pdfDictionary.Put(PdfName.DESTOUTPUTPROFILE, PdfWriter.AddToBody(pdfICCBased).IndirectReference);

            PdfWriter.ExtraCatalog.Put(PdfName.OUTPUTINTENTS, new PdfArray(pdfDictionary));
        }
        // ---------------------------------------------------------------------------
        /**
         * Extracts the font names from page or XObject resources.
         * @param set the HashSet with the font names
         * @param resources the resources dictionary
         */
        public void ProcessResource(HashSet<String> set, PdfDictionary resource)
        {
            if (resource == null) return;

            PdfDictionary xobjects = resource.GetAsDict(PdfName.XOBJECT);
            if (xobjects != null) {
              foreach (PdfName key in xobjects.Keys) {
            ProcessResource(set, xobjects.GetAsDict(key));
              }
            }
            PdfDictionary fonts = resource.GetAsDict(PdfName.FONT);
            if (fonts == null) return;

            PdfDictionary font;
            foreach (PdfName key in fonts.Keys) {
              font = fonts.GetAsDict(key);
              String name = font.GetAsName(PdfName.BASEFONT).ToString();
              if (name.Length > 8 && name.Substring(7, 1) == "+") {
            name = String.Format(
              "{0} subset ({1})",
              name.Substring(8), name.Substring(1, 7)
            );
              }
              else {
              name = name.Substring(1);
              PdfDictionary desc = font.GetAsDict(PdfName.FONTDESCRIPTOR);
              if (desc == null) {
                name += " nofontdescriptor";
              }
              else if (desc.Get(PdfName.FONTFILE) != null) {
                name += " (Type 1) embedded";
              }
              else if (desc.Get(PdfName.FONTFILE2) != null) {
                name += " (TrueType) embedded";
              }
              else if (desc.Get(PdfName.FONTFILE3) != null) {
                name += " (" + font.GetAsName(PdfName.SUBTYPE).ToString().Substring(1) + ") embedded";
              }
              }
              set.Add(name);
            }
        }
Example #21
0
 internal void SetOriginalResources(PdfDictionary resources, int[] newNamePtr) {
     if (newNamePtr != null)
         namePtr = newNamePtr;
     forbiddenNames = new Dictionary<PdfName,object>();
     usedNames = new Dictionary<PdfName,PdfName>();
     if (resources == null)
         return;
     originalResources = new PdfDictionary();
     originalResources.Merge(resources);
     foreach (PdfName key in resources.Keys) {
         PdfObject sub = PdfReader.GetPdfObject(resources.Get(key));
         if (sub != null && sub.IsDictionary()) {
             PdfDictionary dic = (PdfDictionary)sub;
             foreach (PdfName name in dic.Keys) {
                 forbiddenNames[name] = null;
             }
             PdfDictionary dic2 = new PdfDictionary();
             dic2.Merge(dic);
             originalResources.Put(key, dic2);
         }
     }
 }
Example #22
0
 private ReturnType CopyPageMarks(PdfDictionary parentTree, PdfNumber arrayNumber, int newArrayNumber) {
     PdfArray pages = (PdfArray)GetDirectObject(parentTree.Get(PdfName.NUMS));
     if (pages == null) {
         PdfArray kids = (PdfArray)GetDirectObject(parentTree.Get(PdfName.KIDS));
         if (kids == null)
             return ReturnType.NOTFOUND;
         int cur = kids.Size/2;
         int begin = 0;
         while (true) {
             PdfDictionary kidTree = (PdfDictionary)GetDirectObject(kids[cur + begin]);
             switch (CopyPageMarks(kidTree,arrayNumber,newArrayNumber)) {
                 case ReturnType.FOUND:
                     return ReturnType.FOUND;
                 case ReturnType.ABOVE:
                     begin += cur;
                     cur /= 2;
                     if (cur == 0)
                         cur = 1;
                     if (cur + begin == kids.Size)
                         return ReturnType.ABOVE;
                     break;
                 case ReturnType.BELOW:
                     if (cur + begin == 0)
                         return ReturnType.BELOW;
                     if (cur == 0)
                         return ReturnType.NOTFOUND;
                     cur /= 2;
                     break;
                 default:
                     return ReturnType.NOTFOUND;
             }
         }
     } else {
         if (pages.Size == 0)
             return ReturnType.NOTFOUND;
         return FindAndCopyMarks(pages, arrayNumber.IntValue, newArrayNumber);
     }
 }
Example #23
0
 public virtual PdfObject GetPdfObject(PdfWriter writer) {
     PdfArray array = new PdfArray(PdfName.LAB);
     PdfDictionary dictionary = new PdfDictionary();
     if (whitePoint == null
         || whitePoint.Length != 3
         || whitePoint[0] < 0.000001f || whitePoint[2] < 0.000001f
         || whitePoint[1] < 0.999999f || whitePoint[1] > 1.000001f)
         throw new Exception(MessageLocalization.GetComposedMessage("lab.cs.white.point"));
     dictionary.Put(PdfName.WHITEPOINT, new PdfArray(whitePoint));
     if (blackPoint != null) {
         if (blackPoint.Length != 3
             || blackPoint[0] < -0.000001f || blackPoint[1] < -0.000001f || blackPoint[2] < -0.000001f)
             throw new Exception(MessageLocalization.GetComposedMessage("lab.cs.black.point"));
         dictionary.Put(PdfName.BLACKPOINT, new PdfArray(blackPoint));
     }
     if (range != null) {
         if (range.Length != 4 || range[0] > range[1] || range[2] > range[3])
             throw new Exception(MessageLocalization.GetComposedMessage("lab.cs.range"));
         dictionary.Put(PdfName.RANGE, new PdfArray(range));
     }
     array.Add(dictionary);
     return array;
 }
Example #24
0
        void Manipulate(ip.PdfDictionary element)
        {
            if (element == null)
            {
                return;
            }

            if (ip.PdfName.FIGURE.Equals(element.Get(ip.PdfName.S)))
            {
                element.Put(ip.PdfName.ALT, new ip.PdfString("Image"));
            }

            var kids = element.GetAsArray(ip.PdfName.K);

            if (kids == null)
            {
                return;
            }
            for (var i = 0; i < kids.Size; i++)
            {
                Manipulate(kids.GetAsDict(i));
            }
        }
Example #25
0
        private void DoType1TT()
        {
            CMapToUnicode toUnicode = null;
            PdfObject     enc       = PdfReader.GetPdfObject(font.Get(PdfName.ENCODING));

            if (enc == null)
            {
                FillEncoding(null);
                toUnicode = ProcessToUnicode();
                if (toUnicode != null)
                {
                    IDictionary <int, int> rm = toUnicode.CreateReverseMapping();
                    foreach (KeyValuePair <int, int> kv in rm)
                    {
                        uni2byte[kv.Key] = kv.Value;
                    }
                }
            }
            else
            {
                if (enc.IsName())
                {
                    FillEncoding((PdfName)enc);
                }
                else if (enc.IsDictionary())
                {
                    PdfDictionary encDic = (PdfDictionary)enc;
                    enc = PdfReader.GetPdfObject(encDic.Get(PdfName.BASEENCODING));
                    if (enc == null)
                    {
                        FillEncoding(null);
                    }
                    else
                    {
                        FillEncoding((PdfName)enc);
                    }
                    PdfArray diffs = encDic.GetAsArray(PdfName.DIFFERENCES);
                    if (diffs != null)
                    {
                        diffmap = new IntHashtable();
                        int currentNumber = 0;
                        for (int k = 0; k < diffs.Size; ++k)
                        {
                            PdfObject obj = diffs[k];
                            if (obj.IsNumber())
                            {
                                currentNumber = ((PdfNumber)obj).IntValue;
                            }
                            else
                            {
                                int[] c = GlyphList.NameToUnicode(PdfName.DecodeName(((PdfName)obj).ToString()));
                                if (c != null && c.Length > 0)
                                {
                                    uni2byte[c[0]] = currentNumber;
                                    diffmap[c[0]]  = currentNumber;
                                }
                                else
                                {
                                    if (toUnicode == null)
                                    {
                                        toUnicode = ProcessToUnicode();
                                        if (toUnicode == null)
                                        {
                                            toUnicode = new CMapToUnicode();
                                        }
                                    }
                                    string unicode = toUnicode.Lookup(new byte[] { (byte)currentNumber }, 0, 1);
                                    if ((unicode != null) && (unicode.Length == 1))
                                    {
                                        this.uni2byte[unicode[0]] = currentNumber;
                                        this.diffmap[unicode[0]]  = currentNumber;
                                    }
                                }
                                ++currentNumber;
                            }
                        }
                    }
                }
            }
            PdfArray  newWidths = font.GetAsArray(PdfName.WIDTHS);
            PdfNumber first     = font.GetAsNumber(PdfName.FIRSTCHAR);
            PdfNumber last      = font.GetAsNumber(PdfName.LASTCHAR);

            if (BuiltinFonts14.ContainsKey(fontName))
            {
                BaseFont bf;
                bf = BaseFont.CreateFont(fontName, WINANSI, false);
                int[] e = uni2byte.ToOrderedKeys();
                for (int k = 0; k < e.Length; ++k)
                {
                    int n = uni2byte[e[k]];
                    widths[n] = bf.GetRawWidth(n, GlyphList.UnicodeToName(e[k]));
                }
                if (diffmap != null)   //widths for differences must override existing ones
                {
                    e = diffmap.ToOrderedKeys();
                    for (int k = 0; k < e.Length; ++k)
                    {
                        int n = diffmap[e[k]];
                        widths[n] = bf.GetRawWidth(n, GlyphList.UnicodeToName(e[k]));
                    }
                    diffmap = null;
                }
                Ascender    = bf.GetFontDescriptor(ASCENT, 1000);
                CapHeight   = bf.GetFontDescriptor(CAPHEIGHT, 1000);
                Descender   = bf.GetFontDescriptor(DESCENT, 1000);
                ItalicAngle = bf.GetFontDescriptor(ITALICANGLE, 1000);
                fontWeight  = bf.GetFontDescriptor(FONT_WEIGHT, 1000);
                llx         = bf.GetFontDescriptor(BBOXLLX, 1000);
                lly         = bf.GetFontDescriptor(BBOXLLY, 1000);
                urx         = bf.GetFontDescriptor(BBOXURX, 1000);
                ury         = bf.GetFontDescriptor(BBOXURY, 1000);
            }
            if (first != null && last != null && newWidths != null)
            {
                int f     = first.IntValue;
                int nSize = f + newWidths.Size;
                if (widths.Length < nSize)
                {
                    int[] tmp = new int[nSize];
                    System.Array.Copy(widths, 0, tmp, 0, f);
                    widths = tmp;
                }
                for (int k = 0; k < newWidths.Size; ++k)
                {
                    widths[f + k] = newWidths.GetAsNumber(k).IntValue;
                }
            }
            FillFontDesc(font.GetAsDict(PdfName.FONTDESCRIPTOR));
        }
Example #26
0
 public byte[] Decode(byte[] b, PdfName filterName, PdfObject decodeParams, PdfDictionary streamDictionary)
 {
     return(b);
 }
        virtual public bool ReadKey(PdfDictionary enc, byte[] password)
        {
            if (password == null)
            {
                password = new byte[0];
            }
            byte[] oValue  = DocWriter.GetISOBytes(enc.Get(PdfName.O).ToString());
            byte[] uValue  = DocWriter.GetISOBytes(enc.Get(PdfName.U).ToString());
            byte[] oeValue = DocWriter.GetISOBytes(enc.Get(PdfName.OE).ToString());
            byte[] ueValue = DocWriter.GetISOBytes(enc.Get(PdfName.UE).ToString());
            byte[] perms   = DocWriter.GetISOBytes(enc.Get(PdfName.PERMS).ToString());

            PdfNumber pValue = (PdfNumber)enc.Get(PdfName.P);

            this.oeKey = oeValue;
            this.ueKey = ueValue;
            this.perms = perms;

            this.ownerKey = oValue;
            this.userKey  = uValue;

            this.permissions = pValue.LongValue;

            bool    isUserPass = false;
            IDigest md         = DigestUtilities.GetDigest("SHA-256");

            md.BlockUpdate(password, 0, Math.Min(password.Length, 127));
            md.BlockUpdate(oValue, VALIDATION_SALT_OFFSET, SALT_LENGHT);
            md.BlockUpdate(uValue, 0, OU_LENGHT);
            byte[]            hash        = DigestUtilities.DoFinal(md);
            bool              isOwnerPass = CompareArray(hash, oValue, 32);
            AESCipherCBCnoPad ac;

            if (isOwnerPass)
            {
                md.BlockUpdate(password, 0, Math.Min(password.Length, 127));
                md.BlockUpdate(oValue, KEY_SALT_OFFSET, SALT_LENGHT);
                md.BlockUpdate(uValue, 0, OU_LENGHT);
                md.DoFinal(hash, 0);
                ac  = new AESCipherCBCnoPad(false, hash);
                key = ac.ProcessBlock(oeValue, 0, oeValue.Length);
            }
            else
            {
                md.BlockUpdate(password, 0, Math.Min(password.Length, 127));
                md.BlockUpdate(uValue, VALIDATION_SALT_OFFSET, SALT_LENGHT);
                md.DoFinal(hash, 0);
                isUserPass = CompareArray(hash, uValue, 32);
                if (!isUserPass)
                {
                    throw new BadPasswordException(MessageLocalization.GetComposedMessage("bad.user.password"));
                }
                md.BlockUpdate(password, 0, Math.Min(password.Length, 127));
                md.BlockUpdate(uValue, KEY_SALT_OFFSET, SALT_LENGHT);
                md.DoFinal(hash, 0);
                ac  = new AESCipherCBCnoPad(false, hash);
                key = ac.ProcessBlock(ueValue, 0, ueValue.Length);
            }
            ac = new AESCipherCBCnoPad(false, key);
            byte[] decPerms = ac.ProcessBlock(perms, 0, perms.Length);
            if (decPerms[9] != (byte)'a' || decPerms[10] != (byte)'d' || decPerms[11] != (byte)'b')
            {
                throw new BadPasswordException(MessageLocalization.GetComposedMessage("bad.user.password"));
            }
            permissions = (decPerms[0] & 0xff) | ((decPerms[1] & 0xff) << 8)
                          | ((decPerms[2] & 0xff) << 16) | ((decPerms[2] & 0xff) << 24);
            encryptMetadata = decPerms[8] == (byte)'T';
            return(isOwnerPass);
        }
        /**
         * Retrieves the page labels from a PDF as an array of {@link PdfPageLabelFormat} objects.
         * @param reader a PdfReader object that has the page labels you want to retrieve
         * @return  a PdfPageLabelEntry array, containing an entry for each format change
         * or <code>null</code> if no page labels are present
         */
        public static PdfPageLabelFormat[] GetPageLabelFormats(PdfReader reader)
        {
            PdfDictionary dict   = reader.Catalog;
            PdfDictionary labels = (PdfDictionary)PdfReader.GetPdfObjectRelease(dict.Get(PdfName.PAGELABELS));

            if (labels == null)
            {
                return(null);
            }
            Dictionary <int, PdfObject> numberTree = PdfNumberTree.ReadTree(labels);

            int[] numbers = new int[numberTree.Count];
            numberTree.Keys.CopyTo(numbers, 0);
            Array.Sort(numbers);
            PdfPageLabelFormat[] formats = new PdfPageLabelFormat[numberTree.Count];
            String prefix;
            int    numberStyle;
            int    pagecount;

            for (int k = 0; k < numbers.Length; ++k)
            {
                int           key = numbers[k];
                PdfDictionary d   = (PdfDictionary)PdfReader.GetPdfObjectRelease(numberTree[key]);
                if (d.Contains(PdfName.ST))
                {
                    pagecount = ((PdfNumber)d.Get(PdfName.ST)).IntValue;
                }
                else
                {
                    pagecount = 1;
                }
                if (d.Contains(PdfName.P))
                {
                    prefix = ((PdfString)d.Get(PdfName.P)).ToUnicodeString();
                }
                else
                {
                    prefix = "";
                }
                if (d.Contains(PdfName.S))
                {
                    char type = ((PdfName)d.Get(PdfName.S)).ToString()[1];
                    switch (type)
                    {
                    case 'R': numberStyle = UPPERCASE_ROMAN_NUMERALS; break;

                    case 'r': numberStyle = LOWERCASE_ROMAN_NUMERALS; break;

                    case 'A': numberStyle = UPPERCASE_LETTERS; break;

                    case 'a': numberStyle = LOWERCASE_LETTERS; break;

                    default: numberStyle = DECIMAL_ARABIC_NUMERALS; break;
                    }
                }
                else
                {
                    numberStyle = EMPTY;
                }
                formats[k] = new PdfPageLabelFormat(key + 1, numberStyle, prefix, pagecount);
            }
            return(formats);
        }
Example #29
0
        // constructor

        /**
         * Constructs a <CODE>PdfImage</CODE>-object.
         *
         * @param image the <CODE>Image</CODE>-object
         * @param name the <CODE>PdfName</CODE> for this image
         * @throws BadPdfFormatException on error
         */

        public PdfImage(Image image, String name, PdfIndirectReference maskRef)
        {
            if (name == null)
            {
                GenerateImgResName(image);
            }
            else
            {
                this.name = new PdfName(name);
            }
            Put(PdfName.TYPE, PdfName.XOBJECT);
            Put(PdfName.SUBTYPE, PdfName.IMAGE);
            Put(PdfName.WIDTH, new PdfNumber(image.Width));
            Put(PdfName.HEIGHT, new PdfNumber(image.Height));
            if (image.Layer != null)
            {
                Put(PdfName.OC, image.Layer.Ref);
            }
            if (image.IsMask() && (image.Bpc == 1 || image.Bpc > 0xff))
            {
                Put(PdfName.IMAGEMASK, PdfBoolean.PDFTRUE);
            }
            if (maskRef != null)
            {
                if (image.Smask)
                {
                    Put(PdfName.SMASK, maskRef);
                }
                else
                {
                    Put(PdfName.MASK, maskRef);
                }
            }
            if (image.IsMask() && image.Inverted)
            {
                Put(PdfName.DECODE, new PdfLiteral("[1 0]"));
            }
            if (image.Interpolation)
            {
                Put(PdfName.INTERPOLATE, PdfBoolean.PDFTRUE);
            }
            Stream isp = null;

            try {
                // Raw Image data
                if (image.IsImgRaw())
                {
                    // will also have the CCITT parameters
                    int   colorspace   = image.Colorspace;
                    int[] transparency = image.Transparency;
                    if (transparency != null && !image.IsMask() && maskRef == null)
                    {
                        StringBuilder s = new StringBuilder("[");
                        for (int k = 0; k < transparency.Length; ++k)
                        {
                            s.Append(transparency[k]).Append(' ');
                        }
                        s.Append(']');
                        Put(PdfName.MASK, new PdfLiteral(s.ToString()));
                    }
                    bytes = image.RawData;
                    Put(PdfName.LENGTH, new PdfNumber(bytes.Length));
                    int bpc = image.Bpc;
                    if (bpc > 0xff)
                    {
                        if (!image.IsMask())
                        {
                            Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
                        }
                        Put(PdfName.BITSPERCOMPONENT, new PdfNumber(1));
                        Put(PdfName.FILTER, PdfName.CCITTFAXDECODE);
                        int           k           = bpc - Image.CCITTG3_1D;
                        PdfDictionary decodeparms = new PdfDictionary();
                        if (k != 0)
                        {
                            decodeparms.Put(PdfName.K, new PdfNumber(k));
                        }
                        if ((colorspace & Image.CCITT_BLACKIS1) != 0)
                        {
                            decodeparms.Put(PdfName.BLACKIS1, PdfBoolean.PDFTRUE);
                        }
                        if ((colorspace & Image.CCITT_ENCODEDBYTEALIGN) != 0)
                        {
                            decodeparms.Put(PdfName.ENCODEDBYTEALIGN, PdfBoolean.PDFTRUE);
                        }
                        if ((colorspace & Image.CCITT_ENDOFLINE) != 0)
                        {
                            decodeparms.Put(PdfName.ENDOFLINE, PdfBoolean.PDFTRUE);
                        }
                        if ((colorspace & Image.CCITT_ENDOFBLOCK) != 0)
                        {
                            decodeparms.Put(PdfName.ENDOFBLOCK, PdfBoolean.PDFFALSE);
                        }
                        decodeparms.Put(PdfName.COLUMNS, new PdfNumber(image.Width));
                        decodeparms.Put(PdfName.ROWS, new PdfNumber(image.Height));
                        Put(PdfName.DECODEPARMS, decodeparms);
                    }
                    else
                    {
                        switch (colorspace)
                        {
                        case 1:
                            Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
                            if (image.Inverted)
                            {
                                Put(PdfName.DECODE, new PdfLiteral("[1 0]"));
                            }
                            break;

                        case 3:
                            Put(PdfName.COLORSPACE, PdfName.DEVICERGB);
                            if (image.Inverted)
                            {
                                Put(PdfName.DECODE, new PdfLiteral("[1 0 1 0 1 0]"));
                            }
                            break;

                        case 4:
                        default:
                            Put(PdfName.COLORSPACE, PdfName.DEVICECMYK);
                            if (image.Inverted)
                            {
                                Put(PdfName.DECODE, new PdfLiteral("[1 0 1 0 1 0 1 0]"));
                            }
                            break;
                        }
                        PdfDictionary additional = image.Additional;
                        if (additional != null)
                        {
                            Merge(additional);
                        }
                        if (image.IsMask() && (image.Bpc == 1 || image.Bpc > 8))
                        {
                            Remove(PdfName.COLORSPACE);
                        }
                        Put(PdfName.BITSPERCOMPONENT, new PdfNumber(image.Bpc));
                        if (image.Deflated)
                        {
                            Put(PdfName.FILTER, PdfName.FLATEDECODE);
                        }
                        else
                        {
                            FlateCompress(image.CompressionLevel);
                        }
                    }
                    return;
                }

                // GIF, JPEG or PNG
                String errorID;
                if (image.RawData == null)
                {
                    isp     = WebRequest.Create(image.Url).GetResponse().GetResponseStream();
                    errorID = image.Url.ToString();
                }
                else
                {
                    isp     = new MemoryStream(image.RawData);
                    errorID = "Byte array";
                }
                switch (image.Type)
                {
                case Image.JPEG:
                    Put(PdfName.FILTER, PdfName.DCTDECODE);
                    switch (image.Colorspace)
                    {
                    case 1:
                        Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
                        break;

                    case 3:
                        Put(PdfName.COLORSPACE, PdfName.DEVICERGB);
                        break;

                    default:
                        Put(PdfName.COLORSPACE, PdfName.DEVICECMYK);
                        if (image.Inverted)
                        {
                            Put(PdfName.DECODE, new PdfLiteral("[1 0 1 0 1 0 1 0]"));
                        }
                        break;
                    }
                    Put(PdfName.BITSPERCOMPONENT, new PdfNumber(8));
                    if (image.RawData != null)
                    {
                        bytes = image.RawData;
                        Put(PdfName.LENGTH, new PdfNumber(bytes.Length));
                        return;
                    }
                    streamBytes = new MemoryStream();
                    TransferBytes(isp, streamBytes, -1);
                    break;

                case Image.JPEG2000:
                    Put(PdfName.FILTER, PdfName.JPXDECODE);
                    if (image.Colorspace > 0)
                    {
                        switch (image.Colorspace)
                        {
                        case 1:
                            Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
                            break;

                        case 3:
                            Put(PdfName.COLORSPACE, PdfName.DEVICERGB);
                            break;

                        default:
                            Put(PdfName.COLORSPACE, PdfName.DEVICECMYK);
                            break;
                        }
                        Put(PdfName.BITSPERCOMPONENT, new PdfNumber(image.Bpc));
                    }
                    if (image.RawData != null)
                    {
                        bytes = image.RawData;
                        Put(PdfName.LENGTH, new PdfNumber(bytes.Length));
                        return;
                    }
                    streamBytes = new MemoryStream();
                    TransferBytes(isp, streamBytes, -1);
                    break;

                case Image.JBIG2:
                    Put(PdfName.FILTER, PdfName.JBIG2DECODE);
                    Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
                    Put(PdfName.BITSPERCOMPONENT, new PdfNumber(1));
                    if (image.RawData != null)
                    {
                        bytes = image.RawData;
                        Put(PdfName.LENGTH, new PdfNumber(bytes.Length));
                        return;
                    }
                    streamBytes = new MemoryStream();
                    TransferBytes(isp, streamBytes, -1);
                    break;

                default:
                    throw new IOException(MessageLocalization.GetComposedMessage("1.is.an.unknown.image.format", errorID));
                }
                Put(PdfName.LENGTH, new PdfNumber(streamBytes.Length));
            }
            finally {
                if (isp != null)
                {
                    try{
                        isp.Close();
                    }
                    catch  {
                        // empty on purpose
                    }
                }
            }
        }
Example #30
0
 public PRStream(PRStream stream, PdfDictionary newDic, PdfReader reader) : this(stream, newDic)
 {
     this.reader = reader;
 }
        /** Generates the CIDFontTyte2 dictionary.
         * @param fontDescriptor the indirect reference to the font descriptor
         * @param subsetPrefix the subset prefix
         * @param metrics the horizontal width metrics
         * @return a stream
         */
        private PdfDictionary GetCIDFontType2(PdfIndirectReference fontDescriptor, string subsetPrefix, Object[] metrics)
        {
            PdfDictionary dic = new PdfDictionary(PdfName.FONT);

            // sivan; cff
            if (cff)
            {
                dic.Put(PdfName.SUBTYPE, PdfName.CIDFONTTYPE0);
                dic.Put(PdfName.BASEFONT, new PdfName(subsetPrefix + fontName + "-" + encoding));
            }
            else
            {
                dic.Put(PdfName.SUBTYPE, PdfName.CIDFONTTYPE2);
                dic.Put(PdfName.BASEFONT, new PdfName(subsetPrefix + fontName));
            }
            dic.Put(PdfName.FONTDESCRIPTOR, fontDescriptor);
            if (!cff)
            {
                dic.Put(PdfName.CIDTOGIDMAP, PdfName.IDENTITY);
            }
            PdfDictionary cdic = new PdfDictionary();

            cdic.Put(PdfName.REGISTRY, new PdfString("Adobe"));
            cdic.Put(PdfName.ORDERING, new PdfString("Identity"));
            cdic.Put(PdfName.SUPPLEMENT, new PdfNumber(0));
            dic.Put(PdfName.CIDSYSTEMINFO, cdic);
            if (!vertical)
            {
                dic.Put(PdfName.DW, new PdfNumber(1000));
                StringBuilder buf        = new StringBuilder("[");
                int           lastNumber = -10;
                bool          firstTime  = true;
                for (int k = 0; k < metrics.Length; ++k)
                {
                    int[] metric = (int[])metrics[k];
                    if (metric[1] == 1000)
                    {
                        continue;
                    }
                    int m = metric[0];
                    if (m == lastNumber + 1)
                    {
                        buf.Append(' ').Append(metric[1]);
                    }
                    else
                    {
                        if (!firstTime)
                        {
                            buf.Append(']');
                        }
                        firstTime = false;
                        buf.Append(m).Append('[').Append(metric[1]);
                    }
                    lastNumber = m;
                }
                if (buf.Length > 1)
                {
                    buf.Append("]]");
                    dic.Put(PdfName.W, new PdfLiteral(buf.ToString()));
                }
            }
            return(dic);
        }
 internal void AddDefaultColor(PdfDictionary dic)
 {
     colorDictionary.Merge(dic);
 }
Example #33
0
        internal override void WriteFont(PdfWriter writer, PdfIndirectReference piRef, Object[] oParams)
        {
            if (this.writer != writer)
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("type3.font.used.with.the.wrong.pdfwriter"));
            }
            // Get first & lastchar ...
            int firstChar = 0;

            while (firstChar < usedSlot.Length && !usedSlot[firstChar])
            {
                firstChar++;
            }

            if (firstChar == usedSlot.Length)
            {
                throw new DocumentException(MessageLocalization.GetComposedMessage("no.glyphs.defined.for.type3.font"));
            }
            int lastChar = usedSlot.Length - 1;

            while (lastChar >= firstChar && !usedSlot[lastChar])
            {
                lastChar--;
            }

            int[] widths = new int[lastChar - firstChar + 1];
            int[] invOrd = new int[lastChar - firstChar + 1];

            int invOrdIndx = 0, w = 0;

            for (int u = firstChar; u <= lastChar; u++, w++)
            {
                if (usedSlot[u])
                {
                    invOrd[invOrdIndx++] = u;
                    widths[w]            = widths3[u];
                }
            }
            PdfArray      diffs     = new PdfArray();
            PdfDictionary charprocs = new PdfDictionary();
            int           last      = -1;

            for (int k = 0; k < invOrdIndx; ++k)
            {
                int c = invOrd[k];
                if (c > last)
                {
                    last = c;
                    diffs.Add(new PdfNumber(last));
                }
                ++last;
                int    c2 = invOrd[k];
                String s  = GlyphList.UnicodeToName(c2);
                if (s == null)
                {
                    s = "a" + c2;
                }
                PdfName n = new PdfName(s);
                diffs.Add(n);
                Type3Glyph glyph;
                char2glyph.TryGetValue((char)c2, out glyph);
                PdfStream stream = new PdfStream(glyph.ToPdf(null));
                stream.FlateCompress(compressionLevel);
                PdfIndirectReference refp = writer.AddToBody(stream).IndirectReference;
                charprocs.Put(n, refp);
            }
            PdfDictionary font = new PdfDictionary(PdfName.FONT);

            font.Put(PdfName.SUBTYPE, PdfName.TYPE3);
            if (colorized)
            {
                font.Put(PdfName.FONTBBOX, new PdfRectangle(0, 0, 0, 0));
            }
            else
            {
                font.Put(PdfName.FONTBBOX, new PdfRectangle(llx, lly, urx, ury));
            }
            font.Put(PdfName.FONTMATRIX, new PdfArray(new float[] { 0.001f, 0, 0, 0.001f, 0, 0 }));
            font.Put(PdfName.CHARPROCS, writer.AddToBody(charprocs).IndirectReference);
            PdfDictionary encoding = new PdfDictionary();

            encoding.Put(PdfName.DIFFERENCES, diffs);
            font.Put(PdfName.ENCODING, writer.AddToBody(encoding).IndirectReference);
            font.Put(PdfName.FIRSTCHAR, new PdfNumber(firstChar));
            font.Put(PdfName.LASTCHAR, new PdfNumber(lastChar));
            font.Put(PdfName.WIDTHS, writer.AddToBody(new PdfArray(widths)).IndirectReference);
            if (pageResources.HasResources())
            {
                font.Put(PdfName.RESOURCES, writer.AddToBody(pageResources.Resources).IndirectReference);
            }
            writer.AddToBody(font, piRef);
        }
Example #34
0
        internal protected virtual void WriteFont(TrueTypeFontUnicode font, PdfIndirectReference refer, Object[] parms, byte[] rotbits)
        {
            Dictionary <int, int[]> longTag = (Dictionary <int, int[]>)parms[0];

            font.AddRangeUni(longTag, true, font.Subset);
            int[][] metrics = new int[longTag.Count][];
            longTag.Values.CopyTo(metrics, 0);
            Array.Sort(metrics, font);
            PdfIndirectReference ind_font = null;
            PdfObject            pobj     = null;
            PdfIndirectObject    obj      = null;
            PdfIndirectReference cidset   = null;

            // sivan: cff
            if (font.Cff)
            {
                byte[] b = font.ReadCffFont();
                if (font.Subset || font.SubsetRanges != null)
                {
                    CFFFontSubset cff = new CFFFontSubset(new RandomAccessFileOrArray(b), longTag);
                    b = cff.Process(cff.GetNames()[0]);
                }
                pobj     = new BaseFont.StreamFont(b, "CIDFontType0C", font.CompressionLevel);
                obj      = writer.AddToBody(pobj);
                ind_font = obj.IndirectReference;
            }
            else
            {
                byte[] b;
                if (font.Subset || font.DirectoryOffset != 0)
                {
                    b = font.GetSubSet(new HashSet <int>(longTag.Keys), true);
                }
                else
                {
                    b = font.GetFullFont();
                }
                int[] lengths = new int[] { b.Length };
                pobj     = new BaseFont.StreamFont(b, lengths, font.CompressionLevel);
                obj      = writer.AddToBody(pobj);
                ind_font = obj.IndirectReference;
            }
            String subsetPrefix = "";

            if (font.Subset)
            {
                subsetPrefix = TrueTypeFontUnicode.CreateSubsetPrefix();
            }
            PdfDictionary dic = font.GetFontDescriptor(ind_font, subsetPrefix, cidset);

            obj      = writer.AddToBody(dic);
            ind_font = obj.IndirectReference;

            pobj     = font.GetCIDFontType2(ind_font, subsetPrefix, metrics);
            obj      = writer.AddToBody(pobj);
            ind_font = obj.IndirectReference;

            pobj = font.GetToUnicode(metrics);
            PdfIndirectReference toUnicodeRef = null;

            if (pobj != null)
            {
                obj          = writer.AddToBody(pobj);
                toUnicodeRef = obj.IndirectReference;
            }

            pobj = font.GetFontBaseType(ind_font, subsetPrefix, toUnicodeRef);
            writer.AddToBody(pobj, refer);
        }
Example #35
0
 /** Creates a new instance of DocumentFont */
 internal DocumentFont(PRIndirectReference refFont)
 {
     this.refFont = refFont;
     font         = (PdfDictionary)PdfReader.GetPdfObject(refFont);
     Init();
 }
Example #36
0
        /**
         * Creates a number tree.
         * @param items the item of the number tree. The key is an <CODE>Integer</CODE>
         * and the value is a <CODE>PdfObject</CODE>.
         * @param writer the writer
         * @throws IOException on error
         * @return the dictionary with the number tree.
         */
        public static PdfDictionary WriteTree <T>(Dictionary <int, T> items, PdfWriter writer) where T : PdfObject
        {
            if (items.Count == 0)
            {
                return(null);
            }
            int[] numbers = new int[items.Count];
            items.Keys.CopyTo(numbers, 0);
            Array.Sort(numbers);
            if (numbers.Length <= leafSize)
            {
                PdfDictionary dic = new PdfDictionary();
                PdfArray      ar  = new PdfArray();
                for (int k = 0; k < numbers.Length; ++k)
                {
                    ar.Add(new PdfNumber(numbers[k]));
                    ar.Add(items[numbers[k]]);
                }
                dic.Put(PdfName.NUMS, ar);
                return(dic);
            }
            int skip = leafSize;

            PdfIndirectReference[] kids = new PdfIndirectReference[(numbers.Length + leafSize - 1) / leafSize];
            for (int k = 0; k < kids.Length; ++k)
            {
                int           offset = k * leafSize;
                int           end    = Math.Min(offset + leafSize, numbers.Length);
                PdfDictionary dic    = new PdfDictionary();
                PdfArray      arr    = new PdfArray();
                arr.Add(new PdfNumber(numbers[offset]));
                arr.Add(new PdfNumber(numbers[end - 1]));
                dic.Put(PdfName.LIMITS, arr);
                arr = new PdfArray();
                for (; offset < end; ++offset)
                {
                    arr.Add(new PdfNumber(numbers[offset]));
                    arr.Add(items[numbers[offset]]);
                }
                dic.Put(PdfName.NUMS, arr);
                kids[k] = writer.AddToBody(dic).IndirectReference;
            }
            int top = kids.Length;

            while (true)
            {
                if (top <= leafSize)
                {
                    PdfArray arr = new PdfArray();
                    for (int k = 0; k < top; ++k)
                    {
                        arr.Add(kids[k]);
                    }
                    PdfDictionary dic = new PdfDictionary();
                    dic.Put(PdfName.KIDS, arr);
                    return(dic);
                }
                skip *= leafSize;
                int tt = (numbers.Length + skip - 1) / skip;
                for (int k = 0; k < tt; ++k)
                {
                    int           offset = k * leafSize;
                    int           end    = Math.Min(offset + leafSize, top);
                    PdfDictionary dic    = new PdfDictionary();
                    PdfArray      arr    = new PdfArray();
                    arr.Add(new PdfNumber(numbers[k * skip]));
                    arr.Add(new PdfNumber(numbers[Math.Min((k + 1) * skip, numbers.Length) - 1]));
                    dic.Put(PdfName.LIMITS, arr);
                    arr = new PdfArray();
                    for (; offset < end; ++offset)
                    {
                        arr.Add(kids[offset]);
                    }
                    dic.Put(PdfName.KIDS, arr);
                    kids[k] = writer.AddToBody(dic).IndirectReference;
                }
                top = tt;
            }
        }
Example #37
0
        public PdfDictionary GetEncryptionDictionary()
        {
            PdfDictionary dic = new PdfDictionary();

            if (publicKeyHandler.GetRecipientsSize() > 0)
            {
                PdfArray recipients = null;

                dic.Put(PdfName.FILTER, PdfName.PUBSEC);
                dic.Put(PdfName.R, new PdfNumber(revision));

                recipients = publicKeyHandler.GetEncodedRecipients();

                if (revision == STANDARD_ENCRYPTION_40)
                {
                    dic.Put(PdfName.V, new PdfNumber(1));
                    dic.Put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_S4);
                    dic.Put(PdfName.RECIPIENTS, recipients);
                }
                else if (revision == STANDARD_ENCRYPTION_128 && encryptMetadata)
                {
                    dic.Put(PdfName.V, new PdfNumber(2));
                    dic.Put(PdfName.LENGTH, new PdfNumber(128));
                    dic.Put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_S4);
                    dic.Put(PdfName.RECIPIENTS, recipients);
                }
                else
                {
                    dic.Put(PdfName.R, new PdfNumber(AES_128));
                    dic.Put(PdfName.V, new PdfNumber(4));
                    dic.Put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_S5);

                    PdfDictionary stdcf = new PdfDictionary();
                    stdcf.Put(PdfName.RECIPIENTS, recipients);
                    if (!encryptMetadata)
                    {
                        stdcf.Put(PdfName.ENCRYPTMETADATA, PdfBoolean.PDFFALSE);
                    }

                    if (revision == AES_128)
                    {
                        stdcf.Put(PdfName.CFM, PdfName.AESV2);
                    }
                    else
                    {
                        stdcf.Put(PdfName.CFM, PdfName.V2);
                    }
                    PdfDictionary cf = new PdfDictionary();
                    cf.Put(PdfName.DEFAULTCRYPTFILTER, stdcf);
                    dic.Put(PdfName.CF, cf);
                    if (embeddedFilesOnly)
                    {
                        dic.Put(PdfName.EFF, PdfName.DEFAULTCRYPTFILTER);
                        dic.Put(PdfName.STRF, PdfName.IDENTITY);
                        dic.Put(PdfName.STMF, PdfName.IDENTITY);
                    }
                    else
                    {
                        dic.Put(PdfName.STRF, PdfName.DEFAULTCRYPTFILTER);
                        dic.Put(PdfName.STMF, PdfName.DEFAULTCRYPTFILTER);
                    }
                }

                IDigest sh = DigestUtilities.GetDigest("SHA1");
                byte[]  encodedRecipient = null;
                byte[]  seed             = publicKeyHandler.GetSeed();
                sh.BlockUpdate(seed, 0, seed.Length);
                for (int i = 0; i < publicKeyHandler.GetRecipientsSize(); i++)
                {
                    encodedRecipient = publicKeyHandler.GetEncodedRecipient(i);
                    sh.BlockUpdate(encodedRecipient, 0, encodedRecipient.Length);
                }
                if (!encryptMetadata)
                {
                    sh.BlockUpdate(metadataPad, 0, metadataPad.Length);
                }
                byte[] mdResult = new byte[sh.GetDigestSize()];
                sh.DoFinal(mdResult, 0);
                SetupByEncryptionKey(mdResult, keyLength);
            }
            else
            {
                dic.Put(PdfName.FILTER, PdfName.STANDARD);
                dic.Put(PdfName.O, new PdfLiteral(PdfContentByte.EscapeString(ownerKey)));
                dic.Put(PdfName.U, new PdfLiteral(PdfContentByte.EscapeString(userKey)));
                dic.Put(PdfName.P, new PdfNumber(permissions));
                dic.Put(PdfName.R, new PdfNumber(revision));
                if (revision == STANDARD_ENCRYPTION_40)
                {
                    dic.Put(PdfName.V, new PdfNumber(1));
                }
                else if (revision == STANDARD_ENCRYPTION_128 && encryptMetadata)
                {
                    dic.Put(PdfName.V, new PdfNumber(2));
                    dic.Put(PdfName.LENGTH, new PdfNumber(128));
                }
                else
                {
                    if (!encryptMetadata)
                    {
                        dic.Put(PdfName.ENCRYPTMETADATA, PdfBoolean.PDFFALSE);
                    }
                    dic.Put(PdfName.R, new PdfNumber(AES_128));
                    dic.Put(PdfName.V, new PdfNumber(4));
                    dic.Put(PdfName.LENGTH, new PdfNumber(128));
                    PdfDictionary stdcf = new PdfDictionary();
                    stdcf.Put(PdfName.LENGTH, new PdfNumber(16));
                    if (embeddedFilesOnly)
                    {
                        stdcf.Put(PdfName.AUTHEVENT, PdfName.EFOPEN);
                        dic.Put(PdfName.EFF, PdfName.STDCF);
                        dic.Put(PdfName.STRF, PdfName.IDENTITY);
                        dic.Put(PdfName.STMF, PdfName.IDENTITY);
                    }
                    else
                    {
                        stdcf.Put(PdfName.AUTHEVENT, PdfName.DOCOPEN);
                        dic.Put(PdfName.STRF, PdfName.STDCF);
                        dic.Put(PdfName.STMF, PdfName.STDCF);
                    }
                    if (revision == AES_128)
                    {
                        stdcf.Put(PdfName.CFM, PdfName.AESV2);
                    }
                    else
                    {
                        stdcf.Put(PdfName.CFM, PdfName.V2);
                    }
                    PdfDictionary cf = new PdfDictionary();
                    cf.Put(PdfName.STDCF, stdcf);
                    dic.Put(PdfName.CF, cf);
                }
            }
            return(dic);
        }
 internal static void MergeResources(PdfDictionary result, PdfDictionary source)
 {
     MergeResources(result, source, null);
 }
        /** Outputs to the writer the font dictionaries and streams.
         * @param writer the writer for this document
         * @param ref the font indirect reference
         * @param parms several parameters that depend on the font type
         * @throws IOException on error
         * @throws DocumentException error in generating the object
         */
        internal override void WriteFont(PdfWriter writer, PdfIndirectReference piref, Object[] parms)
        {
            Dictionary <int, int[]> longTag = (Dictionary <int, int[]>)parms[0];

            AddRangeUni(longTag, true, subset);
            int[][] metrics = new int[longTag.Count][];
            longTag.Values.CopyTo(metrics, 0);
            Array.Sort(metrics, this);
            PdfIndirectReference ind_font = null;
            PdfObject            pobj     = null;
            PdfIndirectObject    obj      = null;
            PdfIndirectReference cidset   = null;

            if (writer.PDFXConformance == PdfWriter.PDFA1A || writer.PDFXConformance == PdfWriter.PDFA1B)
            {
                PdfStream stream;
                if (metrics.Length == 0)
                {
                    stream = new PdfStream(new byte[] { (byte)0x80 });
                }
                else
                {
                    int    top    = metrics[metrics.Length - 1][0];
                    byte[] bt     = new byte[top / 8 + 1];
                    int    length = metrics.GetLength(0);
                    for (int k = 0; k < length; ++k)
                    {
                        int v = metrics[k][0];
                        bt[v / 8] |= rotbits[v % 8];
                    }
                    stream = new PdfStream(bt);
                    stream.FlateCompress(compressionLevel);
                }
                cidset = writer.AddToBody(stream).IndirectReference;
            }
            // sivan: cff
            if (cff)
            {
                byte[] b = ReadCffFont();
                if (subset || subsetRanges != null)
                {
                    CFFFontSubset cffs = new CFFFontSubset(new RandomAccessFileOrArray(b), longTag);
                    b = cffs.Process((cffs.GetNames())[0]);
                }

                pobj     = new StreamFont(b, "CIDFontType0C", compressionLevel);
                obj      = writer.AddToBody(pobj);
                ind_font = obj.IndirectReference;
            }
            else
            {
                byte[] b;
                if (subset || directoryOffset != 0)
                {
                    TrueTypeFontSubSet sb = new TrueTypeFontSubSet(fileName, new RandomAccessFileOrArray(rf), longTag, directoryOffset, false, false);
                    b = sb.Process();
                }
                else
                {
                    b = GetFullFont();
                }
                int[] lengths = new int[] { b.Length };
                pobj     = new StreamFont(b, lengths, compressionLevel);
                obj      = writer.AddToBody(pobj);
                ind_font = obj.IndirectReference;
            }
            String subsetPrefix = "";

            if (subset)
            {
                subsetPrefix = CreateSubsetPrefix();
            }
            PdfDictionary dic = GetFontDescriptor(ind_font, subsetPrefix, cidset);

            obj      = writer.AddToBody(dic);
            ind_font = obj.IndirectReference;

            pobj     = GetCIDFontType2(ind_font, subsetPrefix, metrics);
            obj      = writer.AddToBody(pobj);
            ind_font = obj.IndirectReference;

            pobj = GetToUnicode(metrics);
            PdfIndirectReference toUnicodeRef = null;

            if (pobj != null)
            {
                obj          = writer.AddToBody(pobj);
                toUnicodeRef = obj.IndirectReference;
            }

            pobj = GetFontBaseType(ind_font, subsetPrefix, toUnicodeRef);
            writer.AddToBody(pobj, piref);
        }
Example #40
0
        /**
         * Gets the button appearance.
         * @throws IOException on error
         * @throws DocumentException on error
         * @return the button appearance
         */
        virtual public PdfAppearance GetAppearance()
        {
            PdfAppearance app = GetBorderAppearance();
            Rectangle     box = new Rectangle(app.BoundingBox);

            if ((text == null || text.Length == 0) && (layout == LAYOUT_LABEL_ONLY || (image == null && template == null && iconReference == null)))
            {
                return(app);
            }
            if (layout == LAYOUT_ICON_ONLY && image == null && template == null && iconReference == null)
            {
                return(app);
            }
            BaseFont ufont       = RealFont;
            bool     borderExtra = borderStyle == PdfBorderDictionary.STYLE_BEVELED || borderStyle == PdfBorderDictionary.STYLE_INSET;
            float    h           = box.Height - borderWidth * 2;
            float    bw2         = borderWidth;

            if (borderExtra)
            {
                h   -= borderWidth * 2;
                bw2 *= 2;
            }
            float offsetX = (borderExtra ? 2 * borderWidth : borderWidth);

            offsetX = Math.Max(offsetX, 1);
            float offX = Math.Min(bw2, offsetX);

            tp = null;
            float textX   = float.NaN;
            float textY   = 0;
            float fsize   = fontSize;
            float wt      = box.Width - 2 * offX - 2;
            float ht      = box.Height - 2 * offX;
            float adj     = (iconFitToBounds ? 0 : offX + 1);
            int   nlayout = layout;

            if (image == null && template == null && iconReference == null)
            {
                nlayout = LAYOUT_LABEL_ONLY;
            }
            Rectangle iconBox = null;

            while (true)
            {
                switch (nlayout)
                {
                case LAYOUT_LABEL_ONLY:
                case LAYOUT_LABEL_OVER_ICON:
                    if (text != null && text.Length > 0 && wt > 0 && ht > 0)
                    {
                        fsize = CalculateFontSize(wt, ht);
                        textX = (box.Width - ufont.GetWidthPoint(text, fsize)) / 2;
                        textY = (box.Height - ufont.GetFontDescriptor(BaseFont.ASCENT, fsize)) / 2;
                    }
                    goto case LAYOUT_ICON_ONLY;

                case LAYOUT_ICON_ONLY:
                    if (nlayout == LAYOUT_LABEL_OVER_ICON || nlayout == LAYOUT_ICON_ONLY)
                    {
                        iconBox = new Rectangle(box.Left + adj, box.Bottom + adj, box.Right - adj, box.Top - adj);
                    }
                    break;

                case LAYOUT_ICON_TOP_LABEL_BOTTOM:
                    if (text == null || text.Length == 0 || wt <= 0 || ht <= 0)
                    {
                        nlayout = LAYOUT_ICON_ONLY;
                        continue;
                    }
                    float nht = box.Height * 0.35f - offX;
                    if (nht > 0)
                    {
                        fsize = CalculateFontSize(wt, nht);
                    }
                    else
                    {
                        fsize = 4;
                    }
                    textX   = (box.Width - ufont.GetWidthPoint(text, fsize)) / 2;
                    textY   = offX - ufont.GetFontDescriptor(BaseFont.DESCENT, fsize);
                    iconBox = new Rectangle(box.Left + adj, textY + fsize, box.Right - adj, box.Top - adj);
                    break;

                case LAYOUT_LABEL_TOP_ICON_BOTTOM:
                    if (text == null || text.Length == 0 || wt <= 0 || ht <= 0)
                    {
                        nlayout = LAYOUT_ICON_ONLY;
                        continue;
                    }
                    nht = box.Height * 0.35f - offX;
                    if (nht > 0)
                    {
                        fsize = CalculateFontSize(wt, nht);
                    }
                    else
                    {
                        fsize = 4;
                    }
                    textX = (box.Width - ufont.GetWidthPoint(text, fsize)) / 2;
                    textY = box.Height - offX - fsize;
                    if (textY < offX)
                    {
                        textY = offX;
                    }
                    iconBox = new Rectangle(box.Left + adj, box.Bottom + adj, box.Right - adj, textY + ufont.GetFontDescriptor(BaseFont.DESCENT, fsize));
                    break;

                case LAYOUT_LABEL_LEFT_ICON_RIGHT:
                    if (text == null || text.Length == 0 || wt <= 0 || ht <= 0)
                    {
                        nlayout = LAYOUT_ICON_ONLY;
                        continue;
                    }
                    float nw = box.Width * 0.35f - offX;
                    if (nw > 0)
                    {
                        fsize = CalculateFontSize(wt, nw);
                    }
                    else
                    {
                        fsize = 4;
                    }
                    if (ufont.GetWidthPoint(text, fsize) >= wt)
                    {
                        nlayout = LAYOUT_LABEL_ONLY;
                        fsize   = fontSize;
                        continue;
                    }
                    textX   = offX + 1;
                    textY   = (box.Height - ufont.GetFontDescriptor(BaseFont.ASCENT, fsize)) / 2;
                    iconBox = new Rectangle(textX + ufont.GetWidthPoint(text, fsize), box.Bottom + adj, box.Right - adj, box.Top - adj);
                    break;

                case LAYOUT_ICON_LEFT_LABEL_RIGHT:
                    if (text == null || text.Length == 0 || wt <= 0 || ht <= 0)
                    {
                        nlayout = LAYOUT_ICON_ONLY;
                        continue;
                    }
                    nw = box.Width * 0.35f - offX;
                    if (nw > 0)
                    {
                        fsize = CalculateFontSize(wt, nw);
                    }
                    else
                    {
                        fsize = 4;
                    }
                    if (ufont.GetWidthPoint(text, fsize) >= wt)
                    {
                        nlayout = LAYOUT_LABEL_ONLY;
                        fsize   = fontSize;
                        continue;
                    }
                    textX   = box.Width - ufont.GetWidthPoint(text, fsize) - offX - 1;
                    textY   = (box.Height - ufont.GetFontDescriptor(BaseFont.ASCENT, fsize)) / 2;
                    iconBox = new Rectangle(box.Left + adj, box.Bottom + adj, textX - 1, box.Top - adj);
                    break;
                }
                break;
            }
            if (textY < box.Bottom + offX)
            {
                textY = box.Bottom + offX;
            }
            if (iconBox != null && (iconBox.Width <= 0 || iconBox.Height <= 0))
            {
                iconBox = null;
            }
            bool     haveIcon          = false;
            float    boundingBoxWidth  = 0;
            float    boundingBoxHeight = 0;
            PdfArray matrix            = null;

            if (iconBox != null)
            {
                if (image != null)
                {
                    tp             = new PdfTemplate(writer);
                    tp.BoundingBox = new Rectangle(image);
                    writer.AddDirectTemplateSimple(tp, PdfName.FRM);
                    tp.AddImage(image, image.Width, 0, 0, image.Height, 0, 0);
                    haveIcon          = true;
                    boundingBoxWidth  = tp.BoundingBox.Width;
                    boundingBoxHeight = tp.BoundingBox.Height;
                }
                else if (template != null)
                {
                    tp             = new PdfTemplate(writer);
                    tp.BoundingBox = new Rectangle(template.Width, template.Height);
                    writer.AddDirectTemplateSimple(tp, PdfName.FRM);
                    tp.AddTemplate(template, template.BoundingBox.Left, template.BoundingBox.Bottom);
                    haveIcon          = true;
                    boundingBoxWidth  = tp.BoundingBox.Width;
                    boundingBoxHeight = tp.BoundingBox.Height;
                }
                else if (iconReference != null)
                {
                    PdfDictionary dic = (PdfDictionary)PdfReader.GetPdfObject(iconReference);
                    if (dic != null)
                    {
                        Rectangle r2 = PdfReader.GetNormalizedRectangle(dic.GetAsArray(PdfName.BBOX));
                        matrix            = dic.GetAsArray(PdfName.MATRIX);
                        haveIcon          = true;
                        boundingBoxWidth  = r2.Width;
                        boundingBoxHeight = r2.Height;
                    }
                }
            }
            if (haveIcon)
            {
                float icx = iconBox.Width / boundingBoxWidth;
                float icy = iconBox.Height / boundingBoxHeight;
                if (proportionalIcon)
                {
                    switch (scaleIcon)
                    {
                    case SCALE_ICON_IS_TOO_BIG:
                        icx = Math.Min(icx, icy);
                        icx = Math.Min(icx, 1);
                        break;

                    case SCALE_ICON_IS_TOO_SMALL:
                        icx = Math.Min(icx, icy);
                        icx = Math.Max(icx, 1);
                        break;

                    case SCALE_ICON_NEVER:
                        icx = 1;
                        break;

                    default:
                        icx = Math.Min(icx, icy);
                        break;
                    }
                    icy = icx;
                }
                else
                {
                    switch (scaleIcon)
                    {
                    case SCALE_ICON_IS_TOO_BIG:
                        icx = Math.Min(icx, 1);
                        icy = Math.Min(icy, 1);
                        break;

                    case SCALE_ICON_IS_TOO_SMALL:
                        icx = Math.Max(icx, 1);
                        icy = Math.Max(icy, 1);
                        break;

                    case SCALE_ICON_NEVER:
                        icx = icy = 1;
                        break;

                    default:
                        break;
                    }
                }
                float xpos = iconBox.Left + (iconBox.Width - (boundingBoxWidth * icx)) * iconHorizontalAdjustment;
                float ypos = iconBox.Bottom + (iconBox.Height - (boundingBoxHeight * icy)) * iconVerticalAdjustment;
                app.SaveState();
                app.Rectangle(iconBox.Left, iconBox.Bottom, iconBox.Width, iconBox.Height);
                app.Clip();
                app.NewPath();
                if (tp != null)
                {
                    app.AddTemplate(tp, icx, 0, 0, icy, xpos, ypos);
                }
                else
                {
                    float cox = 0;
                    float coy = 0;
                    if (matrix != null && matrix.Size == 6)
                    {
                        PdfNumber nm = matrix.GetAsNumber(4);
                        if (nm != null)
                        {
                            cox = nm.FloatValue;
                        }
                        nm = matrix.GetAsNumber(5);
                        if (nm != null)
                        {
                            coy = nm.FloatValue;
                        }
                    }
                    app.AddTemplateReference(iconReference, PdfName.FRM, icx, 0, 0, icy, xpos - cox * icx, ypos - coy * icy);
                }
                app.RestoreState();
            }
            if (!float.IsNaN(textX))
            {
                app.SaveState();
                app.Rectangle(offX, offX, box.Width - 2 * offX, box.Height - 2 * offX);
                app.Clip();
                app.NewPath();
                if (textColor == null)
                {
                    app.ResetGrayFill();
                }
                else
                {
                    app.SetColorFill(textColor);
                }
                app.BeginText();
                app.SetFontAndSize(ufont, fsize);
                app.SetTextMatrix(textX, textY);
                app.ShowText(text);
                app.EndText();
                app.RestoreState();
            }
            return(app);
        }
Example #41
0
        virtual public String[] GetFieldValues(String name)
        {
            PdfDictionary field = GetField(name);

            if (field == null)
            {
                return new String[] { }
            }
            ;
            PdfObject v = GetPdfObject(field.Get(PdfName.V));

            if (v == null)
            {
                return new String[] { }
            }
            ;
            if (v.IsName())
            {
                return new String[] { PdfName.DecodeName(((PdfName)v).ToString()) }
            }
            ;
            else if (v.IsString())
            {
                PdfString vs = (PdfString)v;

                if (encoding == null || vs.Encoding != null)
                {
                    return new String[] { vs.ToUnicodeString() }
                }
                ;
                byte[] b = vs.GetBytes();
                if (b.Length >= 2 && b[0] == (byte)254 && b[1] == (byte)255)
                {
                    return new String[] { vs.ToUnicodeString() }
                }
                ;
                try
                {
                    if (encoding.Equals(PdfName.SHIFT_JIS))
                    {
                        return new String[] { Encoding.GetEncoding(932).GetString(b) }
                    }
                    ;
                    else if (encoding.Equals(PdfName.UHC))
                    {
                        return new String[] { Encoding.GetEncoding(949).GetString(b) }
                    }
                    ;
                    else if (encoding.Equals(PdfName.GBK))
                    {
                        return new String[] { Encoding.GetEncoding(936).GetString(b) }
                    }
                    ;
                    else if (encoding.Equals(PdfName.BIGFIVE))
                    {
                        return new String[] { Encoding.GetEncoding(950).GetString(b) }
                    }
                    ;
                    else if (encoding.Equals(PdfName.UTF_8))
                    {
                        return new String[] { Encoding.UTF8.GetString(b) }
                    }
                    ;
                }
                catch
                {
                }
                return(new String[] { vs.ToUnicodeString() });
            }
            else if (v.IsArray())
            {
                PdfArray vsArray = (PdfArray)v;
                System.Collections.Generic.List <String> vals = new System.Collections.Generic.List <String>();
                for (Int32 vsIdx = 0; vsIdx < vsArray.Size; vsIdx++)
                {
                    if (vsArray[vsIdx] == null)
                    {
                        vals.Add("");
                    }
                    else if (vsArray[vsIdx].IsString())
                    {
                        PdfString vs = (PdfString)vsArray[vsIdx];
                        if (encoding == null || vs.Encoding != null)
                        {
                            vals.Add(vs.ToUnicodeString());
                        }
                        else
                        {
                            byte[] b1 = vs.GetBytes();
                            if (b1.Length >= 2 && b1[0] == (byte)254 && b1[1] == (byte)255)
                            {
                                vals.Add(vs.ToUnicodeString());
                            }
                            else
                            {
                                try
                                {
                                    if (encoding.Equals(PdfName.SHIFT_JIS))
                                    {
                                        vals.Add(Encoding.GetEncoding(932).GetString(b1));
                                    }
                                    else if (encoding.Equals(PdfName.UHC))
                                    {
                                        vals.Add(Encoding.GetEncoding(949).GetString(b1));
                                    }
                                    else if (encoding.Equals(PdfName.GBK))
                                    {
                                        vals.Add(Encoding.GetEncoding(936).GetString(b1));
                                    }
                                    else if (encoding.Equals(PdfName.BIGFIVE))
                                    {
                                        vals.Add(Encoding.GetEncoding(950).GetString(b1));
                                    }
                                    else if (encoding.Equals(PdfName.UTF_8))
                                    {
                                        vals.Add(Encoding.UTF8.GetString(b1));
                                    }
                                }
                                catch
                                {
                                }
                            }
                        }
                    }
                    else if (vsArray[vsIdx].IsName())
                    {
                        vals.Add(PdfName.DecodeName(((PdfName)vsArray[vsIdx]).ToString()));
                    }
                }
                return(vals.ToArray());
            }
            return(new String[] { });
        }
Example #42
0
        /**
         * @see com.lowagie.text.pdf.PdfDictionary#toPdf(com.lowagie.text.pdf.PdfWriter, java.io.OutputStream)
         */
        public override void ToPdf(PdfWriter writer, Stream os)
        {
            if (inputStream != null && compressed)
            {
                Put(PdfName.FILTER, PdfName.FLATEDECODE);
            }
            PdfEncryption crypto = null;

            if (writer != null)
            {
                crypto = writer.Encryption;
            }
            if (crypto != null)
            {
                PdfObject filter = Get(PdfName.FILTER);
                if (filter != null)
                {
                    if (PdfName.CRYPT.Equals(filter))
                    {
                        crypto = null;
                    }
                    else if (filter.IsArray())
                    {
                        PdfArray a = (PdfArray)filter;
                        if (!a.IsEmpty() && PdfName.CRYPT.Equals(a[0]))
                        {
                            crypto = null;
                        }
                    }
                }
            }
            if (crypto != null && crypto.IsEmbeddedFilesOnly())
            {
                PdfArray      filter      = new PdfArray();
                PdfArray      decodeparms = new PdfArray();
                PdfDictionary crypt       = new PdfDictionary();
                crypt.Put(PdfName.NAME, PdfName.STDCF);
                filter.Add(PdfName.CRYPT);
                decodeparms.Add(crypt);
                if (compressed)
                {
                    filter.Add(PdfName.FLATEDECODE);
                    decodeparms.Add(new PdfNull());
                }
                Put(PdfName.FILTER, filter);
                Put(PdfName.DECODEPARMS, decodeparms);
            }
            PdfObject nn = Get(PdfName.LENGTH);

            if (crypto != null && nn != null && nn.IsNumber())
            {
                int sz = ((PdfNumber)nn).IntValue;
                Put(PdfName.LENGTH, new PdfNumber(crypto.CalculateStreamSize(sz)));
                SuperToPdf(writer, os);
                Put(PdfName.LENGTH, nn);
            }
            else
            {
                SuperToPdf(writer, os);
            }

            os.Write(STARTSTREAM, 0, STARTSTREAM.Length);
            if (inputStream != null)
            {
                rawLength = 0;
                ZDeflaterOutputStream  def = null;
                OutputStreamCounter    osc = new OutputStreamCounter(os);
                OutputStreamEncryption ose = null;
                Stream fout = osc;
                if (crypto != null)
                {
                    fout = ose = crypto.GetEncryptionStream(fout);
                }
                if (compressed)
                {
                    fout = def = new ZDeflaterOutputStream(fout, compressionLevel);
                }

                byte[] buf = new byte[4192];
                while (true)
                {
                    int n = inputStream.Read(buf, 0, buf.Length);
                    if (n <= 0)
                    {
                        break;
                    }
                    fout.Write(buf, 0, n);
                    rawLength += n;
                }
                if (def != null)
                {
                    def.Finish();
                }
                if (ose != null)
                {
                    ose.Finish();
                }
                inputStreamLength = (int)osc.Counter;
            }
            else
            {
                if (crypto == null)
                {
                    if (streamBytes != null)
                    {
                        streamBytes.WriteTo(os);
                    }
                    else
                    {
                        os.Write(bytes, 0, bytes.Length);
                    }
                }
                else
                {
                    byte[] b;
                    if (streamBytes != null)
                    {
                        b = crypto.EncryptByteArray(streamBytes.ToArray());
                    }
                    else
                    {
                        b = crypto.EncryptByteArray(bytes);
                    }
                    os.Write(b, 0, b.Length);
                }
            }
            os.Write(ENDSTREAM, 0, ENDSTREAM.Length);
        }
Example #43
0
        private void DoType1TT()
        {
            PdfObject enc = PdfReader.GetPdfObject(font.Get(PdfName.ENCODING));

            if (enc == null)
            {
                FillEncoding(null);
            }
            else
            {
                if (enc.IsName())
                {
                    FillEncoding((PdfName)enc);
                }
                else
                {
                    PdfDictionary encDic = (PdfDictionary)enc;
                    enc = PdfReader.GetPdfObject(encDic.Get(PdfName.BASEENCODING));
                    if (enc == null)
                    {
                        FillEncoding(null);
                    }
                    else
                    {
                        FillEncoding((PdfName)enc);
                    }
                    PdfArray diffs = encDic.GetAsArray(PdfName.DIFFERENCES);
                    if (diffs != null)
                    {
                        diffmap = new IntHashtable();
                        int currentNumber = 0;
                        for (int k = 0; k < diffs.Size; ++k)
                        {
                            PdfObject obj = diffs[k];
                            if (obj.IsNumber())
                            {
                                currentNumber = ((PdfNumber)obj).IntValue;
                            }
                            else
                            {
                                int[] c = GlyphList.NameToUnicode(PdfName.DecodeName(((PdfName)obj).ToString()));
                                if (c != null && c.Length > 0)
                                {
                                    uni2byte[c[0]] = currentNumber;
                                    diffmap[c[0]]  = currentNumber;
                                }
                                ++currentNumber;
                            }
                        }
                    }
                }
            }
            PdfArray  newWidths = font.GetAsArray(PdfName.WIDTHS);
            PdfNumber first     = font.GetAsNumber(PdfName.FIRSTCHAR);
            PdfNumber last      = font.GetAsNumber(PdfName.LASTCHAR);

            if (BuiltinFonts14.ContainsKey(fontName))
            {
                BaseFont bf;
                bf = BaseFont.CreateFont(fontName, WINANSI, false);
                int[] e = uni2byte.ToOrderedKeys();
                for (int k = 0; k < e.Length; ++k)
                {
                    int n = uni2byte[e[k]];
                    widths[n] = bf.GetRawWidth(n, GlyphList.UnicodeToName(e[k]));
                }
                if (diffmap != null)   //widths for differences must override existing ones
                {
                    e = diffmap.ToOrderedKeys();
                    for (int k = 0; k < e.Length; ++k)
                    {
                        int n = diffmap[e[k]];
                        widths[n] = bf.GetRawWidth(n, GlyphList.UnicodeToName(e[k]));
                    }
                    diffmap = null;
                }
                Ascender    = bf.GetFontDescriptor(ASCENT, 1000);
                CapHeight   = bf.GetFontDescriptor(CAPHEIGHT, 1000);
                Descender   = bf.GetFontDescriptor(DESCENT, 1000);
                ItalicAngle = bf.GetFontDescriptor(ITALICANGLE, 1000);
                llx         = bf.GetFontDescriptor(BBOXLLX, 1000);
                lly         = bf.GetFontDescriptor(BBOXLLY, 1000);
                urx         = bf.GetFontDescriptor(BBOXURX, 1000);
                ury         = bf.GetFontDescriptor(BBOXURY, 1000);
            }
            if (first != null && last != null && newWidths != null)
            {
                int f = first.IntValue;
                for (int k = 0; k < newWidths.Size; ++k)
                {
                    widths[f + k] = newWidths.GetAsNumber(k).IntValue;
                }
            }
            FillFontDesc(font.GetAsDict(PdfName.FONTDESCRIPTOR));
        }
Example #44
0
        /** Generates the font dictionary for this font.
         * @return the PdfDictionary containing the font dictionary
         * @param firstChar the first valid character
         * @param lastChar the last valid character
         * @param shortTag a 256 bytes long <CODE>byte</CODE> array where each unused byte is represented by 0
         * @param fontDescriptor the indirect reference to a PdfDictionary containing the font descriptor or <CODE>null</CODE>
         */
        private PdfDictionary GetFontBaseType(PdfIndirectReference fontDescriptor, int firstChar, int lastChar, byte[] shortTag)
        {
            PdfDictionary dic = new PdfDictionary(PdfName.FONT);

            dic.Put(PdfName.SUBTYPE, PdfName.TYPE1);
            dic.Put(PdfName.BASEFONT, new PdfName(FontName));
            bool stdEncoding = encoding.Equals(CP1252) || encoding.Equals(MACROMAN);

            if (!fontSpecific || specialMap != null)
            {
                for (int k = firstChar; k <= lastChar; ++k)
                {
                    if (!differences[k].Equals(notdef))
                    {
                        firstChar = k;
                        break;
                    }
                }
                if (stdEncoding)
                {
                    dic.Put(PdfName.ENCODING, encoding.Equals(CP1252) ? PdfName.WIN_ANSI_ENCODING : PdfName.MAC_ROMAN_ENCODING);
                }
                else
                {
                    PdfDictionary enc = new PdfDictionary(PdfName.ENCODING);
                    PdfArray      dif = new PdfArray();
                    bool          gap = true;
                    for (int k = firstChar; k <= lastChar; ++k)
                    {
                        if (shortTag[k] != 0)
                        {
                            if (gap)
                            {
                                dif.Add(new PdfNumber(k));
                                gap = false;
                            }
                            dif.Add(new PdfName(differences[k]));
                        }
                        else
                        {
                            gap = true;
                        }
                    }
                    enc.Put(PdfName.DIFFERENCES, dif);
                    dic.Put(PdfName.ENCODING, enc);
                }
            }
            if (specialMap != null || forceWidthsOutput || !(builtinFont && (fontSpecific || stdEncoding)))
            {
                dic.Put(PdfName.FIRSTCHAR, new PdfNumber(firstChar));
                dic.Put(PdfName.LASTCHAR, new PdfNumber(lastChar));
                PdfArray wd = new PdfArray();
                for (int k = firstChar; k <= lastChar; ++k)
                {
                    if (shortTag[k] == 0)
                    {
                        wd.Add(new PdfNumber(0));
                    }
                    else
                    {
                        wd.Add(new PdfNumber(widths[k]));
                    }
                }
                dic.Put(PdfName.WIDTHS, wd);
            }
            if (!builtinFont && fontDescriptor != null)
            {
                dic.Put(PdfName.FONTDESCRIPTOR, fontDescriptor);
            }
            return(dic);
        }
        /// <summary>
        /// Creates a name tree.
        /// and the value is a  PdfObject . Note that although the
        /// keys are strings only the lower byte is used and no check is made for chars
        /// with the same lower byte and different upper byte. This will generate a wrong
        /// tree name.
        /// @throws IOException on error
        /// generally pointed to by the key /Dests, for example
        /// </summary>
        /// <param name="items">the item of the name tree. The key is a  String </param>
        /// <param name="writer">the writer</param>
        /// <returns>the dictionary with the name tree. This dictionary is the one</returns>
        public static PdfDictionary WriteTree(Hashtable items, PdfWriter writer)
        {
            if (items.Count == 0)
            {
                return(null);
            }
            string[] names = new string[items.Count];
            items.Keys.CopyTo(names, 0);
            Array.Sort(names);
            if (names.Length <= LeafSize)
            {
                PdfDictionary dic = new PdfDictionary();
                PdfArray      ar  = new PdfArray();
                for (int k = 0; k < names.Length; ++k)
                {
                    ar.Add(new PdfString(names[k], null));
                    ar.Add((PdfObject)items[names[k]]);
                }
                dic.Put(PdfName.Names, ar);
                return(dic);
            }
            int skip = LeafSize;

            PdfIndirectReference[] kids = new PdfIndirectReference[(names.Length + LeafSize - 1) / LeafSize];
            for (int k = 0; k < kids.Length; ++k)
            {
                int           offset = k * LeafSize;
                int           end    = Math.Min(offset + LeafSize, names.Length);
                PdfDictionary dic    = new PdfDictionary();
                PdfArray      arr    = new PdfArray();
                arr.Add(new PdfString(names[offset], null));
                arr.Add(new PdfString(names[end - 1], null));
                dic.Put(PdfName.Limits, arr);
                arr = new PdfArray();
                for (; offset < end; ++offset)
                {
                    arr.Add(new PdfString(names[offset], null));
                    arr.Add((PdfObject)items[names[offset]]);
                }
                dic.Put(PdfName.Names, arr);
                kids[k] = writer.AddToBody(dic).IndirectReference;
            }
            int top = kids.Length;

            while (true)
            {
                if (top <= LeafSize)
                {
                    PdfArray arr = new PdfArray();
                    for (int k = 0; k < top; ++k)
                    {
                        arr.Add(kids[k]);
                    }
                    PdfDictionary dic = new PdfDictionary();
                    dic.Put(PdfName.Kids, arr);
                    return(dic);
                }
                skip *= LeafSize;
                int tt = (names.Length + skip - 1) / skip;
                for (int k = 0; k < tt; ++k)
                {
                    int           offset = k * LeafSize;
                    int           end    = Math.Min(offset + LeafSize, top);
                    PdfDictionary dic    = new PdfDictionary();
                    PdfArray      arr    = new PdfArray();
                    arr.Add(new PdfString(names[k * skip], null));
                    arr.Add(new PdfString(names[Math.Min((k + 1) * skip, names.Length) - 1], null));
                    dic.Put(PdfName.Limits, arr);
                    arr = new PdfArray();
                    for (; offset < end; ++offset)
                    {
                        arr.Add(kids[offset]);
                    }
                    dic.Put(PdfName.Kids, arr);
                    kids[k] = writer.AddToBody(dic).IndirectReference;
                }
                top = tt;
            }
        }
Example #46
0
        // returns the top parent to include in the catalog
        internal PdfIndirectReference WritePageTree()
        {
            if (pages.Count == 0)
            {
                throw new IOException(MessageLocalization.GetComposedMessage("the.document.has.no.pages"));
            }
            int leaf = 1;
            List <PdfIndirectReference> tParents    = parents;
            List <PdfIndirectReference> tPages      = pages;
            List <PdfIndirectReference> nextParents = new List <PdfIndirectReference>();

            while (true)
            {
                leaf *= leafSize;
                int stdCount   = leafSize;
                int rightCount = tPages.Count % leafSize;
                if (rightCount == 0)
                {
                    rightCount = leafSize;
                }
                for (int p = 0; p < tParents.Count; ++p)
                {
                    int count;
                    int thisLeaf = leaf;
                    if (p == tParents.Count - 1)
                    {
                        count    = rightCount;
                        thisLeaf = pages.Count % leaf;
                        if (thisLeaf == 0)
                        {
                            thisLeaf = leaf;
                        }
                    }
                    else
                    {
                        count = stdCount;
                    }
                    PdfDictionary top = new PdfDictionary(PdfName.PAGES);
                    top.Put(PdfName.COUNT, new PdfNumber(thisLeaf));
                    PdfArray         kids   = new PdfArray();
                    List <PdfObject> intern = kids.ArrayList;
                    foreach (PdfObject obb in tPages.GetRange(p * stdCount, count))
                    {
                        intern.Add(obb);
                    }
                    top.Put(PdfName.KIDS, kids);
                    if (tParents.Count > 1)
                    {
                        if ((p % leafSize) == 0)
                        {
                            nextParents.Add(writer.PdfIndirectReference);
                        }
                        top.Put(PdfName.PARENT, nextParents[p / leafSize]);
                    }
                    writer.AddToBody(top, tParents[p]);
                }
                if (tParents.Count == 1)
                {
                    topParent = tParents[0];
                    return(topParent);
                }
                tPages      = tParents;
                tParents    = nextParents;
                nextParents = new List <PdfIndirectReference>();
            }
        }
        /**
         * Retrieves the page labels from a PDF as an array of String objects.
         * @param reader a PdfReader object that has the page labels you want to retrieve
         * @return  a String array or <code>null</code> if no page labels are present
         */
        public static String[] GetPageLabels(PdfReader reader)
        {
            int n = reader.NumberOfPages;

            PdfDictionary dict   = reader.Catalog;
            PdfDictionary labels = (PdfDictionary)PdfReader.GetPdfObjectRelease(dict.Get(PdfName.PAGELABELS));

            if (labels == null)
            {
                return(null);
            }

            String[] labelstrings = new String[n];
            Dictionary <int, PdfObject> numberTree = PdfNumberTree.ReadTree(labels);

            int    pagecount = 1;
            String prefix    = "";
            char   type      = 'D';

            for (int i = 0; i < n; i++)
            {
                if (numberTree.ContainsKey(i))
                {
                    PdfDictionary d = (PdfDictionary)PdfReader.GetPdfObjectRelease(numberTree[i]);
                    if (d.Contains(PdfName.ST))
                    {
                        pagecount = ((PdfNumber)d.Get(PdfName.ST)).IntValue;
                    }
                    else
                    {
                        pagecount = 1;
                    }
                    if (d.Contains(PdfName.P))
                    {
                        prefix = ((PdfString)d.Get(PdfName.P)).ToUnicodeString();
                    }
                    if (d.Contains(PdfName.S))
                    {
                        type = ((PdfName)d.Get(PdfName.S)).ToString()[1];
                    }
                    else
                    {
                        type = 'e';
                    }
                }
                switch (type)
                {
                default:
                    labelstrings[i] = prefix + pagecount;
                    break;

                case 'R':
                    labelstrings[i] = prefix + RomanNumberFactory.GetUpperCaseString(pagecount);
                    break;

                case 'r':
                    labelstrings[i] = prefix + RomanNumberFactory.GetLowerCaseString(pagecount);
                    break;

                case 'A':
                    labelstrings[i] = prefix + RomanAlphabetFactory.GetUpperCaseString(pagecount);
                    break;

                case 'a':
                    labelstrings[i] = prefix + RomanAlphabetFactory.GetLowerCaseString(pagecount);
                    break;

                case 'e':
                    labelstrings[i] = prefix;
                    break;
                }
                pagecount++;
            }
            return(labelstrings);
        }
 public CMapAwareDocumentFont(PdfDictionary font) : base(font)
 {
     fontDic = font;
     InitFont();
 }
Example #49
0
            public byte[] Decode(byte[] b, PdfName filterName, PdfObject decodeParams, PdfDictionary streamDictionary)
            {
                // allocate the output buffer
                MemoryStream baos     = new MemoryStream();
                sbyte        dupCount = -1;

                for (int i = 0; i < b.Length; i++)
                {
                    dupCount = (sbyte)b[i];
                    if (dupCount == -128)
                    {
                        break;                   // this is implicit end of data
                    }
                    if (dupCount >= 0 && dupCount <= 127)
                    {
                        int bytesToCopy = dupCount + 1;
                        baos.Write(b, i, bytesToCopy);
                        i += bytesToCopy;
                    }
                    else
                    {
                        // make dupcount copies of the next byte
                        i++;
                        for (int j = 0; j < 1 - (int)(dupCount); j++)
                        {
                            baos.WriteByte(b[i]);
                        }
                    }
                }
                return(baos.ToArray());
            }
 /**
  * Creates an instance of a CMapAwareFont based on an indirect reference to a font.
  * @param refFont   the indirect reference to a font
  */
 public CMapAwareDocumentFont(PRIndirectReference refFont) : base(refFont)
 {
     fontDic = (PdfDictionary)PdfReader.GetPdfObjectRelease(refFont);
     InitFont();
 }
Example #51
0
 public void Push(PdfDictionary resources)
 {
     _resourceStack.Add(resources);
 }
Example #52
0
 /** Creates a new instance of DocumentFont */
 internal DocumentFont(PdfDictionary font)
 {
     this.refFont = null;
     this.font    = font;
     Init();
 }
Example #53
0
 /**
  * Resets the additional pageDictEntries.
  * @since 5.1.0
  */
 public void ResetPageDictEntries() {
     pageDictEntries = new PdfDictionary();
 }
Example #54
0
 protected void BuildStructTreeRootForTagged(PdfDictionary catalog)
 {
     if (tagged) {
         this.StructureTreeRoot.BuildTree();
         catalog.Put(PdfName.STRUCTTREEROOT, structureTreeRoot.Reference);
         PdfDictionary mi = new PdfDictionary();
         mi.Put(PdfName.MARKED, PdfBoolean.PDFTRUE);
         if (userProperties)
             mi.Put(PdfName.USERPROPERTIES, PdfBoolean.PDFTRUE);
         catalog.Put(PdfName.MARKINFO, mi);
     }
 }
 internal void AddDefaultColorDiff(PdfDictionary dic)
 {
     colorDictionary.MergeDifferent(dic);
 }
Example #56
0
 private void CompleteExtraCatalog(PdfDictionary extraCatalog) {
     if (IsPdfX()) {
         if (extraCatalog.Get(PdfName.OUTPUTINTENTS) == null) {
             PdfDictionary outD = new PdfDictionary(PdfName.OUTPUTINTENT);
             outD.Put(PdfName.OUTPUTCONDITION, new PdfString("SWOP CGATS TR 001-1995"));
             outD.Put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString("CGATS TR 001"));
             outD.Put(PdfName.REGISTRYNAME, new PdfString("http://www.color.org"));
             outD.Put(PdfName.INFO, new PdfString(""));
             outD.Put(PdfName.S, PdfName.GTS_PDFX);
             extraCatalog.Put(PdfName.OUTPUTINTENTS, new PdfArray(outD));
         }
     }
 }
Example #57
0
 private void CompleteInfoDictionary(PdfDictionary info) {
     if (IsPdfX()) {
         if (info.Get(PdfName.GTS_PDFXVERSION) == null) {
             if (((PdfXConformanceImp)pdfIsoConformance).IsPdfX1A2001()) {
                 info.Put(PdfName.GTS_PDFXVERSION, new PdfString("PDF/X-1:2001"));
                 info.Put(new PdfName("GTS_PDFXConformance"), new PdfString("PDF/X-1a:2001"));
             }
             else if (((PdfXConformanceImp)pdfIsoConformance).IsPdfX32002())
                 info.Put(PdfName.GTS_PDFXVERSION, new PdfString("PDF/X-3:2002"));
         }
         if (info.Get(PdfName.TITLE) == null) {
             info.Put(PdfName.TITLE, new PdfString("Pdf document"));
         }
         if (info.Get(PdfName.CREATOR) == null) {
             info.Put(PdfName.CREATOR, new PdfString("Unknown"));
         }
         if (info.Get(PdfName.TRAPPED) == null) {
             info.Put(PdfName.TRAPPED, new PdfName("False"));
         }
     }
 }
Example #58
0
 internal protected virtual XmpWriter GetXmpWriter(MemoryStream baos, PdfDictionary info) {
     if (xmpWriter == null)
         xmpWriter = new XmpWriter(baos, info);
     return xmpWriter;
 }
        private static PdfObject FindImageInPDFDictionary(PdfDictionary pg)
        {
            PdfDictionary res = (PdfDictionary)PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES));


            PdfDictionary xobj = (PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));
            if (xobj != null)
            {
                foreach (PdfName name in xobj.Keys)
                {
                    PdfObject obj = xobj.Get(name);
                    if (obj.IsIndirect())
                    {
                        PdfDictionary tg = (PdfDictionary)PdfReader.GetPdfObject(obj);
                        PdfName type = (PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));

                        //image at the root of the pdf
                        if (PdfName.IMAGE.Equals(type))
                        {
                            return obj;
                        }// image inside a form
                        else if (PdfName.FORM.Equals(type))
                        {
                            return FindImageInPDFDictionary(tg);
                        } //image inside a group
                        else if (PdfName.GROUP.Equals(type))
                        {
                            return FindImageInPDFDictionary(tg);
                        }
                    }
                }
            }
            return null;
        }
        private static AttachmentFile extractFile(PdfDictionary filespec)
        {
            if (filespec == null)
                return null;

            var type = PdfReader.GetPdfObject(filespec.Get(PdfName.TYPE)) as PdfName;
            if (!PdfName.F.Equals(type) && !PdfName.FILESPEC.Equals(type))
                return null;

            var ef = PdfReader.GetPdfObject(filespec.Get(PdfName.EF)) as PdfDictionary;
            if (ef == null)
                return null;

            var fn = PdfReader.GetPdfObject(filespec.Get(PdfName.F)) as PdfString;
            if (fn == null)
                return null;

            var prs = PdfReader.GetPdfObject(ef.Get(PdfName.F)) as PRStream;
            if (prs == null)
                return null;

            return new AttachmentFile
            {
                Content = PdfReader.GetStreamBytes(prs),
                FileName = fn.ToUnicodeString()
            };
        }