Exemplo n.º 1
0
 /**
 * Constructs a PDF Collection Sort Dictionary.
 * @param keys  the keys of the fields that will be used to sort entries
 */
 public PdfCollectionSort(String[] keys)
     : base(PdfName.COLLECTIONSORT)
 {
     PdfArray array = new PdfArray();
     for (int i = 0; i < keys.Length; i++) {
         array.Add(new PdfName(keys[i]));
     }
     Put(PdfName.S, array);
 }
Exemplo n.º 2
0
 /**
 * Defines the sort order of the field (ascending or descending).
 * @param ascending an array with every element corresponding with a name of a field.
 */
 public void SetSortOrder(bool[] ascending)
 {
     PdfObject o = (PdfObject)Get(PdfName.S);
     if (o is PdfArray) {
         if (((PdfArray)o).Size != ascending.Length) {
             throw new InvalidOperationException("The number of booleans in this array doesn't correspond with the number of fields.");
         }
         PdfArray array = new PdfArray();
         for (int i = 0; i < ascending.Length; i++) {
             array.Add(new PdfBoolean(ascending[i]));
         }
         Put(PdfName.A, array);
     }
     else {
         throw new InvalidOperationException("You need a single bool for this collection sort dictionary.");
     }
 }
Exemplo n.º 3
0
 public PdfArray RotateAnnotations(PdfWriter writer, Rectangle pageSize)
 {
     PdfArray array = new PdfArray();
     int rotation = pageSize.Rotation % 360;
     int currentPage = writer.CurrentPageNumber;
     for (int k = 0; k < annotations.Count; ++k) {
         PdfAnnotation dic = (PdfAnnotation)annotations[k];
         int page = dic.PlaceInPage;
         if (page > currentPage) {
             delayedAnnotations.Add(dic);
             continue;
         }
         if (dic.IsForm()) {
             if (!dic.IsUsed()) {
                 Hashtable templates = dic.Templates;
                 if (templates != null)
                     acroForm.AddFieldTemplates(templates);
             }
             PdfFormField field = (PdfFormField)dic;
             if (field.Parent == null)
                 acroForm.AddDocumentField(field.IndirectReference);
         }
         if (dic.IsAnnotation()) {
             array.Add(dic.IndirectReference);
             if (!dic.IsUsed()) {
                 PdfRectangle rect = (PdfRectangle)dic.Get(PdfName.RECT);
                 if (rect != null) {
                     switch (rotation) {
                         case 90:
                             dic.Put(PdfName.RECT, new PdfRectangle(
                                     pageSize.Top - rect.Bottom,
                                     rect.Left,
                                     pageSize.Top - rect.Top,
                                     rect.Right));
                             break;
                         case 180:
                             dic.Put(PdfName.RECT, new PdfRectangle(
                                     pageSize.Right - rect.Left,
                                     pageSize.Top - rect.Bottom,
                                     pageSize.Right - rect.Right,
                                     pageSize.Top - rect.Top));
                             break;
                         case 270:
                             dic.Put(PdfName.RECT, new PdfRectangle(
                                     rect.Bottom,
                                     pageSize.Right - rect.Left,
                                     rect.Top,
                                     pageSize.Right - rect.Right));
                             break;
                     }
                 }
             }
         }
         if (!dic.IsUsed()) {
             dic.SetUsed();
             writer.AddToBody(dic, dic.IndirectReference);
         }
     }
     return array;
 }
Exemplo n.º 4
0
 internal Color GetMKColor(PdfArray ar)
 {
     if (ar == null)
         return null;
     switch (ar.Size) {
         case 1:
             return new GrayColor(ar.GetAsNumber(0).FloatValue);
         case 3:
             return new Color(ExtendedColor.Normalize(ar.GetAsNumber(0).FloatValue), ExtendedColor.Normalize(ar.GetAsNumber(1).FloatValue), ExtendedColor.Normalize(ar.GetAsNumber(2).FloatValue));
         case 4:
             return new CMYKColor(ar.GetAsNumber(0).FloatValue, ar.GetAsNumber(1).FloatValue, ar.GetAsNumber(2).FloatValue, ar.GetAsNumber(3).FloatValue);
         default:
             return null;
     }
 }
Exemplo n.º 5
0
 /**
 * Sets the option list for fields of type list or combo. One of <CODE>exportValues</CODE>
 * or <CODE>displayValues</CODE> may be <CODE>null</CODE> but not both. This method will only
 * set the list but will not set the value or appearance. For that, calling <CODE>setField()</CODE>
 * is required.
 * <p>
 * An example:
 * <p>
 * <PRE>
 * PdfReader pdf = new PdfReader("input.pdf");
 * PdfStamper stp = new PdfStamper(pdf, new FileOutputStream("output.pdf"));
 * AcroFields af = stp.GetAcroFields();
 * af.SetListOption("ComboBox", new String[]{"a", "b", "c"}, new String[]{"first", "second", "third"});
 * af.SetField("ComboBox", "b");
 * stp.Close();
 * </PRE>
 * @param fieldName the field name
 * @param exportValues the export values
 * @param displayValues the display values
 * @return <CODE>true</CODE> if the operation succeeded, <CODE>false</CODE> otherwise
 */
 public bool SetListOption(String fieldName, String[] exportValues, String[] displayValues)
 {
     if (exportValues == null && displayValues == null)
         return false;
     if (exportValues != null && displayValues != null && exportValues.Length != displayValues.Length)
         throw new ArgumentException("The export and the display array must have the same size.");
     int ftype = GetFieldType(fieldName);
     if (ftype != FIELD_TYPE_COMBO && ftype != FIELD_TYPE_LIST)
         return false;
     Item fd = (Item)fields[fieldName];
     String[] sing = null;
     if (exportValues == null && displayValues != null)
         sing = displayValues;
     else if (exportValues != null && displayValues == null)
         sing = exportValues;
     PdfArray opt = new PdfArray();
     if (sing != null) {
         for (int k = 0; k < sing.Length; ++k)
             opt.Add(new PdfString(sing[k], PdfObject.TEXT_UNICODE));
     }
     else {
         for (int k = 0; k < exportValues.Length; ++k) {
             PdfArray a = new PdfArray();
             a.Add(new PdfString(exportValues[k], PdfObject.TEXT_UNICODE));
             a.Add(new PdfString(displayValues[k], PdfObject.TEXT_UNICODE));
             opt.Add(a);
         }
     }
     fd.WriteToAll( PdfName.OPT, opt, Item.WRITE_VALUE | Item.WRITE_MERGED );
     return true;
 }
Exemplo n.º 6
0
 private void AddASEvent(PdfName eventa, PdfName category)
 {
     PdfArray arr = new PdfArray();
     foreach (PdfLayer layer in documentOCG.Keys) {
         PdfDictionary usage = (PdfDictionary)layer.Get(PdfName.USAGE);
         if (usage != null && usage.Get(category) != null)
             arr.Add(layer.Ref);
     }
     if (arr.Size == 0)
         return;
     PdfDictionary d = (PdfDictionary)vOCProperties.Get(PdfName.D);
     PdfArray arras = (PdfArray)d.Get(PdfName.AS);
     if (arras == null) {
         arras = new PdfArray();
         d.Put(PdfName.AS, arras);
     }
     PdfDictionary asa = new PdfDictionary();
     asa.Put(PdfName.EVENT, eventa);
     asa.Put(PdfName.CATEGORY, new PdfArray(category));
     asa.Put(PdfName.OCGS, arr);
     arras.Add(asa);
 }
Exemplo n.º 7
0
 protected void FillOCProperties(bool erase)
 {
     if (vOCProperties == null)
         vOCProperties = new PdfOCProperties();
     if (erase) {
         vOCProperties.Remove(PdfName.OCGS);
         vOCProperties.Remove(PdfName.D);
     }
     if (vOCProperties.Get(PdfName.OCGS) == null) {
         PdfArray gr = new PdfArray();
         foreach (PdfLayer layer in documentOCG.Keys) {
             gr.Add(layer.Ref);
         }
         vOCProperties.Put(PdfName.OCGS, gr);
     }
     if (vOCProperties.Get(PdfName.D) != null)
         return;
     ArrayList docOrder = new ArrayList(documentOCGorder);
     for (ListIterator it = new ListIterator(docOrder); it.HasNext();) {
         PdfLayer layer = (PdfLayer)it.Next();
         if (layer.Parent != null)
             it.Remove();
     }
     PdfArray order = new PdfArray();
     foreach (PdfLayer layer in docOrder) {
         GetOCGOrder(order, layer);
     }
     PdfDictionary d = new PdfDictionary();
     vOCProperties.Put(PdfName.D, d);
     d.Put(PdfName.ORDER, order);
     PdfArray grx = new PdfArray();
     foreach (PdfLayer layer in documentOCG.Keys) {
         if (!layer.On)
             grx.Add(layer.Ref);
     }
     if (grx.Size > 0)
         d.Put(PdfName.OFF, grx);
     if (OCGRadioGroup.Size > 0)
         d.Put(PdfName.RBGROUPS, OCGRadioGroup);
     if (OCGLocked.Size > 0)
         d.Put(PdfName.LOCKED, OCGLocked);
     AddASEvent(PdfName.VIEW, PdfName.ZOOM);
     AddASEvent(PdfName.VIEW, PdfName.VIEW);
     AddASEvent(PdfName.PRINT, PdfName.PRINT);
     AddASEvent(PdfName.EXPORT, PdfName.EXPORT);
     d.Put(PdfName.LISTMODE, PdfName.VISIBLEPAGES);
 }
Exemplo n.º 8
0
 /**
 * Signals that the <CODE>Document</CODE> has been opened and that
 * <CODE>Elements</CODE> can be added.
 * <P>
 * When this method is called, the PDF-document header is
 * written to the outputstream.
 */
 public override void Open()
 {
     base.Open();
     pdf_version.WriteHeader(os);
     body = new PdfBody(this);
     if (pdfxConformance.IsPdfX32002()) {
         PdfDictionary sec = new PdfDictionary();
         sec.Put(PdfName.GAMMA, new PdfArray(new float[]{2.2f,2.2f,2.2f}));
         sec.Put(PdfName.MATRIX, new PdfArray(new float[]{0.4124f,0.2126f,0.0193f,0.3576f,0.7152f,0.1192f,0.1805f,0.0722f,0.9505f}));
         sec.Put(PdfName.WHITEPOINT, new PdfArray(new float[]{0.9505f,1f,1.089f}));
         PdfArray arr = new PdfArray(PdfName.CALRGB);
         arr.Add(sec);
         SetDefaultColorspace(PdfName.DEFAULTRGB, AddToBody(arr).IndirectReference);
     }
 }
Exemplo n.º 9
0
 /**
 * Sets a collection of optional content groups whose states are intended to follow
 * a "radio button" paradigm. That is, the state of at most one optional
 * content group in the array should be ON at a time: if one group is turned
 * ON, all others must be turned OFF.
 * @param group the radio group
 */
 public void AddOCGRadioGroup(ArrayList group)
 {
     PdfArray ar = new PdfArray();
     for (int k = 0; k < group.Count; ++k) {
         PdfLayer layer = (PdfLayer)group[k];
         if (layer.Title == null)
             ar.Add(layer.Ref);
     }
     if (ar.Size == 0)
         return;
     OCGRadioGroup.Add(ar);
 }
Exemplo n.º 10
0
 public static PdfAnnotation CreateLine(PdfWriter writer, Rectangle rect, string contents, float x1, float y1, float x2, float y2)
 {
     PdfAnnotation annot = new PdfAnnotation(writer, rect);
     annot.Put(PdfName.SUBTYPE, PdfName.LINE);
     annot.Put(PdfName.CONTENTS, new PdfString(contents, PdfObject.TEXT_UNICODE));
     PdfArray array = new PdfArray(new PdfNumber(x1));
     array.Add(new PdfNumber(y1));
     array.Add(new PdfNumber(x2));
     array.Add(new PdfNumber(y2));
     annot.Put(PdfName.L, array);
     return annot;
 }
Exemplo n.º 11
0
 public static PdfAnnotation CreateInk(PdfWriter writer, Rectangle rect, string contents, float[][] inkList)
 {
     PdfAnnotation annot = new PdfAnnotation(writer, rect);
     annot.Put(PdfName.SUBTYPE, PdfName.INK);
     annot.Put(PdfName.CONTENTS, new PdfString(contents, PdfObject.TEXT_UNICODE));
     PdfArray outer = new PdfArray();
     for (int k = 0; k < inkList.Length; ++k) {
         PdfArray inner = new PdfArray();
         float[] deep = inkList[k];
         for (int j = 0; j < deep.Length; ++j)
             inner.Add(new PdfNumber(deep[j]));
         outer.Add(inner);
     }
     annot.Put(PdfName.INKLIST, outer);
     return annot;
 }
Exemplo n.º 12
0
        /**
        * Reads next frame image
        */
        protected void ReadImage()
        {
            ix = ReadShort();    // (sub)image position & size
            iy = ReadShort();
            iw = ReadShort();
            ih = ReadShort();

            int packed = inp.ReadByte();
            lctFlag = (packed & 0x80) != 0;     // 1 - local color table flag
            interlace = (packed & 0x40) != 0;   // 2 - interlace flag
            // 3 - sort flag
            // 4-5 - reserved
            lctSize = 2 << (packed & 7);        // 6-8 - local color table size
            m_bpc = NewBpc(m_gbpc);
            if (lctFlag) {
                m_curr_table = ReadColorTable((packed & 7) + 1);   // read table
                m_bpc = NewBpc((packed & 7) + 1);
            }
            else {
                m_curr_table = m_global_table;
            }
            if (transparency && transIndex >= m_curr_table.Length / 3)
                transparency = false;
            if (transparency && m_bpc == 1) { // Acrobat 5.05 doesn't like this combination
                byte[] tp = new byte[12];
                Array.Copy(m_curr_table, 0, tp, 0, 6);
                m_curr_table = tp;
                m_bpc = 2;
            }
            bool skipZero = DecodeImageData();   // decode pixel data
            if (!skipZero)
                Skip();

            Image img = null;
            img = new ImgRaw(iw, ih, 1, m_bpc, m_out);
            PdfArray colorspace = new PdfArray();
            colorspace.Add(PdfName.INDEXED);
            colorspace.Add(PdfName.DEVICERGB);
            int len = m_curr_table.Length;
            colorspace.Add(new PdfNumber(len / 3 - 1));
            colorspace.Add(new PdfString(m_curr_table));
            PdfDictionary ad = new PdfDictionary();
            ad.Put(PdfName.COLORSPACE, colorspace);
            img.Additional = ad;
            if (transparency) {
                img.Transparency = new int[]{transIndex, transIndex};
            }
            img.OriginalType = Image.ORIGINAL_GIF;
            img.OriginalData = fromData;
            img.Url = fromUrl;
            GifFrame gf = new GifFrame();
            gf.image = img;
            gf.ix = ix;
            gf.iy = iy;
            frames.Add(gf);   // add image to frame list

            //ResetFrame();
        }
Exemplo n.º 13
0
            public void AddAnnotation(PdfAnnotation annot)
            {
                ArrayList allAnnots = new ArrayList();

                if (annot.IsForm())
                {
                    PdfFormField field = (PdfFormField)annot;
                    if (field.Parent != null)
                    {
                        return;
                    }
                    ExpandFields(field, allAnnots);
                    if (cstp.fieldTemplates == null)
                    {
                        cstp.fieldTemplates = new Hashtable();
                    }
                }
                else
                {
                    allAnnots.Add(annot);
                }
                for (int k = 0; k < allAnnots.Count; ++k)
                {
                    annot = (PdfAnnotation)allAnnots[k];
                    if (annot.IsForm())
                    {
                        if (!annot.IsUsed())
                        {
                            Hashtable templates = annot.Templates;
                            if (templates != null)
                            {
                                foreach (object tpl in templates.Keys)
                                {
                                    cstp.fieldTemplates[tpl] = null;
                                }
                            }
                        }
                        PdfFormField field = (PdfFormField)annot;
                        if (field.Parent == null)
                        {
                            AddDocumentField(field.IndirectReference);
                        }
                    }
                    if (annot.IsAnnotation())
                    {
                        PdfObject pdfobj = PdfReader.GetPdfObject(pageN.Get(PdfName.ANNOTS), pageN);
                        PdfArray  annots = null;
                        if (pdfobj == null || !pdfobj.IsArray())
                        {
                            annots = new PdfArray();
                            pageN.Put(PdfName.ANNOTS, annots);
                        }
                        else
                        {
                            annots = (PdfArray)pdfobj;
                        }
                        annots.Add(annot.IndirectReference);
                        if (!annot.IsUsed())
                        {
                            PdfRectangle rect = (PdfRectangle)annot.Get(PdfName.RECT);
                            if (rect != null && (rect.Left != 0 || rect.Right != 0 || rect.Top != 0 || rect.Bottom != 0))
                            {
                                int       rotation = reader.GetPageRotation(pageN);
                                Rectangle pageSize = reader.GetPageSizeWithRotation(pageN);
                                switch (rotation)
                                {
                                case 90:
                                    annot.Put(PdfName.RECT, new PdfRectangle(
                                                  pageSize.Top - rect.Bottom,
                                                  rect.Left,
                                                  pageSize.Top - rect.Top,
                                                  rect.Right));
                                    break;

                                case 180:
                                    annot.Put(PdfName.RECT, new PdfRectangle(
                                                  pageSize.Right - rect.Left,
                                                  pageSize.Top - rect.Bottom,
                                                  pageSize.Right - rect.Right,
                                                  pageSize.Top - rect.Top));
                                    break;

                                case 270:
                                    annot.Put(PdfName.RECT, new PdfRectangle(
                                                  rect.Bottom,
                                                  pageSize.Right - rect.Left,
                                                  rect.Top,
                                                  pageSize.Right - rect.Right));
                                    break;
                                }
                            }
                        }
                    }
                    if (!annot.IsUsed())
                    {
                        annot.SetUsed();
                        cstp.AddToBody(annot, annot.IndirectReference);
                    }
                }
            }
Exemplo n.º 14
0
            public void AlterContents()
            {
                if (over == null && under == null)
                {
                    return;
                }
                PdfArray  ar      = null;
                PdfObject content = PdfReader.GetPdfObject(pageN.Get(PdfName.CONTENTS), pageN);

                if (content == null)
                {
                    ar = new PdfArray();
                    pageN.Put(PdfName.CONTENTS, ar);
                }
                else if (content.IsArray())
                {
                    ar = (PdfArray)content;
                }
                else if (content.IsStream())
                {
                    ar = new PdfArray();
                    ar.Add(pageN.Get(PdfName.CONTENTS));
                    pageN.Put(PdfName.CONTENTS, ar);
                }
                else
                {
                    ar = new PdfArray();
                    pageN.Put(PdfName.CONTENTS, ar);
                }
                ByteBuffer out_p = new ByteBuffer();

                if (under != null)
                {
                    out_p.Append(PdfContents.SAVESTATE);
                    ApplyRotation(pageN, out_p);
                    out_p.Append(under.InternalBuffer);
                    out_p.Append(PdfContents.RESTORESTATE);
                }
                if (over != null)
                {
                    out_p.Append(PdfContents.SAVESTATE);
                }
                PdfStream stream = new PdfStream(out_p.ToByteArray());

                stream.FlateCompress(cstp.CompressionLevel);
                PdfIndirectReference ref1 = cstp.AddToBody(stream).IndirectReference;

                ar.AddFirst(ref1);
                out_p.Reset();
                if (over != null)
                {
                    out_p.Append(' ');
                    out_p.Append(PdfContents.RESTORESTATE);
                    out_p.Append(PdfContents.SAVESTATE);
                    ApplyRotation(pageN, out_p);
                    out_p.Append(over.InternalBuffer);
                    out_p.Append(PdfContents.RESTORESTATE);
                    stream = new PdfStream(out_p.ToByteArray());
                    stream.FlateCompress(cstp.CompressionLevel);
                    ar.Add(cstp.AddToBody(stream).IndirectReference);
                }
                pageN.Put(PdfName.RESOURCES, pageResources.Resources);
            }
Exemplo n.º 15
0
 /**
 * Creates a name tree.
 * @param items the item of the name tree. The key is a <CODE>String</CODE>
 * and the value is a <CODE>PdfObject</CODE>. 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.
 * @param writer the writer
 * @throws IOException on error
 * @return the dictionary with the name tree. This dictionary is the one
 * generally pointed to by the key /Dests, for example
 */
 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;
     }
 }
Exemplo n.º 16
0
 public static PdfAnnotation CreateMarkup(PdfWriter writer, Rectangle rect, string contents, int type, float[] quadPoints)
 {
     PdfAnnotation annot = new PdfAnnotation(writer, rect);
     PdfName name = PdfName.HIGHLIGHT;
     switch (type) {
         case MARKUP_UNDERLINE:
             name = PdfName.UNDERLINE;
             break;
         case MARKUP_STRIKEOUT:
             name = PdfName.STRIKEOUT;
             break;
         case MARKUP_SQUIGGLY:
             name = PdfName.SQUIGGLY;
             break;
     }
     annot.Put(PdfName.SUBTYPE, name);
     annot.Put(PdfName.CONTENTS, new PdfString(contents, PdfObject.TEXT_UNICODE));
     PdfArray array = new PdfArray();
     for (int k = 0; k < quadPoints.Length; ++k)
         array.Add(new PdfNumber(quadPoints[k]));
     annot.Put(PdfName.QUADPOINTS, array);
     return annot;
 }
Exemplo n.º 17
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);
        }
Exemplo n.º 18
0
 public static PdfArray GetMKColor(Color color)
 {
     PdfArray array = new PdfArray();
     int type = ExtendedColor.GetType(color);
     switch (type) {
         case ExtendedColor.TYPE_GRAY: {
             array.Add(new PdfNumber(((GrayColor)color).Gray));
             break;
         }
         case ExtendedColor.TYPE_CMYK: {
             CMYKColor cmyk = (CMYKColor)color;
             array.Add(new PdfNumber(cmyk.Cyan));
             array.Add(new PdfNumber(cmyk.Magenta));
             array.Add(new PdfNumber(cmyk.Yellow));
             array.Add(new PdfNumber(cmyk.Black));
             break;
         }
         case ExtendedColor.TYPE_SEPARATION:
         case ExtendedColor.TYPE_PATTERN:
         case ExtendedColor.TYPE_SHADING:
             throw new Exception("Separations, patterns and shadings are not allowed in MK dictionary.");
         default:
             array.Add(new PdfNumber(color.R / 255f));
             array.Add(new PdfNumber(color.G / 255f));
             array.Add(new PdfNumber(color.B / 255f));
             break;
     }
     return array;
 }
Exemplo n.º 19
0
        /**
        * Signals that the <CODE>Document</CODE> was closed and that no other
        * <CODE>Elements</CODE> will be added.
        * <P>
        * The pages-tree is built and written to the outputstream.
        * A Catalog is constructed, as well as an Info-object,
        * the referencetable is composed and everything is written
        * to the outputstream embedded in a Trailer.
        */
        public override void Close()
        {
            if (open) {
                if ((currentPageNumber - 1) != pageReferences.Count)
                    throw new Exception("The page " + pageReferences.Count +
                    " was requested but the document has only " + (currentPageNumber - 1) + " pages.");
                pdf.Close();
                AddSharedObjectsToBody();
                // add the root to the body
                PdfIndirectReference rootRef = root.WritePageTree();
                // make the catalog-object and add it to the body
                PdfDictionary catalog = GetCatalog(rootRef);
                // [C9] if there is XMP data to add: add it
                if (xmpMetadata != null) {
                    PdfStream xmp = new PdfStream(xmpMetadata);
                    xmp.Put(PdfName.TYPE, PdfName.METADATA);
                    xmp.Put(PdfName.SUBTYPE, PdfName.XML);
                    if (crypto != null && !crypto.IsMetadataEncrypted()) {
                        PdfArray ar = new PdfArray();
                        ar.Add(PdfName.CRYPT);
                        xmp.Put(PdfName.FILTER, ar);
                    }
                    catalog.Put(PdfName.METADATA, body.Add(xmp).IndirectReference);
                }
                // [C10] make pdfx conformant
                if (IsPdfX()) {
                    pdfxConformance.CompleteInfoDictionary(Info);
                    pdfxConformance.CompleteExtraCatalog(ExtraCatalog);
                }
                // [C11] Output Intents
                if (extraCatalog != null) {
                    catalog.MergeDifferent(extraCatalog);
                }

                WriteOutlines(catalog, false);

                // add the Catalog to the body
                PdfIndirectObject indirectCatalog = AddToBody(catalog, false);
                // add the info-object to the body
                PdfIndirectObject infoObj = AddToBody(Info, false);

                // [F1] encryption
                PdfIndirectReference encryption = null;
                PdfObject fileID = null;
                body.FlushObjStm();
                if (crypto != null) {
                    PdfIndirectObject encryptionObject = AddToBody(crypto.GetEncryptionDictionary(), false);
                    encryption = encryptionObject.IndirectReference;
                    fileID = crypto.FileID;
                }
                else
                    fileID = PdfEncryption.CreateInfoId(PdfEncryption.CreateDocumentId());

                // write the cross-reference table of the body
                body.WriteCrossReferenceTable(os, indirectCatalog.IndirectReference,
                    infoObj.IndirectReference, encryption,  fileID, prevxref);

                // make the trailer
                // [F2] full compression
                if (fullCompression) {
                    byte[] tmp = GetISOBytes("startxref\n");
                    os.Write(tmp, 0, tmp.Length);
                    tmp = GetISOBytes(body.Offset.ToString());
                    os.Write(tmp, 0, tmp.Length);
                    tmp = GetISOBytes("\n%%EOF\n");
                    os.Write(tmp, 0, tmp.Length);
                }
                else {
                    PdfTrailer trailer = new PdfTrailer(body.Size,
                    body.Offset,
                    indirectCatalog.IndirectReference,
                    infoObj.IndirectReference,
                    encryption,
                    fileID, prevxref);
                    trailer.ToPdf(this, os);
                }
                base.Close();
            }
        }
Exemplo n.º 20
0
 public void SetMKIconFit(PdfName scale, PdfName scalingType, float leftoverLeft, float leftoverBottom, bool fitInBounds)
 {
     PdfDictionary dic = new PdfDictionary();
     if (!scale.Equals(PdfName.A))
         dic.Put(PdfName.SW, scale);
     if (!scalingType.Equals(PdfName.P))
         dic.Put(PdfName.S, scalingType);
     if (leftoverLeft != 0.5f || leftoverBottom != 0.5f) {
         PdfArray array = new PdfArray(new PdfNumber(leftoverLeft));
         array.Add(new PdfNumber(leftoverBottom));
         dic.Put(PdfName.A, array);
     }
     if (fitInBounds)
         dic.Put(PdfName.FB, PdfBoolean.PDFTRUE);
     MK.Put(PdfName.IF, dic);
 }
Exemplo n.º 21
0
 internal ColorDetails AddSimplePatternColorspace(Color color)
 {
     int type = ExtendedColor.GetType(color);
     if (type == ExtendedColor.TYPE_PATTERN || type == ExtendedColor.TYPE_SHADING)
         throw new Exception("An uncolored tile pattern can not have another pattern or shading as color.");
     switch (type) {
         case ExtendedColor.TYPE_RGB:
             if (patternColorspaceRGB == null) {
                 patternColorspaceRGB = new ColorDetails(GetColorspaceName(), body.PdfIndirectReference, null);
                 PdfArray array = new PdfArray(PdfName.PATTERN);
                 array.Add(PdfName.DEVICERGB);
                 AddToBody(array, patternColorspaceRGB.IndirectReference);
             }
             return patternColorspaceRGB;
         case ExtendedColor.TYPE_CMYK:
             if (patternColorspaceCMYK == null) {
                 patternColorspaceCMYK = new ColorDetails(GetColorspaceName(), body.PdfIndirectReference, null);
                 PdfArray array = new PdfArray(PdfName.PATTERN);
                 array.Add(PdfName.DEVICECMYK);
                 AddToBody(array, patternColorspaceCMYK.IndirectReference);
             }
             return patternColorspaceCMYK;
         case ExtendedColor.TYPE_GRAY:
             if (patternColorspaceGRAY == null) {
                 patternColorspaceGRAY = new ColorDetails(GetColorspaceName(), body.PdfIndirectReference, null);
                 PdfArray array = new PdfArray(PdfName.PATTERN);
                 array.Add(PdfName.DEVICEGRAY);
                 AddToBody(array, patternColorspaceGRAY.IndirectReference);
             }
             return patternColorspaceGRAY;
         case ExtendedColor.TYPE_SEPARATION: {
             ColorDetails details = AddSimple(((SpotColor)color).PdfSpotColor);
             ColorDetails patternDetails = (ColorDetails)documentSpotPatterns[details];
             if (patternDetails == null) {
                 patternDetails = new ColorDetails(GetColorspaceName(), body.PdfIndirectReference, null);
                 PdfArray array = new PdfArray(PdfName.PATTERN);
                 array.Add(details.IndirectReference);
                 AddToBody(array, patternDetails.IndirectReference);
                 documentSpotPatterns[details] = patternDetails;
             }
             return patternDetails;
         }
         default:
             throw new Exception("Invalid color type in PdfWriter.AddSimplePatternColorspace().");
     }
 }
Exemplo n.º 22
0
 internal PdfImportedLink(PdfDictionary annotation)
 {
     parameters = (Hashtable)annotation.hashMap.Clone();
     try {
         destination = (PdfArray)parameters[PdfName.DEST];
         parameters.Remove(PdfName.DEST);
     } catch (Exception) {
         throw new ArgumentException("You have to consolidate the named destinations of your reader.");
     }
     if (destination != null) {
         destination = new PdfArray(destination);
     }
     PdfArray rc = (PdfArray)parameters[PdfName.RECT];
     parameters.Remove(PdfName.RECT);
     llx = rc.GetAsNumber(0).FloatValue;
     lly = rc.GetAsNumber(1).FloatValue;
     urx = rc.GetAsNumber(2).FloatValue;
     ury = rc.GetAsNumber(3).FloatValue;
 }
Exemplo n.º 23
0
 private static void GetOCGOrder(PdfArray order, PdfLayer layer)
 {
     if (!layer.OnPanel)
         return;
     if (layer.Title == null)
         order.Add(layer.Ref);
     ArrayList children = layer.Children;
     if (children == null)
         return;
     PdfArray kids = new PdfArray();
     if (layer.Title != null)
         kids.Add(new PdfString(layer.Title, PdfObject.TEXT_UNICODE));
     for (int k = 0; k < children.Count; ++k) {
         GetOCGOrder(kids, (PdfLayer)children[k]);
     }
     if (kids.Size > 0)
         order.Add(kids);
 }
Exemplo n.º 24
0
 /** Generates the font dictionary for this font.
  * @return the PdfDictionary containing the font dictionary
  * @param subsetPrefix the subset prefx
  * @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>
  * @throws DocumentException if there is an error
  */
 protected PdfDictionary GetFontBaseType(PdfIndirectReference fontDescriptor, string subsetPrefix, int firstChar, int lastChar, byte[] shortTag)
 {
     PdfDictionary dic = new PdfDictionary(PdfName.FONT);
     if (cff) {
         dic.Put(PdfName.SUBTYPE, PdfName.TYPE1);
         dic.Put(PdfName.BASEFONT, new PdfName(fontName + style));
     }
     else {
         dic.Put(PdfName.SUBTYPE, PdfName.TRUETYPE);
         dic.Put(PdfName.BASEFONT, new PdfName(subsetPrefix + fontName + style));
     }
     dic.Put(PdfName.BASEFONT, new PdfName(subsetPrefix + fontName + style));
     if (!fontSpecific) {
         for (int k = firstChar; k <= lastChar; ++k) {
             if (!differences[k].Equals(notdef)) {
                 firstChar = k;
                 break;
             }
         }
     if (encoding.Equals(CP1252) || encoding.Equals(MACROMAN))
             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);
         }
     }
     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 (fontDescriptor != null)
         dic.Put(PdfName.FONTDESCRIPTOR, fontDescriptor);
     return dic;
 }
Exemplo n.º 25
0
            /**
            * Returns the CrossReferenceTable of the <CODE>Body</CODE>.
            * @param os
            * @param root
            * @param info
            * @param encryption
            * @param fileID
            * @param prevxref
            * @throws IOException
            */
            internal void WriteCrossReferenceTable(Stream os, PdfIndirectReference root, PdfIndirectReference info, PdfIndirectReference encryption, PdfObject fileID, int prevxref)
            {
                int refNumber = 0;
                if (writer.FullCompression) {
                    FlushObjStm();
                    refNumber = IndirectReferenceNumber;
                    xrefs[new PdfCrossReference(refNumber, position)] = null;
                }
                int first = ((PdfCrossReference)xrefs.GetMinKey()).Refnum;
                int len = 0;
                ArrayList sections = new ArrayList();
                foreach (PdfCrossReference entry in xrefs.Keys) {
                    if (first + len == entry.Refnum)
                        ++len;
                    else {
                        sections.Add(first);
                        sections.Add(len);
                        first = entry.Refnum;
                        len = 1;
                    }
                }
                sections.Add(first);
                sections.Add(len);
                if (writer.FullCompression) {
                    int mid = 4;
                    uint mask = 0xff000000;
                    for (; mid > 1; --mid) {
                        if ((mask & position) != 0)
                            break;
                        mask >>= 8;
                    }
                    ByteBuffer buf = new ByteBuffer();

                    foreach (PdfCrossReference entry in xrefs.Keys) {
                        entry.ToPdf(mid, buf);
                    }
                    PdfStream xr = new PdfStream(buf.ToByteArray());
                    buf = null;
                    xr.FlateCompress(writer.CompressionLevel);
                    xr.Put(PdfName.SIZE, new PdfNumber(Size));
                    xr.Put(PdfName.ROOT, root);
                    if (info != null) {
                        xr.Put(PdfName.INFO, info);
                    }
                    if (encryption != null)
                        xr.Put(PdfName.ENCRYPT, encryption);
                    if (fileID != null)
                        xr.Put(PdfName.ID, fileID);
                    xr.Put(PdfName.W, new PdfArray(new int[]{1, mid, 2}));
                    xr.Put(PdfName.TYPE, PdfName.XREF);
                    PdfArray idx = new PdfArray();
                    for (int k = 0; k < sections.Count; ++k)
                        idx.Add(new PdfNumber((int)sections[k]));
                    xr.Put(PdfName.INDEX, idx);
                    if (prevxref > 0)
                        xr.Put(PdfName.PREV, new PdfNumber(prevxref));
                    PdfEncryption enc = writer.crypto;
                    writer.crypto = null;
                    PdfIndirectObject indirect = new PdfIndirectObject(refNumber, xr, writer);
                    indirect.WriteTo(writer.Os);
                    writer.crypto = enc;
                }
                else {
                    byte[] tmp = GetISOBytes("xref\n");
                    os.Write(tmp, 0, tmp.Length);
                    IEnumerator i = xrefs.Keys;
                    i.MoveNext();
                    for (int k = 0; k < sections.Count; k += 2) {
                        first = (int)sections[k];
                        len = (int)sections[k + 1];
                        tmp = GetISOBytes(first.ToString());
                        os.Write(tmp, 0, tmp.Length);
                        os.WriteByte((byte)' ');
                        tmp = GetISOBytes(len.ToString());
                        os.Write(tmp, 0, tmp.Length);
                        os.WriteByte((byte)'\n');
                        while (len-- > 0) {
                            ((PdfCrossReference)i.Current).ToPdf(os);
                            i.MoveNext();
                        }
                    }
                }
            }
Exemplo n.º 26
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;
 }
Exemplo n.º 27
0
 /**
 * Sets different values in a list selection.
 * No appearance is generated yet; nor does the code check if multiple select is allowed.
 *
 * @param    name    the name of the field
 * @param    value   an array with values that need to be selected
 * @return   true only if the field value was changed
 * @since 2.1.4
 */
 public bool SetListSelection(String name, String[] value)
 {
     Item item = GetFieldItem(name);
     if (item == null)
         return false;
     PdfName type = item.GetMerged(0).GetAsName(PdfName.FT);
     if (!PdfName.CH.Equals(type)) {
         return false;
     }
     String[] options = GetListOptionExport(name);
     PdfArray array = new PdfArray();
     for (int i = 0; i < value.Length; i++) {
         for (int j = 0; j < options.Length; j++) {
             if (options[j].Equals(value[i])) {
                 array.Add(new PdfNumber(j));
             }
         }
     }
     item.WriteToAll(PdfName.I, array, Item.WRITE_MERGED | Item.WRITE_VALUE);
     item.WriteToAll(PdfName.V, null, Item.WRITE_MERGED | Item.WRITE_VALUE);
     item.WriteToAll(PdfName.AP, null, Item.WRITE_MERGED | Item.WRITE_WIDGET);
     item.MarkUsed( this, Item.WRITE_VALUE | Item.WRITE_WIDGET );
     return true;
 }
Exemplo n.º 28
0
 public static PdfFunction Type3(PdfWriter writer, float[] domain, float[] range, PdfFunction[] functions, float[] bounds, float[] encode)
 {
     PdfFunction func = new PdfFunction(writer);
     func.dictionary = new PdfDictionary();
     func.dictionary.Put(PdfName.FUNCTIONTYPE, new PdfNumber(3));
     func.dictionary.Put(PdfName.DOMAIN, new PdfArray(domain));
     if (range != null)
         func.dictionary.Put(PdfName.RANGE, new PdfArray(range));
     PdfArray array = new PdfArray();
     for (int k = 0; k < functions.Length; ++k)
         array.Add(functions[k].Reference);
     func.dictionary.Put(PdfName.FUNCTIONS, array);
     func.dictionary.Put(PdfName.BOUNDS, new PdfArray(bounds));
     func.dictionary.Put(PdfName.ENCODE, new PdfArray(encode));
     return func;
 }
Exemplo n.º 29
0
 private int RemoveRefFromArray(PdfArray array, PdfObject refo)
 {
     if (refo == null || !refo.IsIndirect())
         return array.Size;
     PdfIndirectReference refi = (PdfIndirectReference)refo;
     for (int j = 0; j < array.Size; ++j) {
         PdfObject obj = array[j];
         if (!obj.IsIndirect())
             continue;
         if (((PdfIndirectReference)obj).Number == refi.Number)
             array.Remove(j--);
     }
     return array.Size;
 }
Exemplo n.º 30
0
 internal static PdfArray CreateDestinationArray(String value, PdfWriter writer)
 {
     PdfArray ar = new PdfArray();
     StringTokenizer tk = new StringTokenizer(value);
     int n = int.Parse(tk.NextToken());
     ar.Add(writer.GetPageReference(n));
     if (!tk.HasMoreTokens()) {
         ar.Add(PdfName.XYZ);
         ar.Add(new float[]{0, 10000, 0});
     }
     else {
         String fn = tk.NextToken();
         if (fn.StartsWith("/"))
             fn = fn.Substring(1);
         ar.Add(new PdfName(fn));
         for (int k = 0; k < 4 && tk.HasMoreTokens(); ++k) {
             fn = tk.NextToken();
             if (fn.Equals("null"))
                 ar.Add(PdfNull.PDFNULL);
             else
                 ar.Add(new PdfNumber(fn));
         }
     }
     return ar;
 }
Exemplo n.º 31
0
 private PdfObject SimplifyColorspace(PdfArray obj)
 {
     if (obj == null)
         return obj;
     PdfObject first = obj.GetAsName(0);
     if (PdfName.CALGRAY.Equals(first))
         return PdfName.DEVICEGRAY;
     else if (PdfName.CALRGB.Equals(first))
         return PdfName.DEVICERGB;
     else
         return obj;
 }
Exemplo n.º 32
0
 /**
 * Adds an image to the document but not to the page resources. It is used with
 * templates and <CODE>Document.Add(Image)</CODE>.
 * @param image the <CODE>Image</CODE> to add
 * @param fixedRef the reference to used. It may be <CODE>null</CODE>,
 * a <CODE>PdfIndirectReference</CODE> or a <CODE>PRIndirectReference</CODE>.
 * @return the name of the image added
 * @throws PdfException on error
 * @throws DocumentException on error
 */
 public PdfName AddDirectImageSimple(Image image, PdfIndirectReference fixedRef)
 {
     PdfName name;
     // if the images is already added, just retrieve the name
     if (images.ContainsKey(image.MySerialId)) {
         name = (PdfName) images[image.MySerialId];
     }
     // if it's a new image, add it to the document
     else {
         if (image.IsImgTemplate()) {
             name = new PdfName("img" + images.Count);
             if (image is ImgWMF){
                 ImgWMF wmf = (ImgWMF)image;
                 wmf.ReadWMF(PdfTemplate.CreateTemplate(this, 0, 0));
             }
         }
         else {
             PdfIndirectReference dref = image.DirectReference;
             if (dref != null) {
                 PdfName rname = new PdfName("img" + images.Count);
                 images[image.MySerialId] = rname;
                 imageDictionary.Put(rname, dref);
                 return rname;
             }
             Image maskImage = image.ImageMask;
             PdfIndirectReference maskRef = null;
             if (maskImage != null) {
                 PdfName mname = (PdfName)images[maskImage.MySerialId];
                 maskRef = GetImageReference(mname);
             }
             PdfImage i = new PdfImage(image, "img" + images.Count, maskRef);
             if (image is ImgJBIG2) {
                 byte[] globals = ((ImgJBIG2) image).GlobalBytes;
                 if (globals != null) {
                     PdfDictionary decodeparms = new PdfDictionary();
                     decodeparms.Put(PdfName.JBIG2GLOBALS, GetReferenceJBIG2Globals(globals));
                     i.Put(PdfName.DECODEPARMS, decodeparms);
                 }
             }
             if (image.HasICCProfile()) {
                 PdfICCBased icc = new PdfICCBased(image.TagICC, image.CompressionLevel);
                 PdfIndirectReference iccRef = Add(icc);
                 PdfArray iccArray = new PdfArray();
                 iccArray.Add(PdfName.ICCBASED);
                 iccArray.Add(iccRef);
                 PdfArray colorspace = i.GetAsArray(PdfName.COLORSPACE);
                 if (colorspace != null) {
                     if (colorspace.Size > 1 && PdfName.INDEXED.Equals(colorspace[0]))
                         colorspace[1] = iccArray;
                     else
                         i.Put(PdfName.COLORSPACE, iccArray);
                 }
                 else
                     i.Put(PdfName.COLORSPACE, iccArray);
             }
             Add(i, fixedRef);
             name = i.Name;
         }
         images[image.MySerialId] = name;
     }
     return name;
 }
Exemplo n.º 33
0
 /**
 * Compresses the stream.
 * @param compressionLevel the compression level (0 = best speed, 9 = best compression, -1 is default)
 * @since   2.1.3
 */
 public void FlateCompress(int compressionLevel)
 {
     if (!Document.Compress)
         return;
     // check if the flateCompress-method has allready been
     if (compressed) {
         return;
     }
     this.compressionLevel = compressionLevel;
     if (inputStream != null) {
         compressed = true;
         return;
     }
     // check if a filter allready exists
     PdfObject filter = PdfReader.GetPdfObject(Get(PdfName.FILTER));
     if (filter != null) {
         if (filter.IsName()) {
             if (PdfName.FLATEDECODE.Equals(filter))
                 return;
         }
         else if (filter.IsArray()) {
             if (((PdfArray) filter).Contains(PdfName.FLATEDECODE))
                 return;
         }
         else {
             throw new PdfException("Stream could not be compressed: filter is not a name or array.");
         }
     }
     // compress
     MemoryStream stream = new MemoryStream();
     var zip = new ZOutputStream(stream, compressionLevel);
     if (streamBytes != null)
         streamBytes.WriteTo(zip);
     else
         zip.Write(bytes, 0, bytes.Length);
     //zip.Close();
     zip.Finish();
     // update the object
     streamBytes = stream;
     bytes = null;
     Put(PdfName.LENGTH, new PdfNumber(streamBytes.Length));
     if (filter == null) {
         Put(PdfName.FILTER, PdfName.FLATEDECODE);
     }
     else {
         PdfArray filters = new PdfArray(filter);
         filters.Add(PdfName.FLATEDECODE);
         Put(PdfName.FILTER, filters);
     }
     compressed = true;
 }
Exemplo n.º 34
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(Hashtable items, PdfWriter writer)
        {
            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((PdfObject)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((PdfObject)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;
            }
        }