Beispiel #1
0
        public byte[] Decode(PdfObject decodedObject, byte[] inputData, DecodeParameters decodeParameters)
        {
            FIBITMAP myImage = new FIBITMAP();
            using (MemoryStream stream = new MemoryStream(inputData))
            {
                myImage = FreeImage.LoadFromStream(stream);
            }

            Bitmap bitmap = FreeImage.GetBitmap(myImage);

            decodedObject.ColorSpace = ColorSpace.RGB;

            byte[] result = new byte[decodedObject.Width * decodedObject.Height * 3];

            for (int i = 0; i < decodedObject.Width; i++)
            {
                for (int j = 0; j < decodedObject.Height; j++)
                {
                    Color pixel = bitmap.GetPixel(i, j);

                    int index = j * decodedObject.Width + i;
                    result[index * 3] = pixel.R;
                    result[index * 3 + 1] = pixel.G;
                    result[index * 3 + 2] = pixel.B;
                }
            }

            return result;
        }
Beispiel #2
0
    // About PdfReference 
    // 
    // * A PdfReference holds the either ObjectID or the PdfObject or both.
    // 
    // * Each PdfObject has a PdfReference if and only if it is an indirect object. Direct objects have
    //   no PdfReference, because they are embedded in a parent objects.
    //
    // * PdfReference objects are used to reference PdfObject instances. A value in a PDF dictionary
    //   or array that is a PdfReference represents an indirect reference. A value in a PDF dictionary or
    //   or array that is a PdfObject represents a direct (or embeddded) object.
    //
    // * When a PDF file is imported, the PdfXRefTable is filled with PdfReference objects keeping the
    //   ObjectsIDs and file positions (offsets) of all indirect objects.
    //
    // * Indirect objects can easily be renumbered because they do not rely on their ObjectsIDs.
    //
    // * During modification of a document the ObjectID of an indirect object has no meaning,
    //   except that they must be different in pairs.

    /// <summary>
    /// Initializes a new PdfReference instance for the specified indirect object.
    /// </summary>
    public PdfReference(PdfObject pdfObject)
    {
      Debug.Assert(pdfObject.Reference == null, "Must not create iref for an object that already has one.");
      this.value = pdfObject;
#if UNIQUE_IREF && DEBUG
      this.uid = ++PdfReference.counter;
#endif
    }
        internal PdfDictionary(
			PdfObject	Parent
			)
        {
            KeyValue = new List<PdfKeyValue>();
            this.Parent = Parent;
            this.Document = Parent.Document;
            return;
        }
 /**
  * Processes an object. If the object is indirect, it is added to the
  * list of resources. If not, it is just processed.
  * @param object    the object to process
  */
 protected void Process(PdfObject @object) {
     PRIndirectReference @ref = @object.IndRef;
     if (@ref == null) {
         LoopOver(@object);
     } else {
         bool containsKey = resources.ContainsKey(@ref.Number);
         resources[@ref.Number] = @object;
         if (!containsKey)
             LoopOver(@object);
     }
 }
 virtual public void CacheObject(PdfIndirectReference iref, PdfObject obj) {
     if (obj.Type == 0) {
         cachedObjects[new RefKey(iref)] = obj;
     }
     else if (obj is PdfDictionary) {
         cachedObjects[new RefKey(iref)] = CleverPdfDictionaryClone((PdfDictionary) obj);
     }
     else if (obj.IsArray()) {
         cachedObjects[new RefKey(iref)] = CleverPdfArrayClone((PdfArray) obj);
     }
 }
 /**
  * Creates a StructureObject for an OBJR dictionary.
  * @param structElem	the parent structure element
  * @param ref			the reference of the parent structure element
  * @param dict			the object reference dictionary
  */
 public StructureObject(PdfDictionary structElem, PdfIndirectReference refa, PdfDictionary dict) {
     this.structElem = structElem;
     this.refa = refa;
     this.obj = dict.GetDirectObject(PdfName.OBJ);
     this.objref = dict.GetAsIndirectObject(PdfName.OBJ);
     this.structParent = ((PdfDictionary) obj).GetAsNumber(PdfName.STRUCTPARENT).IntValue;
     PdfIndirectReference pg = dict.GetAsIndirectObject(PdfName.PG);
     if (pg == null)
         pg = structElem.GetAsIndirectObject(PdfName.PG);
     this.pageref = pg.Number;
 }
        /// <summary>
        /// Adds a PdfObject to the table.
        /// </summary>
        public void Add(PdfObject value)
        {
            if (value.Owner == null)
                value.Document = _document;
            else
                Debug.Assert(value.Owner == _document);

            if (value.ObjectID.IsEmpty)
                value.SetObjectID(GetNewObjectNumber(), 0);

            if (ObjectTable.ContainsKey(value.ObjectID))
                throw new InvalidOperationException("Object already in table.");

            ObjectTable.Add(value.ObjectID, value.Reference);
        }
Beispiel #8
0
 internal PdfIndirectObject Add(PdfObject objecta, int refNumber, bool inObjStm)
 {
     if (inObjStm && objecta.CanBeInObjStm() && writer.FullCompression) {
         PdfCrossReference pxref = AddToObjStm(objecta, refNumber);
         PdfIndirectObject indirect = new PdfIndirectObject(refNumber, objecta, writer);
         xrefs.Remove(pxref);
         xrefs[pxref] = null;
         return indirect;
     }
     else {
         PdfIndirectObject indirect = new PdfIndirectObject(refNumber, objecta, writer);
         PdfCrossReference pxref = new PdfCrossReference(refNumber, position);
         xrefs.Remove(pxref);
         xrefs[pxref] = null;
         indirect.WriteTo(writer.Os);
         position = writer.Os.Counter;
         return indirect;
     }
 }
Beispiel #9
0
 private PdfWriter.PdfBody.PdfCrossReference AddToObjStm(PdfObject obj, int nObj)
 {
     if (numObj >= OBJSINSTREAM)
         FlushObjStm();
     if (index == null) {
         index = new ByteBuffer();
         streamObjects = new ByteBuffer();
         currentObjNum = IndirectReferenceNumber;
         numObj = 0;
     }
     int p = streamObjects.Size;
     int idx = numObj++;
     PdfEncryption enc = writer.crypto;
     writer.crypto = null;
     obj.ToPdf(writer, streamObjects);
     writer.crypto = enc;
     streamObjects.Append(' ');
     index.Append(nObj).Append(' ').Append(p).Append(' ');
     return new PdfWriter.PdfBody.PdfCrossReference(2, nObj, currentObjNum, idx);
 }
Beispiel #10
0
 /// <summary>
 /// Hack for dead objects.
 /// </summary>
 internal void SetObject(PdfObject value)
 {
   this.value = value;
 }
Beispiel #11
0
        internal PdfFormXObject(PdfDocument thisDocument, PdfImportedObjectTable importedObjectTable, XPdfForm form)
            : base(thisDocument)
        {
            Debug.Assert(ReferenceEquals(thisDocument, importedObjectTable.Owner));
            Elements.SetName(Keys.Type, "/XObject");
            Elements.SetName(Keys.Subtype, "/Form");

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

            XPdfForm pdfForm = form;
            // Get import page
            PdfPages importPages = importedObjectTable.ExternalDocument.Pages;

            if (pdfForm.PageNumber < 1 || pdfForm.PageNumber > importPages.Count)
            {
                PSSR.ImportPageNumberOutOfRange(pdfForm.PageNumber, importPages.Count, form._path);
            }
            PdfPage importPage = importPages[pdfForm.PageNumber - 1];

            // Import resources
            PdfItem res = importPage.Elements["/Resources"];

            if (res != null) // unlikely but possible
            {
#if true
                // Get root object
                PdfObject root;
                if (res is PdfReference)
                {
                    root = ((PdfReference)res).Value;
                }
                else
                {
                    root = (PdfDictionary)res;
                }

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

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

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

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

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

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

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

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

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

            // (no cloning needed because the bytes keep untouched)
            Stream = content.Stream; // new PdfStream(bytes, this);
            Elements.SetInteger("/Length", content.Stream.Value.Length);
        }
 virtual protected PdfObject GetDirectObject(PdfObject obj) {
     if (obj == null)
         return null;
     //use counter to prevent indirect reference cycling
     int count = 0;
     // resolve references
     while (obj is PdfIndirectReference) {
         PdfObject curr;
         if (obj.IsIndirect())
             curr = PdfReader.GetPdfObject(obj);
         else
             cachedObjects.TryGetValue(new RefKey((PdfIndirectReference) obj), out curr);
         if (curr == null) break;
         obj = curr;
         //10 - is max allowed reference chain
         if (count++ > 10)
             break;
     }
     return obj;
 }
Beispiel #13
0
 public Indexed(PdfObject @base, int hival, PdfString lookup)
     : this(GetIndexedCsArray(@base, hival, lookup))
 {
 }
Beispiel #14
0
 /// <summary>
 /// Sets the black-generation function value or
 /// <c>Default</c>
 /// ,
 /// <c>BG2</c>
 /// key.
 /// Note, if both
 /// <c>BG</c>
 /// and
 /// <c>BG2</c>
 /// are present in the same graphics state parameter dictionary,
 /// <c>BG2</c>
 /// takes precedence.
 /// </summary>
 /// <param name="blackGenerationFunction2">
 /// a
 /// <see cref="iText.Kernel.Pdf.PdfObject"/>
 /// value, shall be either
 /// <see cref="iText.Kernel.Pdf.Function.PdfFunction"/>
 /// or
 /// <c>Default</c>
 /// .
 /// </param>
 /// <returns>object itself.</returns>
 public virtual iText.Kernel.Pdf.Extgstate.PdfExtGState SetBlackGenerationFunction2(PdfObject blackGenerationFunction2
                                                                                    )
 {
     return(Put(PdfName.BG2, blackGenerationFunction2));
 }
Beispiel #15
0
 private void MarkUsed(PdfObject obj)
 {
     if (!append)
         return;
     ((PdfStamperImp)writer).MarkUsed(obj);
 }
Beispiel #16
0
 /// <summary>
 /// Sets the current soft mask,
 /// <c>SMask</c>
 /// key.
 /// </summary>
 /// <param name="sMask">
 /// a
 /// <see cref="iText.Kernel.Pdf.PdfObject"/>
 /// , shall be either
 /// <see cref="iText.Kernel.Pdf.PdfName"/>
 /// or
 /// <see cref="iText.Kernel.Pdf.PdfDictionary"/>
 /// .
 /// </param>
 /// <returns>object itself.</returns>
 public virtual iText.Kernel.Pdf.Extgstate.PdfExtGState SetSoftMask(PdfObject sMask)
 {
     return(Put(PdfName.SMask, sMask));
 }
Beispiel #17
0
 /// <summary>Puts the value into Graphics state parameter dictionary and associates it with the specified key.
 ///     </summary>
 /// <remarks>
 /// Puts the value into Graphics state parameter dictionary and associates it with the specified key.
 /// If the key is already present, it will override the old value with the specified one.
 /// </remarks>
 /// <param name="key">key to insert or to override</param>
 /// <param name="value">the value to associate with the specified key</param>
 /// <returns>object itself.</returns>
 public virtual iText.Kernel.Pdf.Extgstate.PdfExtGState Put(PdfName key, PdfObject value)
 {
     GetPdfObject().Put(key, value);
     return(this);
 }
        /// <summary>Updates current graphic state with values from extended graphic state dictionary.</summary>
        /// <param name="extGState">the wrapper around the extended graphic state dictionary</param>
        /// <param name="pdfDocument">the document to retrieve fonts from. Needed when the newly created fonts are used
        ///     </param>
        internal virtual void UpdateFromExtGState(PdfExtGState extGState, PdfDocument pdfDocument)
        {
            float?lw = extGState.GetLineWidth();

            if (lw != null)
            {
                lineWidth = (float)lw;
            }
            int?lc = extGState.GetLineCapStyle();

            if (lc != null)
            {
                lineCapStyle = (int)lc;
            }
            int?lj = extGState.GetLineJoinStyle();

            if (lj != null)
            {
                lineJoinStyle = (int)lj;
            }
            float?ml = extGState.GetMiterLimit();

            if (ml != null)
            {
                miterLimit = (float)ml;
            }
            PdfArray d = extGState.GetDashPattern();

            if (d != null)
            {
                dashPattern = d;
            }
            PdfName ri = extGState.GetRenderingIntent();

            if (ri != null)
            {
                renderingIntent = ri;
            }
            bool?op = extGState.GetStrokeOverprintFlag();

            if (op != null)
            {
                strokeOverprint = (bool)op;
            }
            op = extGState.GetFillOverprintFlag();
            if (op != null)
            {
                fillOverprint = (bool)op;
            }
            int?opm = extGState.GetOverprintMode();

            if (opm != null)
            {
                overprintMode = (int)opm;
            }
            PdfArray fnt = extGState.GetFont();

            if (fnt != null)
            {
                PdfDictionary fontDictionary = fnt.GetAsDictionary(0);
                if (this.font == null || this.font.GetPdfObject() != fontDictionary)
                {
                    this.font = pdfDocument.GetFont(fontDictionary);
                }
                PdfNumber fntSz = fnt.GetAsNumber(1);
                if (fntSz != null)
                {
                    this.fontSize = fntSz.FloatValue();
                }
            }
            PdfObject bg = extGState.GetBlackGenerationFunction();

            if (bg != null)
            {
                blackGenerationFunction = bg;
            }
            PdfObject bg2 = extGState.GetBlackGenerationFunction2();

            if (bg2 != null)
            {
                blackGenerationFunction2 = bg2;
            }
            PdfObject ucr = extGState.GetUndercolorRemovalFunction();

            if (ucr != null)
            {
                underColorRemovalFunction = ucr;
            }
            PdfObject ucr2 = extGState.GetUndercolorRemovalFunction2();

            if (ucr2 != null)
            {
                underColorRemovalFunction2 = ucr2;
            }
            PdfObject tr = extGState.GetTransferFunction();

            if (tr != null)
            {
                transferFunction = tr;
            }
            PdfObject tr2 = extGState.GetTransferFunction2();

            if (tr2 != null)
            {
                transferFunction2 = tr2;
            }
            PdfObject ht = extGState.GetHalftone();

            if (ht != null)
            {
                halftone = ht;
            }
            PdfObject local_htp = extGState.GetPdfObject().Get(PdfName.HTP);

            if (local_htp != null)
            {
                this.htp = local_htp;
            }
            float?fl = extGState.GetFlatnessTolerance();

            if (fl != null)
            {
                flatnessTolerance = (float)fl;
            }
            float?sm = extGState.GetSmothnessTolerance();

            if (sm != null)
            {
                smoothnessTolerance = sm;
            }
            bool?sa = extGState.GetAutomaticStrokeAdjustmentFlag();

            if (sa != null)
            {
                automaticStrokeAdjustment = (bool)sa;
            }
            PdfObject bm = extGState.GetBlendMode();

            if (bm != null)
            {
                blendMode = bm;
            }
            PdfObject sMask = extGState.GetSoftMask();

            if (sMask != null)
            {
                softMask = sMask;
            }
            float?ca = extGState.GetStrokeOpacity();

            if (ca != null)
            {
                strokeAlpha = (float)ca;
            }
            ca = extGState.GetFillOpacity();
            if (ca != null)
            {
                fillAlpha = (float)ca;
            }
            bool?ais = extGState.GetAlphaSourceFlag();

            if (ais != null)
            {
                alphaIsShape = (bool)ais;
            }
            bool?tk = extGState.GetTextKnockoutFlag();

            if (tk != null)
            {
                textKnockout = (bool)tk;
            }
        }
        private PdfFormField MergeFieldsWithTheSameName(PdfFormField newField)
        {
            String    fullFieldName = newField.GetFieldName().ToUnicodeString();
            PdfString fieldName     = newField.GetPdfObject().GetAsString(PdfName.T);

            logger.Warn(MessageFormatUtil.Format(iText.IO.LogMessageConstant.DOCUMENT_ALREADY_HAS_FIELD, fullFieldName
                                                 ));
            PdfFormField existingField = formTo.GetField(fullFieldName);

            if (existingField.IsFlushed())
            {
                int index = 0;
                do
                {
                    index++;
                    newField.SetFieldName(fieldName.ToUnicodeString() + "_#" + index);
                    fullFieldName = newField.GetFieldName().ToUnicodeString();
                }while (formTo.GetField(fullFieldName) != null);
                return(newField);
            }
            newField.GetPdfObject().Remove(PdfName.T);
            newField.GetPdfObject().Remove(PdfName.P);
            formTo.GetFields().Remove(existingField.GetPdfObject());
            PdfArray kids = existingField.GetKids();

            if (kids != null && !kids.IsEmpty())
            {
                existingField.AddKid(newField);
                return(existingField);
            }
            existingField.GetPdfObject().Remove(PdfName.T);
            existingField.GetPdfObject().Remove(PdfName.P);
            PdfFormField mergedField = PdfFormField.CreateEmptyField(documentTo);

            mergedField.Put(PdfName.FT, existingField.GetFormType()).Put(PdfName.T, fieldName);
            PdfDictionary parent = existingField.GetParent();

            if (parent != null)
            {
                mergedField.Put(PdfName.Parent, parent);
                PdfArray parentKids = parent.GetAsArray(PdfName.Kids);
                for (int i = 0; i < parentKids.Size(); i++)
                {
                    PdfObject obj = parentKids.Get(i);
                    if (obj == existingField.GetPdfObject())
                    {
                        parentKids.Set(i, mergedField.GetPdfObject());
                        break;
                    }
                }
            }
            kids = existingField.GetKids();
            if (kids != null)
            {
                mergedField.Put(PdfName.Kids, kids);
            }
            mergedField.AddKid(existingField).AddKid(newField);
            PdfObject value = existingField.GetValue();

            if (value != null)
            {
                mergedField.Put(PdfName.V, existingField.GetPdfObject().Get(PdfName.V));
            }
            return(mergedField);
        }
Beispiel #20
0
        /**
         * decodes the bytes currently captured in the streamBytes and replaces it with an image representation of the bytes
         * (this will either be a png or a tiff, depending on the color depth of the image)
         * @throws IOException
         */
        private void DecodeImageBytes()
        {
            if (streamContentType != null)
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("Decoding.can't.happen.on.this.type.of.stream.(.1.)", streamContentType.FileExtension));
            }
            pngColorType = -1;
            PdfArray decode = dictionary.GetAsArray(PdfName.DECODE);

            width       = dictionary.GetAsNumber(PdfName.WIDTH).IntValue;
            height      = dictionary.GetAsNumber(PdfName.HEIGHT).IntValue;
            bpc         = dictionary.GetAsNumber(PdfName.BITSPERCOMPONENT).IntValue;
            pngBitDepth = bpc;
            PdfObject colorspace = dictionary.GetDirectObject(PdfName.COLORSPACE);

            if (colorspace is PdfName && colorSpaceDic != null)
            {
                PdfObject csLookup = colorSpaceDic.GetDirectObject((PdfName)colorspace);
                if (csLookup != null)
                {
                    colorspace = csLookup;
                }
            }

            palette = null;
            icc     = null;
            stride  = 0;
            FindColorspace(colorspace, true);
            MemoryStream ms = new MemoryStream();

            if (pngColorType < 0)
            {
                if (bpc != 8)
                {
                    throw new UnsupportedPdfException(MessageLocalization.GetComposedMessage("the.color.depth.1.is.not.supported", bpc));
                }
                if (PdfName.DEVICECMYK.Equals(colorspace))
                {
                }
                else if (colorspace is PdfArray)
                {
                    PdfArray  ca   = (PdfArray)colorspace;
                    PdfObject tyca = ca.GetDirectObject(0);
                    if (!PdfName.ICCBASED.Equals(tyca))
                    {
                        throw new UnsupportedPdfException(MessageLocalization.GetComposedMessage("the.color.space.1.is.not.supported", colorspace));
                    }
                    PRStream pr = (PRStream)ca.GetDirectObject(1);
                    int      n  = pr.GetAsNumber(PdfName.N).IntValue;
                    if (n != 4)
                    {
                        throw new UnsupportedPdfException(MessageLocalization.GetComposedMessage("N.value.1.is.not.supported", n));
                    }
                    icc = PdfReader.GetStreamBytes(pr);
                }
                else
                {
                    throw new UnsupportedPdfException(MessageLocalization.GetComposedMessage("the.color.space.1.is.not.supported", colorspace));
                }
                stride = 4 * width;
                TiffWriter wr = new TiffWriter();
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL, 4));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_BITSPERSAMPLE, new int[] { 8, 8, 8, 8 }));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_PHOTOMETRIC, TIFFConstants.PHOTOMETRIC_SEPARATED));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_IMAGEWIDTH, width));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_IMAGELENGTH, height));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_COMPRESSION, TIFFConstants.COMPRESSION_LZW));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_PREDICTOR, TIFFConstants.PREDICTOR_HORIZONTAL_DIFFERENCING));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP, height));
                wr.AddField(new TiffWriter.FieldRational(TIFFConstants.TIFFTAG_XRESOLUTION, new int[] { 300, 1 }));
                wr.AddField(new TiffWriter.FieldRational(TIFFConstants.TIFFTAG_YRESOLUTION, new int[] { 300, 1 }));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_RESOLUTIONUNIT, TIFFConstants.RESUNIT_INCH));
                wr.AddField(new TiffWriter.FieldAscii(TIFFConstants.TIFFTAG_SOFTWARE, Version.GetInstance().GetVersion));
                MemoryStream comp = new MemoryStream();
                TiffWriter.CompressLZW(comp, 2, imageBytes, height, 4, stride);
                byte[] buf = comp.ToArray();
                wr.AddField(new TiffWriter.FieldImage(buf));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_STRIPBYTECOUNTS, buf.Length));
                if (icc != null)
                {
                    wr.AddField(new TiffWriter.FieldUndefined(TIFFConstants.TIFFTAG_ICCPROFILE, icc));
                }
                wr.WriteFile(ms);
                streamContentType = ImageBytesType.CCITT;
                imageBytes        = ms.ToArray();
                return;
            }
            else
            {
                PngWriter png = new PngWriter(ms);
                if (decode != null)
                {
                    if (pngBitDepth == 1)
                    {
                        // if the decode array is 1,0, then we need to invert the image
                        if (decode.GetAsNumber(0).IntValue == 1 && decode.GetAsNumber(1).IntValue == 0)
                        {
                            int len = imageBytes.Length;
                            for (int t = 0; t < len; ++t)
                            {
                                imageBytes[t] ^= 0xff;
                            }
                        }
                        else
                        {
                            // if the decode array is 0,1, do nothing.  It's possible that the array could be 0,0 or 1,1 - but that would be silly, so we'll just ignore that case
                        }
                    }
                    else
                    {
                        // todo: add decode transformation for other depths
                    }
                }
                png.WriteHeader(width, height, pngBitDepth, pngColorType);
                if (icc != null)
                {
                    png.WriteIccProfile(icc);
                }
                if (palette != null)
                {
                    png.WritePalette(palette);
                }
                png.WriteData(imageBytes, stride);
                png.WriteEnd();
                streamContentType = ImageBytesType.PNG;
                imageBytes        = ms.ToArray();
            }
        }
Beispiel #21
0
 /**
  * Transforms value abbreviations into their corresponding real value 
  * @param key the key that the value is for
  * @param value the value that might be an abbreviation
  * @return if value is an allowed abbreviation for the key, the expanded value for that abbreviation.  Otherwise, value is returned without modification 
  */
 private static PdfObject GetAlternateValue(PdfName key, PdfObject value){
     if (key == PdfName.FILTER){
         if (value is PdfName){
             PdfName altValue;
             inlineImageFilterAbbreviationMap.TryGetValue((PdfName)value, out altValue);
             if (altValue != null)
                 return altValue;
         } else if (value is PdfArray){
             PdfArray array = ((PdfArray)value);
             PdfArray altArray = new PdfArray();
             int count = array.Size;
             for (int i = 0; i < count; i++){
                 altArray.Add(GetAlternateValue(key, array[i]));
             }
             return altArray;
         }
     } else if (key == PdfName.COLORSPACE){
         if (value is PdfName){
             PdfName altValue;
             inlineImageColorSpaceAbbreviationMap.TryGetValue((PdfName)value, out altValue);
             if (altValue != null)
                 return altValue;
         }
     }
     
     return value;
 }
Beispiel #22
0
 /// <summary>
 /// Sets the undercolor-removal function value or
 /// <c>Default</c>
 /// ,
 /// <c>UCR2</c>
 /// key.
 /// Note, if both
 /// <c>UCR</c>
 /// and
 /// <c>UCR2</c>
 /// are present in the same graphics state parameter dictionary,
 /// <c>UCR2</c>
 /// takes precedence.
 /// </summary>
 /// <param name="undercolorRemovalFunction2">
 /// a
 /// <see cref="iText.Kernel.Pdf.PdfObject"/>
 /// value, shall be either
 /// <see cref="iText.Kernel.Pdf.Function.PdfFunction"/>
 /// or
 /// <c>Default</c>
 /// .
 /// </param>
 /// <returns>object itself.</returns>
 public virtual iText.Kernel.Pdf.Extgstate.PdfExtGState SetUndercolorRemovalFunction2(PdfObject undercolorRemovalFunction2
                                                                                      )
 {
     return(Put(PdfName.UCR2, undercolorRemovalFunction2));
 }
Beispiel #23
0
 /**
  * Searches for a tag in a page.
  * 
  * @param tag
  *            the name of the tag
  * @param obj
  *            an identifier to find the marked content
  * @param page
  *            a page dictionary
  * @throws IOException
  */
 public virtual void ParseTag(String tag, PdfObject obj, PdfDictionary page) {
     // if the identifier is a number, we can extract the content right away
     if (obj is PdfNumber) {
         PdfNumber mcid = (PdfNumber) obj;
         RenderFilter filter = new MarkedContentRenderFilter(mcid.IntValue);
         ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
         FilteredTextRenderListener listener = new FilteredTextRenderListener(strategy, new RenderFilter[]{filter});
         PdfContentStreamProcessor processor = new PdfContentStreamProcessor(
                 listener);
         processor.ProcessContent(PdfReader.GetPageContent(page), page
                 .GetAsDict(PdfName.RESOURCES));
         outp.Write(XMLUtil.EscapeXML(listener.GetResultantText(), true));
     }
     // if the identifier is an array, we call the parseTag method
     // recursively
     else if (obj is PdfArray) {
         PdfArray arr = (PdfArray) obj;
         int n = arr.Size;
         for (int i = 0; i < n; i++) {
             ParseTag(tag, arr[i], page);
             if (i < n - 1)
                 outp.WriteLine();
         }
     }
     // if the identifier is a dictionary, we get the resources from the
     // dictionary
     else if (obj is PdfDictionary) {
         PdfDictionary mcr = (PdfDictionary) obj;
         ParseTag(tag, mcr.GetDirectObject(PdfName.MCID), mcr
                 .GetAsDict(PdfName.PG));
     }
 }
Beispiel #24
0
 /// <summary>
 /// Sets the transfer function value or
 /// <c>Default</c>
 /// ,
 /// <c>TR2</c>
 /// key.
 /// Note, if both
 /// <c>TR</c>
 /// and
 /// <c>TR2</c>
 /// are present in the same graphics state parameter dictionary,
 /// <c>TR2</c>
 /// takes precedence.
 /// </summary>
 /// <param name="transferFunction2">
 /// a
 /// <see cref="iText.Kernel.Pdf.PdfObject"/>
 /// , shall be either
 /// <see cref="iText.Kernel.Pdf.Function.PdfFunction"/>
 /// ,
 /// <see cref="iText.Kernel.Pdf.PdfArray"/>
 /// ,
 /// <see cref="iText.Kernel.Pdf.PdfName"/>
 /// or
 /// <c>Default</c>
 /// .
 /// </param>
 /// <returns>object itself.</returns>
 public virtual iText.Kernel.Pdf.Extgstate.PdfExtGState SetTransferFunction2(PdfObject transferFunction2)
 {
     return(Put(PdfName.TR2, transferFunction2));
 }
Beispiel #25
0
 /**
 * This function writes the given key/value pair to all the instances
 * of merged, widget, and/or value, depending on the <code>writeFlags</code> setting
 *
 * @since 2.1.5
 *
 * @param key        you'll never guess what this is for.
 * @param value      if value is null, the key will be removed
 * @param writeFlags ORed together WRITE_* flags
 */
 public void WriteToAll(PdfName key, PdfObject value, int writeFlags)
 {
     int i;
     PdfDictionary curDict = null;
     if ((writeFlags & WRITE_MERGED) != 0) {
         for (i = 0; i < merged.Count; ++i) {
             curDict = GetMerged(i);
             curDict.Put(key, value);
         }
     }
     if ((writeFlags & WRITE_WIDGET) != 0) {
         for (i = 0; i < widgets.Count; ++i) {
             curDict = GetWidget(i);
             curDict.Put(key, value);
         }
     }
     if ((writeFlags & WRITE_VALUE) != 0) {
         for (i = 0; i < values.Count; ++i) {
             curDict = GetValue(i);
             curDict.Put(key, value);
         }
     }
 }
Beispiel #26
0
 /// <summary>
 /// Sets the halftone or
 /// <c>Default</c>
 /// ,
 /// <c>HT</c>
 /// key.
 /// </summary>
 /// <param name="halftone">
 /// a
 /// <see cref="iText.Kernel.Pdf.PdfObject"/>
 /// , shall be either
 /// <see cref="iText.Kernel.Pdf.PdfDictionary"/>
 /// ,
 /// <see cref="iText.Kernel.Pdf.PdfStream"/>
 /// or
 /// <see cref="iText.Kernel.Pdf.PdfName"/>
 /// .
 /// </param>
 /// <returns>object itself.</returns>
 public virtual iText.Kernel.Pdf.Extgstate.PdfExtGState SetHalftone(PdfObject halftone)
 {
     return(Put(PdfName.HT, halftone));
 }
 virtual protected PdfStream GetDirectStream(PdfObject obj) {
     obj = GetDirectObject(obj);
     if (obj != null && obj.IsStream())
         return (PdfStream) obj;
     return null;
 }
Beispiel #28
0
 public virtual iText.Kernel.Pdf.Extgstate.PdfExtGState SetHTP(PdfObject htp)
 {
     return(Put(PdfName.HTP, htp));
 }
        ////////////////////////////////////////////////////////////////////
        // Initial Object Array
        ////////////////////////////////////////////////////////////////////
        private void ConstructorHelper(
			Double		Width,			// page width
			Double		Height,			// page height
			Double		ScaleFactor,	// scale factor from user units to points (i.e. 72.0 for inch)
			String		FileName,
			Stream		OutputStream
			)
        {
            // set scale factor (user units to points)
            this.ScaleFactor = ScaleFactor;

            // save page default size
            PageSize = new SizeD(Width, Height);

            // PDF document root object the Catalog object
            CatalogObject = new PdfObject(this, ObjectType.Dictionary, "/Catalog");

            // add viewer preferences
            CatalogObject.Dictionary.Add("/ViewerPreferences", "<</PrintScaling/None>>");

            // Parent object for all pages
            PagesObject = new PdfObject(this, ObjectType.Dictionary, "/Pages");

            // add indirect reference to pages within the catalog object
            CatalogObject.Dictionary.AddIndirectReference("/Pages", PagesObject);

            // document id
            DocumentID = RandomByteArray(16);

            // create file using file name
            if(FileName != null)
            {
            // save file name
            this.FileName = FileName;

            // constructor helper
            PdfFile = new PdfBinaryWriter(new FileStream(FileName, FileMode.Create, FileAccess.Write, FileShare.None));
            }

            // write to caller's file or memory stream
            else
            {
            PdfFile = new PdfBinaryWriter(OutputStream);
            }

            // write PDF version number
            PdfFile.WriteString("%PDF-1.7\n");

            // add this comment to tell compression programs that this is a binary file
            PdfFile.WriteString("%\u00b5\u00b5\u00b5\u00b5\n");

            // exit
            return;
        }
Beispiel #30
0
 /// <summary>
 /// Sets the current blend mode for the transparent imaging model,
 /// <c>BM</c>
 /// key.
 /// </summary>
 /// <param name="blendMode">
 /// a
 /// <see cref="iText.Kernel.Pdf.PdfObject"/>
 /// , shall be either
 /// <see cref="iText.Kernel.Pdf.PdfName"/>
 /// or
 /// <see cref="iText.Kernel.Pdf.PdfArray"/>
 /// .
 /// </param>
 /// <returns>object itself.</returns>
 public virtual iText.Kernel.Pdf.Extgstate.PdfExtGState SetBlendMode(PdfObject blendMode)
 {
     return(Put(PdfName.BM, blendMode));
 }
Beispiel #31
0
 /**
  * Sets state of this object according to the color space
  * @param colorspace the colorspace to use
  * @param allowIndexed whether indexed color spaces will be resolved (used for recursive call)
  * @throws IOException if there is a problem with reading from the underlying stream
  */
 private void FindColorspace(PdfObject colorspace, bool allowIndexed)
 {
     if (colorspace == null && bpc == 1)  // handle imagemasks
     {
         stride       = (width * bpc + 7) / 8;
         pngColorType = 0;
     }
     else if (PdfName.DEVICEGRAY.Equals(colorspace))
     {
         stride       = (width * bpc + 7) / 8;
         pngColorType = 0;
     }
     else if (PdfName.DEVICERGB.Equals(colorspace))
     {
         if (bpc == 8 || bpc == 16)
         {
             stride       = (width * bpc * 3 + 7) / 8;
             pngColorType = 2;
         }
     }
     else if (colorspace is PdfArray)
     {
         PdfArray  ca   = (PdfArray)colorspace;
         PdfObject tyca = ca.GetDirectObject(0);
         if (PdfName.CALGRAY.Equals(tyca))
         {
             stride       = (width * bpc + 7) / 8;
             pngColorType = 0;
         }
         else if (PdfName.CALRGB.Equals(tyca))
         {
             if (bpc == 8 || bpc == 16)
             {
                 stride       = (width * bpc * 3 + 7) / 8;
                 pngColorType = 2;
             }
         }
         else if (PdfName.ICCBASED.Equals(tyca))
         {
             PRStream pr = (PRStream)ca.GetDirectObject(1);
             int      n  = pr.GetAsNumber(PdfName.N).IntValue;
             if (n == 1)
             {
                 stride       = (width * bpc + 7) / 8;
                 pngColorType = 0;
                 icc          = PdfReader.GetStreamBytes(pr);
             }
             else if (n == 3)
             {
                 stride       = (width * bpc * 3 + 7) / 8;
                 pngColorType = 2;
                 icc          = PdfReader.GetStreamBytes(pr);
             }
         }
         else if (allowIndexed && PdfName.INDEXED.Equals(tyca))
         {
             FindColorspace(ca.GetDirectObject(1), false);
             if (pngColorType == 2)
             {
                 PdfObject id2 = ca.GetDirectObject(3);
                 if (id2 is PdfString)
                 {
                     palette = ((PdfString)id2).GetBytes();
                 }
                 else if (id2 is PRStream)
                 {
                     palette = PdfReader.GetStreamBytes(((PRStream)id2));
                 }
                 stride       = (width * bpc + 7) / 8;
                 pngColorType = 3;
             }
         }
     }
 }
Beispiel #32
0
        protected override void CheckPdfObject(PdfWriter writer, int key, Object obj1)
        {
            if (obj1 is PdfNumber)
            {
                PdfNumber number = (PdfNumber)obj1;
                if (Math.Abs(number.DoubleValue) > maxRealValue && number.ToString().Contains("."))
                {
                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("real.number.is.out.of.range"));
                }
            }
            else if (obj1 is PdfString)
            {
                PdfString str = (PdfString)obj1;
                if (str.GetBytes().Length > maxStringLength)
                {
                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("pdf.string.is.too.long"));
                }
            }
            else if (obj1 is PdfArray)
            {
                PdfArray array = (PdfArray)obj1;
                if (array.Size > maxArrayLength)
                {
                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("pdf.array.exceeds.length.set.by.PDFA1.standard", array.Length.ToString()));
                }
            }
            else if (obj1 is PdfDictionary)
            {
                PdfDictionary dictionary = (PdfDictionary)obj1;
                if (dictionary.Size > maxDictionaryLength)
                {
                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("pdf.dictionary.is.out.of.bounds"));
                }
                PdfName type = dictionary.GetAsName(PdfName.TYPE);
                if (PdfName.CATALOG.Equals(type))
                {
                    if (!dictionary.Contains(PdfName.METADATA))
                    {
                        throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("the.document.catalog.dictionary.shall.contain.metadata"));
                    }

                    if (dictionary.Contains(PdfName.AA))
                    {
                        throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("the.document.catalog.dictionary.shall.not.include.an.aa.entry"));
                    }

                    if (dictionary.Contains(PdfName.NAMES))
                    {
                        PdfDictionary names = GetDirectDictionary(dictionary.Get(PdfName.NAMES));
                        if (names != null && names.Contains(PdfName.EMBEDDEDFILES))
                        {
                            throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("the.document.catalog.dictionary.shall.not.include.embeddedfiles.names.entry"));
                        }
                    }

                    if (CheckStructure(conformanceLevel))
                    {
                        PdfDictionary markInfo = GetDirectDictionary(dictionary.Get(PdfName.MARKINFO));
                        if (markInfo == null || markInfo.GetAsBoolean(PdfName.MARKED) == null || markInfo.GetAsBoolean(PdfName.MARKED).BooleanValue == false)
                        {
                            throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("document.catalog.dictionary.shall.include.a.markinfo.dictionary.whose.entry.marked.shall.have.a.value.of.true"));
                        }
                        if (!dictionary.Contains(PdfName.LANG))
                        {
                            if (LOGGER.IsLogging(Level.WARN))
                            {
                                LOGGER.Warn(MessageLocalization.GetComposedMessage("document.catalog.dictionary.should.contain.lang.entry"));
                            }
                        }
                    }
                }
                else if (PdfName.PAGE.Equals(type))
                {
                    if (dictionary.Contains(PdfName.AA))
                    {
                        throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("page.dictionary.shall.not.include.aa.entry"));
                    }
                }
                else if (PdfName.OUTPUTINTENT.Equals(type))
                {
                    isCheckOutputIntent = true;
                    PdfObject destOutputIntent = dictionary.Get(PdfName.DESTOUTPUTPROFILE);
                    if (destOutputIntent != null && pdfaDestOutputIntent != null)
                    {
                        if (pdfaDestOutputIntent.IndRef != destOutputIntent.IndRef)
                        {
                            throw new PdfAConformanceException(obj1,
                                                               MessageLocalization.GetComposedMessage(
                                                                   "if.outputintents.array.more.than.one.entry.the.same.indirect.object"));
                        }
                    }
                    else
                    {
                        pdfaDestOutputIntent = destOutputIntent;
                    }

                    PdfName gts = dictionary.GetAsName(PdfName.S);
                    if (pdfaDestOutputIntent != null)
                    {
                        if (PdfName.GTS_PDFA1.Equals(gts))
                        {
                            if (pdfaOutputIntentColorSpace != null)
                            {
                                throw new PdfAConformanceException(obj1,
                                                                   MessageLocalization.GetComposedMessage("a.pdfa.file.may.have.only.one.pdfa.outputintent"));
                            }
                            pdfaOutputIntentColorSpace = "";
                            ICC_Profile icc_profile = writer.ColorProfile;
                            pdfaOutputIntentColorSpace = Encoding.GetEncoding("US-ASCII").GetString(icc_profile.Data, 16, 4);
                        }
                    }
                    else
                    {
                        throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("outputintent.shall.have.gtspdfa1.and.destoutputintent"));
                    }
                }
            }
        }
Beispiel #33
0
        /// <summary>
        /// Replace all indirect references to external objects by their cloned counterparts
        /// owned by the importer document.
        /// </summary>
        void FixUpObject_old(PdfImportedObjectTable iot, PdfObject value)
        {
            // TODO: merge with PdfXObject.FixUpObject
            PdfDictionary dict;
            PdfArray      array;

            if ((dict = value as PdfDictionary) != null)
            {
                // Set document for cloned direct objects
                if (dict.Owner == null)
                {
                    dict.Document = Owner;
                }
                else
                {
                    Debug.Assert(dict.Owner == Owner);
                }

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

                // Search for indirect references in all array elements
                int count = array.Elements.Count;
                for (int idx = 0; idx < count; idx++)
                {
                    PdfItem item = array.Elements[idx];
                    // Is item an iref?
                    PdfReference iref = item as PdfReference;
                    if (iref != null)
                    {
                        // Does the iref belongs to this document?
                        if (iref.Document == Owner)
                        {
                            // Yes: fine
                            continue;
                        }
                        else
                        {
                            Debug.Assert(iref.Document == iot.ExternalDocument);
                            // No: replace with iref of cloned object
                            PdfReference newXRef = iot[iref.ObjectID];
                            Debug.Assert(newXRef != null);
                            Debug.Assert(newXRef.Document == Owner);
                            array.Elements[idx] = newXRef;
                        }
                    }
                    else if (item is PdfObject)
                    {
                        // Fix up inner objects
                        FixUpObject_old(iot, (PdfObject)item);
                    }
                }
            }
        }
Beispiel #34
0
 protected override void CheckAnnotation(PdfWriter writer, int key, Object obj1)
 {
     if (obj1 is PdfFormField)
     {
         PdfFormField field = (PdfFormField)obj1;
         if (!field.Contains(PdfName.SUBTYPE))
         {
             return;
         }
         if (field.Contains(PdfName.AA) || field.Contains(PdfName.A))
         {
             throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("widget.annotation.dictionary.or.field.dictionary.shall.not.include.a.or.aa.entry"));
         }
     }
     if (obj1 is PdfAnnotation)
     {
         PdfAnnotation annot   = (PdfAnnotation)obj1;
         PdfName       subtype = annot.Get(PdfName.SUBTYPE) as PdfName;
         if (subtype != null && !allowedAnnotTypes.Contains(subtype))
         {
             throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("annotation.type.1.not.allowed", subtype.ToString()));
         }
         PdfNumber ca = annot.GetAsNumber(PdfName.CA);
         if (ca != null && ca.FloatValue != 1.0)
         {
             throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("an.annotation.dictionary.shall.not.contain.the.ca.key.with.a.value.other.than.1"));
         }
         PdfNumber f = annot.GetAsNumber(PdfName.F);
         if (f == null)
         {
             throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("an.annotation.dictionary.shall.contain.the.f.key"));
         }
         int flags = f.IntValue;
         if (CheckFlag(flags, PdfAnnotation.FLAGS_PRINT) == false || CheckFlag(flags, PdfAnnotation.FLAGS_HIDDEN) ||
             CheckFlag(flags, PdfAnnotation.FLAGS_INVISIBLE) || CheckFlag(flags, PdfAnnotation.FLAGS_NOVIEW))
         {
             throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("the.f.keys.print.flag.bit.shall.be.set.to.1.and.its.hidden.invisible.and.noview.flag.bits.shall.be.set.to.0"));
         }
         if (PdfName.TEXT.Equals(annot.GetAsName(PdfName.SUBTYPE)))
         {
             if (CheckFlag(flags, PdfAnnotation.FLAGS_NOZOOM) == false || CheckFlag(flags, PdfAnnotation.FLAGS_NOROTATE) == false)
             {
                 throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("text.annotations.should.set.the.nozoom.and.norotate.flag.bits.of.the.f.key.to.1"));
             }
         }
         if (annot.Contains(PdfName.C) || annot.Contains(PdfName.IC))
         {
             ICC_Profile colorProfile = ((PdfAWriter)writer).ColorProfile;
             String      cs           = "";
             cs = System.Text.Encoding.ASCII.GetString(colorProfile.Data, 16, 4);
             cs = cs.Trim();
             if (!"RGB".Equals(cs.ToUpper()))
             {
                 throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("destoutputprofile.in.the.pdfa1.outputintent.dictionary.shall.be.rgb"));
             }
         }
         PdfDictionary ap = GetDirectDictionary(annot.Get(PdfName.AP));
         if (ap != null)
         {
             if (ap.Contains(PdfName.R) || ap.Contains(PdfName.D))
             {
                 throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("appearance.dictionary.shall.contain.only.the.n.key.with.stream.value"));
             }
             PdfObject n = ap.Get(PdfName.N);
             if (!(n is PdfIndirectReference))
             {
                 throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("appearance.dictionary.shall.contain.only.the.n.key.with.stream.value"));
             }
         }
         if (PdfName.WIDGET.Equals(annot.GetAsName(PdfName.SUBTYPE)) && (annot.Contains(PdfName.AA) || annot.Contains(PdfName.A)))
         {
             throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("widget.annotation.dictionary.or.field.dictionary.shall.not.include.a.or.aa.entry"));
         }
         if (CheckStructure(conformanceLevel))
         {
             if (contentAnnotations.Contains(subtype) && !annot.Contains(PdfName.CONTENTS))
             {
                 throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("annotation.of.type.1.should.have.contents.key", subtype.ToString()));
             }
         }
     }
 }
Beispiel #35
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();
                        }
                    }
                }
            }
Beispiel #36
0
 virtual public void SetAccessibleAttribute(PdfName key, PdfObject value)
 {
     title.SetAccessibleAttribute(key, value);
 }
Beispiel #37
0
 // constructors
 /**
 * Constructs a PDF-Trailer.
 *
 * @param        size        the number of entries in the <CODE>PdfCrossReferenceTable</CODE>
 * @param        offset      offset of the <CODE>PdfCrossReferenceTable</CODE>
 * @param        root        an indirect reference to the root of the PDF document
 * @param        info        an indirect reference to the info object of the PDF document
 * @param encryption
 * @param fileID
 * @param prevxref
 */
 internal PdfTrailer(int size, int offset, PdfIndirectReference root, PdfIndirectReference info, PdfIndirectReference encryption, PdfObject fileID, int prevxref)
 {
     this.offset = offset;
     Put(PdfName.SIZE, new PdfNumber(size));
     Put(PdfName.ROOT, root);
     if (info != null) {
         Put(PdfName.INFO, info);
     }
     if (encryption != null)
         Put(PdfName.ENCRYPT, encryption);
     if (fileID != null)
         Put(PdfName.ID, fileID);
     if (prevxref > 0)
         Put(PdfName.PREV, new PdfNumber(prevxref));
 }
 public virtual void SetAttributes(PdfObject attributes)
 {
     Put(PdfName.A, attributes);
 }
Beispiel #39
0
 /**
  * Inspects a child of a structured element. This can be an array or a
  * dictionary.
  * 
  * @param k
  *            the child to inspect
  * @throws IOException
  */
 virtual public void InspectChild(PdfObject k) {
     if (k == null)
         return;
     if (k is PdfArray)
         InspectChildArray((PdfArray) k);
     else if (k is PdfDictionary)
         InspectChildDictionary((PdfDictionary) k);
 }
 public virtual iText.Kernel.Pdf.Tagging.PdfStructElem Put(PdfName key, PdfObject value)
 {
     GetPdfObject().Put(key, value);
     SetModified();
     return(this);
 }
    /// <summary>
    /// Replace all indirect references to external objects by their cloned counterparts
    /// owned by the importer document.
    /// </summary>
    void FixUpObject_old(PdfImportedObjectTable iot, PdfObject value)
    {
      // TODO: merge with PdfXObject.FixUpObject
      PdfDictionary dict;
      PdfArray array;
      if ((dict = value as PdfDictionary) != null)
      {
        // Set document for cloned direct objects
        if (dict.Owner == null)
          dict.Document = this.Owner;
        else
          Debug.Assert(dict.Owner == this.Owner);

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

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

            PdfSmartCopy.ByteStore streamKey = null;
            bool validStream = false;

            if (srcObj.IsStream())
            {
                streamKey   = new PdfSmartCopy.ByteStore((PRStream)srcObj, serialized);
                validStream = true;
                PdfIndirectReference streamRef;
                if (streamMap.TryGetValue(streamKey, out streamRef))
                {
                    return(streamRef);
                }
            }
            else if (srcObj.IsDictionary())
            {
                streamKey   = new PdfSmartCopy.ByteStore((PdfDictionary)srcObj, serialized);
                validStream = true;
                PdfIndirectReference streamRef;
                if (streamMap.TryGetValue(streamKey, out streamRef))
                {
                    return(streamRef);
                }
            }

            PdfIndirectReference theRef;
            RefKey             key = new RefKey(@in);
            IndirectReferences iRef;

            if (indirects.TryGetValue(key, out iRef))
            {
                theRef = iRef.Ref;
                if (iRef.Copied)
                {
                    return(theRef);
                }
            }
            else
            {
                theRef         = body.PdfIndirectReference;
                iRef           = new IndirectReferences(theRef);
                indirects[key] = iRef;
            }
            if (srcObj.IsDictionary())
            {
                PdfObject type = PdfReader.GetPdfObjectRelease(((PdfDictionary)srcObj).Get(PdfName.TYPE));
                if (type != null && PdfName.PAGE.Equals(type))
                {
                    return(theRef);
                }
            }
            iRef.SetCopied();

            if (validStream)
            {
                streamMap[streamKey] = theRef;
            }

            PdfObject obj = CopyObject(srcObj);

            AddToBody(obj, theRef);
            return(theRef);
        }
Beispiel #43
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;
 }
Beispiel #44
0
        /// <summary>
        /// Opens an existing PDF document.
        /// </summary>
        public static PdfDocument Open(Stream stream, string password, PdfDocumentOpenMode openmode, PdfPasswordProvider passwordProvider, PdfReadAccuracy accuracy)
        {
            PdfDocument document;

            try
            {
                Lexer lexer = new Lexer(stream);
                document           = new PdfDocument(lexer);
                document._state   |= DocumentState.Imported;
                document._openMode = openmode;
                document._fileSize = stream.Length;

                // Get file version.
                byte[] header = new byte[1024];
                stream.Position = 0;
                stream.Read(header, 0, 1024);
                document._version = GetPdfFileVersion(header);
                if (document._version == 0)
                {
                    throw new InvalidOperationException(PSSR.InvalidPdf);
                }

                document._irefTable.IsUnderConstruction = true;
                Parser parser = new Parser(document);

                // Read all trailers or cross-reference streams, but no objects.
                document._trailer = parser.ReadTrailer();

                if (document._trailer == null)
                {
                    ParserDiagnostics.ThrowParserException("Invalid PDF file: no trailer found.");
                }

                Debug.Assert(document._irefTable.IsUnderConstruction);
                document._irefTable.IsUnderConstruction = false;

                // Is document encrypted?
                PdfReference xrefEncrypt = document._trailer.Elements[PdfTrailer.Keys.Encrypt] as PdfReference;
                if (xrefEncrypt != null)
                {
                    //xrefEncrypt.Value = parser.ReadObject(null, xrefEncrypt.ObjectID, false);
                    PdfObject encrypt = parser.ReadObject(null, xrefEncrypt.ObjectID, false, false);

                    encrypt.Reference = xrefEncrypt;
                    xrefEncrypt.Value = encrypt;
                    PdfStandardSecurityHandler securityHandler = document.SecurityHandler;
TryAgain:
                    PasswordValidity validity = securityHandler.ValidatePassword(password);
                    if (validity == PasswordValidity.Invalid)
                    {
                        if (passwordProvider != null)
                        {
                            PdfPasswordProviderArgs args = new PdfPasswordProviderArgs();
                            passwordProvider(args);
                            if (args.Abort)
                            {
                                return(null);
                            }
                            password = args.Password;
                            goto TryAgain;
                        }
                        else
                        {
                            if (password == null)
                            {
                                throw new PdfReaderException(PSSR.PasswordRequired);
                            }
                            else
                            {
                                throw new PdfReaderException(PSSR.InvalidPassword);
                            }
                        }
                    }
                    else if (validity == PasswordValidity.UserPassword && openmode == PdfDocumentOpenMode.Modify)
                    {
                        if (passwordProvider != null)
                        {
                            PdfPasswordProviderArgs args = new PdfPasswordProviderArgs();
                            passwordProvider(args);
                            if (args.Abort)
                            {
                                return(null);
                            }
                            password = args.Password;
                            goto TryAgain;
                        }
                        else
                        {
                            throw new PdfReaderException(PSSR.OwnerPasswordRequired);
                        }
                    }
                }
                else
                {
                    if (password != null)
                    {
                        // Password specified but document is not encrypted.
                        // ignore
                    }
                }

                PdfReference[] irefs2 = document._irefTable.AllReferences;
                int            count2 = irefs2.Length;

                // 3rd: Create iRefs for all compressed objects.
                Dictionary <int, object> objectStreams = new Dictionary <int, object>();
                for (int idx = 0; idx < count2; idx++)
                {
                    PdfReference            iref       = irefs2[idx];
                    PdfCrossReferenceStream xrefStream = iref.Value as PdfCrossReferenceStream;
                    if (xrefStream != null)
                    {
                        for (int idx2 = 0; idx2 < xrefStream.Entries.Count; idx2++)
                        {
                            PdfCrossReferenceStream.CrossReferenceStreamEntry item = xrefStream.Entries[idx2];
                            // Is type xref to compressed object?
                            if (item.Type == 2)
                            {
                                //PdfReference irefNew = parser.ReadCompressedObject(new PdfObjectID((int)item.Field2), (int)item.Field3);
                                //document._irefTable.Add(irefNew);
                                int objectNumber = (int)item.Field2;
                                if (!objectStreams.ContainsKey(objectNumber))
                                {
                                    objectStreams.Add(objectNumber, null);
                                    PdfObjectID objectID = new PdfObjectID((int)item.Field2);
                                    parser.ReadIRefsFromCompressedObject(objectID);
                                }
                            }
                        }
                    }
                }

                // 4th: Read compressed objects.
                for (int idx = 0; idx < count2; idx++)
                {
                    PdfReference            iref       = irefs2[idx];
                    PdfCrossReferenceStream xrefStream = iref.Value as PdfCrossReferenceStream;
                    if (xrefStream != null)
                    {
                        for (int idx2 = 0; idx2 < xrefStream.Entries.Count; idx2++)
                        {
                            PdfCrossReferenceStream.CrossReferenceStreamEntry item = xrefStream.Entries[idx2];
                            // Is type xref to compressed object?
                            if (item.Type == 2)
                            {
                                PdfReference irefNew = parser.ReadCompressedObject(new PdfObjectID((int)item.Field2),
                                                                                   (int)item.Field3);
                                Debug.Assert(document._irefTable.Contains(iref.ObjectID));
                                //document._irefTable.Add(irefNew);
                            }
                        }
                    }
                }


                PdfReference[] irefs = document._irefTable.AllReferences;
                int            count = irefs.Length;

                // Read all indirect objects.
                for (int idx = 0; idx < count; idx++)
                {
                    PdfReference iref = irefs[idx];
                    if (iref.Value == null)
                    {
#if DEBUG_
                        if (iref.ObjectNumber == 1074)
                        {
                            iref.GetType();
                        }
#endif
                        try
                        {
                            Debug.Assert(document._irefTable.Contains(iref.ObjectID));
                            PdfObject pdfObject = parser.ReadObject(null, iref.ObjectID, false, false);
                            Debug.Assert(pdfObject.Reference == iref);
                            pdfObject.Reference = iref;
                            Debug.Assert(pdfObject.Reference.Value != null, "Something went wrong.");
                        }
                        catch (PositionNotFoundException ex)
                        {
                            Debug.WriteLine(ex.Message);

                            if (accuracy == PdfReadAccuracy.Strict)
                            {
                                throw;
                            }
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(ex.Message);
                            // 4STLA rethrow exception to notify caller.
                            throw;
                        }
                    }
                    else
                    {
                        Debug.Assert(document._irefTable.Contains(iref.ObjectID));
                        //iref.GetType();
                    }
                    // Set maximum object number.
                    document._irefTable._maxObjectNumber = Math.Max(document._irefTable._maxObjectNumber,
                                                                    iref.ObjectNumber);
                }

                // Encrypt all objects.
                if (xrefEncrypt != null)
                {
                    document.SecurityHandler.EncryptDocument();
                }

                // Fix references of trailer values and then objects and irefs are consistent.
                document._trailer.Finish();

#if DEBUG_
                // Some tests...
                PdfReference[] reachables = document.xrefTable.TransitiveClosure(document.trailer);
                reachables.GetType();
                reachables = document.xrefTable.AllXRefs;
                document.xrefTable.CheckConsistence();
#endif

                if (openmode == PdfDocumentOpenMode.Modify)
                {
                    // Create new or change existing document IDs.
                    if (document.Internals.SecondDocumentID == "")
                    {
                        document._trailer.CreateNewDocumentIDs();
                    }
                    else
                    {
                        byte[] agTemp = Guid.NewGuid().ToByteArray();
                        document.Internals.SecondDocumentID = PdfEncoders.RawEncoding.GetString(agTemp, 0, agTemp.Length);
                    }

                    // Change modification date
                    document.Info.ModificationDate = DateTime.Now;

                    // Remove all unreachable objects
                    int removed = document._irefTable.Compact();
                    if (removed != 0)
                    {
                        Debug.WriteLine("Number of deleted unreachable objects: " + removed);
                    }

                    // Force flattening of page tree
                    PdfPages pages = document.Pages;
                    Debug.Assert(pages != null);

                    //bool b = document.irefTable.Contains(new PdfObjectID(1108));
                    //b.GetType();

                    document._irefTable.CheckConsistence();
                    document._irefTable.Renumber();
                    document._irefTable.CheckConsistence();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                throw;
            }
            return(document);
        }
Beispiel #45
0
 internal PdfObjectInternals(PdfObject obj)
 {
     _obj = obj;
 }
        ///// <summary>
        ///// The garbage collector for PDF objects.
        ///// </summary>
        //public sealed class GC
        //{
        //  PdfXRefTable xrefTable;
        //
        //  internal GC(PdfXRefTable xrefTable)
        //  {
        //    _xrefTable = xrefTable;
        //  }
        //
        //  public void Collect()
        //  { }
        //
        //  public PdfReference[] ReachableObjects()
        //  {
        //    Hash_table objects = new Hash_table();
        //    TransitiveClosure(objects, _xrefTable.document.trailer);
        //  }

        /// <summary>
        /// Calculates the transitive closure of the specified PdfObject, i.e. all indirect objects
        /// recursively reachable from the specified object.
        /// </summary>
        public PdfReference[] TransitiveClosure(PdfObject pdfObject)
        {
            return(TransitiveClosure(pdfObject, short.MaxValue));
        }
 virtual protected PdfDictionary GetDirectDictionary(PdfObject obj) {
     obj = GetDirectObject(obj);
     if (obj != null && obj is PdfDictionary)
         return (PdfDictionary) obj;
     return null;
 }
        public static PdfViewerPreferencesImp GetViewerPreferences(PdfDictionary catalog)
        {
            PdfViewerPreferencesImp preferences = new PdfViewerPreferencesImp();
            int     prefs = 0;
            PdfName name  = null;
            // page layout
            PdfObject obj = PdfReader.GetPdfObjectRelease(catalog.Get(PdfName.PAGELAYOUT));

            if (obj != null && obj.IsName())
            {
                name = (PdfName)obj;
                if (name.Equals(PdfName.SINGLEPAGE))
                {
                    prefs |= PdfWriter.PageLayoutSinglePage;
                }
                else if (name.Equals(PdfName.ONECOLUMN))
                {
                    prefs |= PdfWriter.PageLayoutOneColumn;
                }
                else if (name.Equals(PdfName.TWOCOLUMNLEFT))
                {
                    prefs |= PdfWriter.PageLayoutTwoColumnLeft;
                }
                else if (name.Equals(PdfName.TWOCOLUMNRIGHT))
                {
                    prefs |= PdfWriter.PageLayoutTwoColumnRight;
                }
                else if (name.Equals(PdfName.TWOPAGELEFT))
                {
                    prefs |= PdfWriter.PageLayoutTwoPageLeft;
                }
                else if (name.Equals(PdfName.TWOPAGERIGHT))
                {
                    prefs |= PdfWriter.PageLayoutTwoPageRight;
                }
            }
            // page mode
            obj = PdfReader.GetPdfObjectRelease(catalog.Get(PdfName.PAGEMODE));
            if (obj != null && obj.IsName())
            {
                name = (PdfName)obj;
                if (name.Equals(PdfName.USENONE))
                {
                    prefs |= PdfWriter.PageModeUseNone;
                }
                else if (name.Equals(PdfName.USEOUTLINES))
                {
                    prefs |= PdfWriter.PageModeUseOutlines;
                }
                else if (name.Equals(PdfName.USETHUMBS))
                {
                    prefs |= PdfWriter.PageModeUseThumbs;
                }
                else if (name.Equals(PdfName.FULLSCREEN))
                {
                    prefs |= PdfWriter.PageModeFullScreen;
                }
                else if (name.Equals(PdfName.USEOC))
                {
                    prefs |= PdfWriter.PageModeUseOC;
                }
                else if (name.Equals(PdfName.USEATTACHMENTS))
                {
                    prefs |= PdfWriter.PageModeUseAttachments;
                }
            }
            // set page layout and page mode preferences
            preferences.ViewerPreferences = prefs;
            // other preferences
            obj = PdfReader.GetPdfObjectRelease(catalog
                                                .Get(PdfName.VIEWERPREFERENCES));
            if (obj != null && obj.IsDictionary())
            {
                PdfDictionary vp = (PdfDictionary)obj;
                for (int i = 0; i < VIEWER_PREFERENCES.Length; i++)
                {
                    obj = PdfReader.GetPdfObjectRelease(vp.Get(VIEWER_PREFERENCES[i]));
                    preferences.AddViewerPreference(VIEWER_PREFERENCES[i], obj);
                }
            }
            return(preferences);
        }
 virtual protected PdfArray GetDirectArray(PdfObject obj) {
     obj = GetDirectObject(obj);
     if (obj != null && obj.IsArray())
         return (PdfArray) obj;
     return null;
 }
 /**
  * Sets state of this object according to the color space 
  * @param colorspace the colorspace to use
  * @param allowIndexed whether indexed color spaces will be resolved (used for recursive call)
  * @throws IOException if there is a problem with reading from the underlying stream  
  */
 private void FindColorspace(PdfObject colorspace, bool allowIndexed) {
     if (colorspace == null && bpc == 1){ // handle imagemasks
         stride = (width*bpc + 7) / 8;
         pngColorType = 0;
     }
     else if (PdfName.DEVICEGRAY.Equals(colorspace)) {
         stride = (width * bpc + 7) / 8;
         pngColorType = 0;
     }
     else if (PdfName.DEVICERGB.Equals(colorspace)) {
         if (bpc == 8 || bpc == 16) {
             stride = (width * bpc * 3 + 7) / 8;
             pngColorType = 2;
         }
     }
     else if (colorspace is PdfArray) {
         PdfArray ca = (PdfArray)colorspace;
         PdfObject tyca = ca.GetDirectObject(0);
         if (PdfName.CALGRAY.Equals(tyca)) {
             stride = (width * bpc + 7) / 8;
             pngColorType = 0;
         }
         else if (PdfName.CALRGB.Equals(tyca)) {
             if (bpc == 8 || bpc == 16) {
                 stride = (width * bpc * 3 + 7) / 8;
                 pngColorType = 2;
             }
         }
         else if (PdfName.ICCBASED.Equals(tyca)) {
             PRStream pr = (PRStream)ca.GetDirectObject(1);
             int n = pr.GetAsNumber(PdfName.N).IntValue;
             if (n == 1) {
                 stride = (width * bpc + 7) / 8;
                 pngColorType = 0;
                 icc = PdfReader.GetStreamBytes(pr);
             }
             else if (n == 3) {
                 stride = (width * bpc * 3 + 7) / 8;
                 pngColorType = 2;
                 icc = PdfReader.GetStreamBytes(pr);
             }
         }
         else if (allowIndexed && PdfName.INDEXED.Equals(tyca)) {
             FindColorspace(ca.GetDirectObject(1), false);
             if (pngColorType == 2) {
                 PdfObject id2 = ca.GetDirectObject(3);
                 if (id2 is PdfString) {
                     palette = ((PdfString)id2).GetBytes();
                 }
                 else if (id2 is PRStream) {
                     palette = PdfReader.GetStreamBytes(((PRStream)id2));
                 }
                 stride = (width * bpc + 7) / 8;
                 pngColorType = 3;
             }
         }
     }
 }
        ////////////////////////////////////////////////////////////////////
        // C# string text to PDF strings only
        ////////////////////////////////////////////////////////////////////
        internal String TextToPdfString(
			String		Text,
			PdfObject	Parent
			)
        {
            // convert C# string to byte array
            Byte[] ByteArray = TextToByteArray(Text);

            // encryption is active. PDF string must be encrypted except for encryption dictionary
            if(Encryption != null && Encryption != Parent) ByteArray = Encryption.EncryptByteArray(Parent.ObjectNumber, ByteArray);

            // convert byte array to PDF string format
            return(ByteArrayToPdfString(ByteArray));
        }
Beispiel #52
0
 protected internal Pattern(PdfObject pdfObj)
     : base(pdfObj)
 {
 }
            private PdfDictionary GetPropertiesDictionary(PdfObject operand1, ResourceDictionary resources){
                if (operand1.IsDictionary())
                    return (PdfDictionary)operand1;

                PdfName dictionaryName = ((PdfName)operand1);
                return resources.GetAsDict(dictionaryName);
            }
        /**
         * Sets the viewer preferences for printing.
         */
        public virtual void AddViewerPreference(PdfName key, PdfObject value)
        {
            switch (GetIndex(key))
            {
            case 0:  // HIDETOOLBAR
            case 1:  // HIDEMENUBAR
            case 2:  // HIDEWINDOWUI
            case 3:  // FITWINDOW
            case 4:  // CENTERWINDOW
            case 5:  // DISPLAYDOCTITLE
            case 14: // PICKTRAYBYPDFSIZE
                if (value is PdfBoolean)
                {
                    viewerPreferences.Put(key, value);
                }
                break;

            case 6: // NONFULLSCREENPAGEMODE
                if (value is PdfName &&
                    IsPossibleValue((PdfName)value, NONFULLSCREENPAGEMODE_PREFERENCES))
                {
                    viewerPreferences.Put(key, value);
                }
                break;

            case 7: // DIRECTION
                if (value is PdfName &&
                    IsPossibleValue((PdfName)value, DIRECTION_PREFERENCES))
                {
                    viewerPreferences.Put(key, value);
                }
                break;

            case 8:  // VIEWAREA
            case 9:  // VIEWCLIP
            case 10: // PRINTAREA
            case 11: // PRINTCLIP
                if (value is PdfName &&
                    IsPossibleValue((PdfName)value, PAGE_BOUNDARIES))
                {
                    viewerPreferences.Put(key, value);
                }
                break;

            case 12: // PRINTSCALING
                if (value is PdfName &&
                    IsPossibleValue((PdfName)value, PRINTSCALING_PREFERENCES))
                {
                    viewerPreferences.Put(key, value);
                }
                break;

            case 13: // DUPLEX
                if (value is PdfName &&
                    IsPossibleValue((PdfName)value, DUPLEX_PREFERENCES))
                {
                    viewerPreferences.Put(key, value);
                }
                break;

            case 15: // PRINTPAGERANGE
                if (value is PdfArray)
                {
                    viewerPreferences.Put(key, value);
                }
                break;

            case 16: // NUMCOPIES
                if (value is PdfNumber)
                {
                    viewerPreferences.Put(key, value);
                }
                break;
            }
        }
        void TransitiveClosureImplementation(Dictionary <PdfItem, object> objects, PdfObject pdfObject /*, ref int depth*/)
        {
            try
            {
                _nestingLevel++;
                if (_nestingLevel >= 1000)
                {
                    if (!_overflow.ContainsKey(pdfObject))
                    {
                        _overflow.Add(pdfObject, null);
                    }
                    return;
                }
#if DEBUG_
                //enterCount++;
                if (enterCount == 5400)
                {
                    GetType();
                }
                //if (!Object.ReferenceEquals(pdfObject.Owner, _document))
                //  GetType();
                //////Debug.Assert(Object.ReferenceEquals(pdfObject27.Document, _document));
                //      if (item is PdfObject && ((PdfObject)item).ObjectID.ObjectNumber == 5)
                //        Debug.WriteLine("items: " + ((PdfObject)item).ObjectID.ToString());
                //if (pdfObject.ObjectNumber == 5)
                //  GetType();
#endif

                IEnumerable   enumerable = null; //(IEnumerator)pdfObject;
                PdfDictionary dict;
                PdfArray      array;
                if ((dict = pdfObject as PdfDictionary) != null)
                {
                    enumerable = dict.Elements.Values;
                }
                else if ((array = pdfObject as PdfArray) != null)
                {
                    enumerable = array.Elements;
                }
                else
                {
                    Debug.Assert(false, "Should not come here.");
                }

                if (enumerable != null)
                {
                    foreach (PdfItem item in enumerable)
                    {
                        PdfReference iref = item as PdfReference;
                        if (iref != null)
                        {
                            // Is this an indirect reference to an object that does not exist?
                            //if (iref.Document == null)
                            //{
                            //    Debug.WriteLine("Dead object detected: " + iref.ObjectID.ToString());
                            //    PdfReference dead = DeadObject;
                            //    iref.ObjectID = dead.ObjectID;
                            //    iref.Document = _document;
                            //    iref.SetObject(dead.Value);
                            //    PdfDictionary dict = (PdfDictionary)dead.Value;

                            //    dict.Elements["/DeadObjectCount"] =
                            //      new PdfInteger(dict.Elements.GetInteger("/DeadObjectCount") + 1);

                            //    iref = dead;
                            //}

                            if (!ReferenceEquals(iref.Document, _document))
                            {
                                GetType();
                                Debug.WriteLine(String.Format("Bad iref: {0}", iref.ObjectID.ToString()));
                            }
                            Debug.Assert(ReferenceEquals(iref.Document, _document) || iref.Document == null, "External object detected!");
#if DEBUG_
                            if (iref.ObjectID.ObjectNumber == 23)
                            {
                                GetType();
                            }
#endif
                            if (!objects.ContainsKey(iref))
                            {
                                PdfObject value = iref.Value;

                                // Ignore unreachable objets.
                                if (iref.Document != null)
                                {
                                    // ... from trailer hack
                                    if (value == null)
                                    {
                                        iref = ObjectTable[iref.ObjectID];
                                        Debug.Assert(iref.Value != null);
                                        value = iref.Value;
                                    }
                                    Debug.Assert(ReferenceEquals(iref.Document, _document));
                                    objects.Add(iref, null);
                                    //Debug.WriteLine(String.Format("objects.Add('{0}', null);", iref.ObjectID.ToString()));
                                    if (value is PdfArray || value is PdfDictionary)
                                    {
                                        TransitiveClosureImplementation(objects, value /*, ref depth*/);
                                    }
                                }
                                //else
                                //{
                                //  objects2.Add(this[iref.ObjectID], null);
                                //}
                            }
                        }
                        else
                        {
                            PdfObject pdfObject28 = item as PdfObject;
                            //if (pdfObject28 != null)
                            //  Debug.Assert(Object.ReferenceEquals(pdfObject28.Document, _document));
                            if (pdfObject28 != null && (pdfObject28 is PdfDictionary || pdfObject28 is PdfArray))
                            {
                                TransitiveClosureImplementation(objects, pdfObject28 /*, ref depth*/);
                            }
                        }
                    }
                }
            }
            finally
            {
                _nestingLevel--;
            }
        }
Beispiel #56
0
 public byte[] Decode(byte[] b, PdfName filterName, PdfObject decodeParams, PdfDictionary streamDictionary)
 {
     lastFilterName = filterName;
     return(b);
 }
        ////////////////////////////////////////////////////////////////////
        /// <summary>
        /// PDF chart constructor
        /// </summary>
        /// <param name="Document">Document object parent of this chart.</param>
        /// <param name="Chart">.NET Chart object.</param>
        /// <param name="Resolution">Resolution in pixels per inch (optional argument)</param>
        ////////////////////////////////////////////////////////////////////
        public PdfChart(
			PdfDocument		Document,
			Chart			Chart,
			Double			Resolution = 0.0	// pixels per inch
			)
            : base(Document, ObjectType.Stream, "/XObject")
        {
            // create resource code
            ResourceCode = Document.GenerateResourceNumber('X');

            // create stream length object
            ImageLengthObject = new PdfObject(Document, ObjectType.Other);
            Dictionary.AddIndirectReference("/Length", ImageLengthObject);

            // save chart
            this.Chart = Chart;

            // save resolution
            if(Resolution != 0)
            {
            // chart resolution in pixels per inch
            this.Resolution = Resolution;
            this.Chart.RenderingDpiY = Resolution;
            }
            else
            {
            this.Resolution = this.Chart.RenderingDpiY;
            }

            // calculate chart size in user coordinates
            Width = (Double) this.Chart.Width * 72.0 / (this.Resolution * Document.ScaleFactor);
            Height = (Double) this.Chart.Height * 72.0 / (this.Resolution * Document.ScaleFactor);

            // exit
            return;
        }
Beispiel #58
0
 virtual public void SetAccessibleProperty(PdfName key, PdfObject value)
 {
 }
 public byte[] Decode(byte[] b, PdfName filterName, PdfObject decodeParams, PdfDictionary streamDictionary) {
     lastFilterName = filterName;
     return b;
 }
 /// <summary>
 /// Sets a rich text string (see ISO-320001 12.7.3.4, "Rich Text Strings") that
 /// shall be displayed in the pop-up window when the annotation is opened.
 /// </summary>
 /// <param name="richText">text string or text stream that specifies rich text.</param>
 /// <returns>
 /// this
 /// <see cref="PdfMarkupAnnotation"/>
 /// instance.
 /// </returns>
 public virtual iText.Kernel.Pdf.Annot.PdfMarkupAnnotation SetRichText(PdfObject richText)
 {
     return((iText.Kernel.Pdf.Annot.PdfMarkupAnnotation)Put(PdfName.RC, richText));
 }