Ejemplo n.º 1
0
 public virtual void AddPages(iText.Kernel.Pdf.PdfPages pdfPages)
 {
     kids.Add(pdfPages.GetPdfObject());
     count.SetValue(count.IntValue() + pdfPages.GetCount());
     pdfPages.GetPdfObject().Put(PdfName.Parent, GetPdfObject());
     SetModified();
 }
        public virtual int?GetAttributeAsInt(String attributeName)
        {
            PdfName   name    = PdfStructTreeRoot.ConvertRoleToPdfName(attributeName);
            PdfNumber attrVal = GetPdfObject().GetAsNumber(name);

            return(attrVal != null ? (int?)attrVal.IntValue() : (int?)null);
        }
Ejemplo n.º 3
0
        internal static TrueTypeFont CreateFontProgram(PdfDictionary fontDictionary, FontEncoding fontEncoding)
        {
            iText.Kernel.Font.DocTrueTypeFont fontProgram = new iText.Kernel.Font.DocTrueTypeFont(fontDictionary);
            FillFontDescriptor(fontProgram, fontDictionary.GetAsDictionary(PdfName.FontDescriptor));
            PdfNumber firstCharNumber = fontDictionary.GetAsNumber(PdfName.FirstChar);
            int       firstChar       = firstCharNumber != null?Math.Max(firstCharNumber.IntValue(), 0) : 0;

            int[] widths = FontUtil.ConvertSimpleWidthsArray(fontDictionary.GetAsArray(PdfName.Widths), firstChar, fontProgram
                                                             .GetMissingWidth());
            fontProgram.avgWidth = 0;
            int glyphsWithWidths = 0;

            for (int i = 0; i < 256; i++)
            {
                Glyph glyph = new Glyph(i, widths[i], fontEncoding.GetUnicode(i));
                fontProgram.codeToGlyph[i] = glyph;
                //FontEncoding.codeToUnicode table has higher priority
                if (glyph.HasValidUnicode() && fontEncoding.ConvertToByte(glyph.GetUnicode()) == i)
                {
                    fontProgram.unicodeToGlyph[glyph.GetUnicode()] = glyph;
                }
                if (widths[i] > 0)
                {
                    glyphsWithWidths++;
                    fontProgram.avgWidth += widths[i];
                }
            }
            if (glyphsWithWidths != 0)
            {
                fontProgram.avgWidth /= glyphsWithWidths;
            }
            return(fontProgram);
        }
Ejemplo n.º 4
0
        public virtual void RegisterMcr(PdfMcr mcr)
        {
            SortedDictionary <int, PdfMcr> pageMcrs = pageToPageMcrs.Get(mcr.GetPageObject().GetIndirectReference());

            if (pageMcrs == null)
            {
                pageMcrs = new SortedDictionary <int, PdfMcr>();
                pageToPageMcrs[mcr.GetPageObject().GetIndirectReference()] = pageMcrs;
            }
            if (mcr is PdfObjRef)
            {
                PdfDictionary obj = ((PdfDictionary)mcr.GetPdfObject()).GetAsDictionary(PdfName.Obj);
                if (obj == null || obj.IsFlushed())
                {
                    throw new PdfException(PdfException.WhenAddingObjectReferenceToTheTagTreeItMustBeConnectedToNotFlushedObject
                                           );
                }
                PdfNumber n = obj.GetAsNumber(PdfName.StructParent);
                if (n != null)
                {
                    pageMcrs[StructParentIndexIntoKey(n.IntValue())] = mcr;
                }
                else
                {
                    throw new PdfException(PdfException.StructParentIndexNotFoundInTaggedObject);
                }
            }
            else
            {
                pageMcrs[mcr.GetMcid()] = mcr;
            }
        }
Ejemplo n.º 5
0
        public static iText.Kernel.Pdf.Colorspace.PdfPattern GetPatternInstance(PdfDictionary pdfObject)
        {
            PdfNumber type = pdfObject.GetAsNumber(PdfName.PatternType);

            if (type.IntValue() == 1 && pdfObject is PdfStream)
            {
                return(new PdfPattern.Tiling((PdfStream)pdfObject));
            }
            else
            {
                if (type.IntValue() == 2)
                {
                    return(new PdfPattern.Shading(pdfObject));
                }
            }
            throw new ArgumentException("pdfObject");
        }
        /// <summary>Computes the number of unfiltered bytes that each row of the image will contain.</summary>
        /// <remarks>
        /// Computes the number of unfiltered bytes that each row of the image will contain.
        /// If the number of bytes results in a partial terminating byte, this number is rounded up
        /// per the PDF specification
        /// </remarks>
        /// <param name="imageDictionary">the dictionary of the inline image</param>
        /// <returns>the number of bytes per row of the image</returns>
        private static int ComputeBytesPerRow(PdfDictionary imageDictionary, PdfDictionary colorSpaceDic)
        {
            PdfNumber wObj   = imageDictionary.GetAsNumber(PdfName.Width);
            PdfNumber bpcObj = imageDictionary.GetAsNumber(PdfName.BitsPerComponent);
            int       cpp    = GetComponentsPerPixel(imageDictionary.GetAsName(PdfName.ColorSpace), colorSpaceDic);
            int       w      = wObj.IntValue();
            int       bpc    = bpcObj != null?bpcObj.IntValue() : 1;

            return((w * bpc * cpp + 7) / 8);
        }
Ejemplo n.º 7
0
        private int NormalizeFirstLastChar(PdfNumber firstLast, int defaultValue)
        {
            if (firstLast == null)
            {
                return(defaultValue);
            }
            int result = firstLast.IntValue();

            return(result < 0 || result > 255 ? defaultValue : result);
        }
Ejemplo n.º 8
0
        private int NormalizeFirstLastChar(PdfNumber firstLast, int defaultValue)
        {
            if (firstLast == null)
            {
                return(defaultValue);
            }
            int result = firstLast.IntValue();

            return(result < 0 || result > PdfFont.SIMPLE_FONT_MAX_CHAR_CODE_VALUE ? defaultValue : result);
        }
Ejemplo n.º 9
0
        public virtual int GetFlags()
        {
            PdfNumber f = GetPdfObject().GetAsNumber(PdfName.F);

            if (f != null)
            {
                return(f.IntValue());
            }
            else
            {
                return(0);
            }
        }
Ejemplo n.º 10
0
        public virtual int GetStructParentIndex()
        {
            PdfNumber n = GetPdfObject().GetAsNumber(PdfName.StructParent);

            if (n == null)
            {
                return(-1);
            }
            else
            {
                return(n.IntValue());
            }
        }
Ejemplo n.º 11
0
        public virtual void SignExistingFieldWhenDirectAcroformAndNoSigFlagTest()
        {
            String src       = sourceFolder + "signExistingFieldWhenDirectAcroformAndNoSigFlag.pdf";
            String dest      = destinationFolder + "signExistingFieldWhenDirectAcroformAndNoSigFlag.pdf";
            String fieldName = "Signature1";

            Sign(src, fieldName, dest, chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CADES, PdfSigner.NOT_CERTIFIED
                 );
            PdfDocument doc     = new PdfDocument(new PdfReader(dest));
            PdfNumber   sigFlag = doc.GetCatalog().GetPdfObject().GetAsDictionary(PdfName.AcroForm).GetAsNumber(PdfName.
                                                                                                                SigFlags);

            NUnit.Framework.Assert.AreEqual(new PdfNumber(3).IntValue(), sigFlag.IntValue());
        }
Ejemplo n.º 12
0
 internal static int[] ConvertSimpleWidthsArray(PdfArray widthsArray, int first)
 {
     int[] res = new int[256];
     if (widthsArray == null)
     {
         return(res);
     }
     for (int i = 0; i < widthsArray.Size() && first + i < 256; i++)
     {
         PdfNumber number = widthsArray.GetAsNumber(i);
         res[first + i] = number != null?number.IntValue() : 0;
     }
     return(res);
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Creates an object that can inform you about the type of signature
        /// in a signature dictionary as well as some of the permissions
        /// defined by the signature.
        /// </summary>
        public SignaturePermissions(PdfDictionary sigDict, SignaturePermissions previous)
        {
            if (previous != null)
            {
                annotationsAllowed &= previous.IsAnnotationsAllowed();
                fillInAllowed      &= previous.IsFillInAllowed();
                fieldLocks.AddAll(previous.GetFieldLocks());
            }
            PdfArray @ref = sigDict.GetAsArray(PdfName.Reference);

            if (@ref != null)
            {
                for (int i = 0; i < @ref.Size(); i++)
                {
                    PdfDictionary dict    = @ref.GetAsDictionary(i);
                    PdfDictionary @params = dict.GetAsDictionary(PdfName.TransformParams);
                    if (PdfName.DocMDP.Equals(dict.GetAsName(PdfName.TransformMethod)))
                    {
                        certification = true;
                    }
                    PdfName action = @params.GetAsName(PdfName.Action);
                    if (action != null)
                    {
                        fieldLocks.Add(new SignaturePermissions.FieldLock(this, action, @params.GetAsArray(PdfName.Fields)));
                    }
                    PdfNumber p = @params.GetAsNumber(PdfName.P);
                    if (p == null)
                    {
                        continue;
                    }
                    switch (p.IntValue())
                    {
                    default: {
                        break;
                    }

                    case 1: {
                        fillInAllowed &= false;
                        goto case 2;
                    }

                    case 2: {
                        annotationsAllowed &= false;
                        break;
                    }
                    }
                }
            }
        }
Ejemplo n.º 14
0
        private void FillFontDescriptor(PdfDictionary fontDesc)
        {
            if (fontDesc == null)
            {
                return;
            }
            PdfNumber v = fontDesc.GetAsNumber(PdfName.ItalicAngle);

            if (v != null)
            {
                SetItalicAngle(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.FontWeight);
            if (v != null)
            {
                SetFontWeight(v.IntValue());
            }
            PdfName fontStretch = fontDesc.GetAsName(PdfName.FontStretch);

            if (fontStretch != null)
            {
                SetFontStretch(fontStretch.GetValue());
            }
            PdfName fontName = fontDesc.GetAsName(PdfName.FontName);

            if (fontName != null)
            {
                SetFontName(fontName.GetValue());
            }
            PdfString fontFamily = fontDesc.GetAsString(PdfName.FontFamily);

            if (fontFamily != null)
            {
                SetFontFamily(fontFamily.GetValue());
            }
        }
Ejemplo n.º 15
0
        public virtual void UnregisterMcr(PdfMcr mcrToUnregister)
        {
            PdfDictionary pageDict = mcrToUnregister.GetPageObject();

            if (pageDict == null)
            {
                // invalid mcr, ignore
                return;
            }
            if (pageDict.IsFlushed())
            {
                throw new PdfException(PdfException.CannotRemoveMarkedContentReferenceBecauseItsPageWasAlreadyFlushed);
            }
            IDictionary <int, PdfMcr> pageMcrs = pageToPageMcrs.Get(pageDict.GetIndirectReference());

            if (pageMcrs != null)
            {
                if (mcrToUnregister is PdfObjRef)
                {
                    PdfDictionary obj = ((PdfDictionary)mcrToUnregister.GetPdfObject()).GetAsDictionary(PdfName.Obj);
                    if (obj != null && !obj.IsFlushed())
                    {
                        PdfNumber n = obj.GetAsNumber(PdfName.StructParent);
                        if (n != null)
                        {
                            pageMcrs.JRemove(StructParentIndexIntoKey(n.IntValue()));
                            structTreeRoot.SetModified();
                            return;
                        }
                    }
                    foreach (KeyValuePair <int, PdfMcr> entry in pageMcrs)
                    {
                        if (entry.Value.GetPdfObject() == mcrToUnregister.GetPdfObject())
                        {
                            pageMcrs.JRemove(entry.Key);
                            structTreeRoot.SetModified();
                            break;
                        }
                    }
                }
                else
                {
                    pageMcrs.JRemove(mcrToUnregister.GetMcid());
                    structTreeRoot.SetModified();
                }
            }
        }
Ejemplo n.º 16
0
 internal static int[] ConvertSimpleWidthsArray(PdfArray widthsArray, int first, int missingWidth)
 {
     int[] res = new int[256];
     for (int i = 0; i < res.Length; i++)
     {
         res[i] = missingWidth;
     }
     if (widthsArray == null)
     {
         return(res);
     }
     for (int i_1 = 0; i_1 < widthsArray.Size() && first + i_1 < 256; i_1++)
     {
         PdfNumber number = widthsArray.GetAsNumber(i_1);
         res[first + i_1] = number != null?number.IntValue() : missingWidth;
     }
     return(res);
 }
Ejemplo n.º 17
0
        private void RegisterMcr(PdfMcr mcr, bool registeringOnInit)
        {
            PdfDictionary mcrPageObject = mcr.GetPageObject();

            if (mcrPageObject == null || (!(mcr is PdfObjRef) && mcr.GetMcid() < 0))
            {
                ILog logger = LogManager.GetLogger(typeof(iText.Kernel.Pdf.Tagging.ParentTreeHandler));
                logger.Error(iText.IO.LogMessageConstant.ENCOUNTERED_INVALID_MCR);
                return;
            }
            SortedDictionary <int, PdfMcr> pageMcrs = pageToPageMcrs.Get(mcrPageObject.GetIndirectReference());

            if (pageMcrs == null)
            {
                pageMcrs = new SortedDictionary <int, PdfMcr>();
                pageToPageMcrs.Put(mcrPageObject.GetIndirectReference(), pageMcrs);
            }
            if (mcr is PdfObjRef)
            {
                PdfDictionary obj = ((PdfDictionary)mcr.GetPdfObject()).GetAsDictionary(PdfName.Obj);
                if (obj == null || obj.IsFlushed())
                {
                    throw new PdfException(PdfException.WhenAddingObjectReferenceToTheTagTreeItMustBeConnectedToNotFlushedObject
                                           );
                }
                PdfNumber n = obj.GetAsNumber(PdfName.StructParent);
                if (n != null)
                {
                    pageMcrs.Put(StructParentIndexIntoKey(n.IntValue()), mcr);
                }
                else
                {
                    throw new PdfException(PdfException.StructParentIndexNotFoundInTaggedObject);
                }
            }
            else
            {
                pageMcrs.Put(mcr.GetMcid(), mcr);
            }
            if (!registeringOnInit)
            {
                structTreeRoot.SetModified();
            }
        }
Ejemplo n.º 18
0
        /// <summary>Creates a Type3 font based on an existing font dictionary, which must be an indirect object.</summary>
        /// <param name="fontDictionary">a dictionary of type <code>/Font</code>, must have an indirect reference.</param>
        internal PdfType3Font(PdfDictionary fontDictionary)
            : base(fontDictionary)
        {
            EnsureObjectIsAddedToDocument(fontDictionary);
            CheckFontDictionary(fontDictionary, PdfName.Type3);
            subset       = true;
            embedded     = true;
            fontProgram  = new Type3FontProgram(false);
            fontEncoding = DocFontEncoding.CreateDocFontEncoding(fontDictionary.Get(PdfName.Encoding), null, false);
            PdfDictionary charProcsDic    = GetPdfObject().GetAsDictionary(PdfName.CharProcs);
            PdfArray      fontMatrixArray = GetPdfObject().GetAsArray(PdfName.FontMatrix);

            if (GetPdfObject().ContainsKey(PdfName.FontBBox))
            {
                PdfArray fontBBox = GetPdfObject().GetAsArray(PdfName.FontBBox);
                fontProgram.GetFontMetrics().SetBbox(fontBBox.GetAsNumber(0).IntValue(), fontBBox.GetAsNumber(1).IntValue(
                                                         ), fontBBox.GetAsNumber(2).IntValue(), fontBBox.GetAsNumber(3).IntValue());
            }
            else
            {
                fontProgram.GetFontMetrics().SetBbox(0, 0, 0, 0);
            }
            PdfNumber firstCharNumber = fontDictionary.GetAsNumber(PdfName.FirstChar);
            int       firstChar       = firstCharNumber != null?Math.Max(firstCharNumber.IntValue(), 0) : 0;

            int[]    widths     = FontUtil.ConvertSimpleWidthsArray(fontDictionary.GetAsArray(PdfName.Widths), firstChar);
            double[] fontMatrix = new double[6];
            for (int i = 0; i < fontMatrixArray.Size(); i++)
            {
                fontMatrix[i] = ((PdfNumber)fontMatrixArray.Get(i)).GetValue();
            }
            SetFontMatrix(fontMatrix);
            foreach (PdfName glyphName in charProcsDic.KeySet())
            {
                int unicode = (int)AdobeGlyphList.NameToUnicode(glyphName.GetValue());
                if (unicode != -1 && fontEncoding.CanEncode(unicode))
                {
                    int code = fontEncoding.ConvertToByte(unicode);
                    ((Type3FontProgram)GetFontProgram()).AddGlyph(code, unicode, widths[code], null, new Type3Glyph(charProcsDic
                                                                                                                    .GetAsStream(glyphName), GetDocument()));
                }
            }
        }
Ejemplo n.º 19
0
 internal static int[] ConvertSimpleWidthsArray(PdfArray widthsArray, int first, int missingWidth)
 {
     int[] res = new int[256];
     for (int i = 0; i < res.Length; i++)
     {
         res[i] = missingWidth;
     }
     if (widthsArray == null)
     {
         ILog logger = LogManager.GetLogger(typeof(FontUtil));
         logger.Warn(iText.IO.LogMessageConstant.FONT_DICTIONARY_WITH_NO_WIDTHS);
         return(res);
     }
     for (int i = 0; i < widthsArray.Size() && first + i < 256; i++)
     {
         PdfNumber number = widthsArray.GetAsNumber(i);
         res[first + i] = number != null?number.IntValue() : missingWidth;
     }
     return(res);
 }
Ejemplo n.º 20
0
        /// <summary>Gets the maximum length of the field's text, in characters.</summary>
        /// <remarks>
        /// Gets the maximum length of the field's text, in characters.
        /// This is an optional parameter, so if it is not specified, 0 value will be returned.
        /// </remarks>
        /// <returns>the current maximum text length</returns>
        public virtual int GetMaxLen()
        {
            PdfNumber maxLenEntry = this.GetPdfObject().GetAsNumber(PdfName.MaxLen);

            if (maxLenEntry != null)
            {
                return(maxLenEntry.IntValue());
            }
            else
            {
                PdfDictionary parent = GetParent();
                // MaxLen is an inherited form field property, therefore we try to recursively extract it from the ancestors
                if (parent != null)
                {
                    return(new iText.Forms.Fields.PdfTextFormField(parent).GetMaxLen());
                }
                else
                {
                    return(0);
                }
            }
        }
Ejemplo n.º 21
0
        internal static Type1Font CreateFontProgram(PdfDictionary fontDictionary, FontEncoding fontEncoding, CMapToUnicode
                                                    toUnicode)
        {
            PdfName baseFontName = fontDictionary.GetAsName(PdfName.BaseFont);
            String  baseFont;

            if (baseFontName != null)
            {
                baseFont = baseFontName.GetValue();
            }
            else
            {
                baseFont = FontUtil.CreateRandomFontName();
            }
            if (!fontDictionary.ContainsKey(PdfName.FontDescriptor))
            {
                Type1Font type1StdFont;
                try {
                    //if there are no font modifiers, cached font could be used,
                    //otherwise a new instance should be created.
                    type1StdFont = (Type1Font)FontProgramFactory.CreateFont(baseFont, true);
                }
                catch (Exception) {
                    type1StdFont = null;
                }
                if (type1StdFont != null)
                {
                    return(type1StdFont);
                }
            }
            iText.Kernel.Font.DocType1Font fontProgram = new iText.Kernel.Font.DocType1Font(baseFont);
            PdfDictionary fontDesc = fontDictionary.GetAsDictionary(PdfName.FontDescriptor);

            fontProgram.subtype = fontDesc.GetAsName(PdfName.Subtype);
            FillFontDescriptor(fontProgram, fontDesc);
            PdfNumber firstCharNumber = fontDictionary.GetAsNumber(PdfName.FirstChar);
            int       firstChar       = firstCharNumber != null?Math.Max(firstCharNumber.IntValue(), 0) : 0;

            int[] widths = FontUtil.ConvertSimpleWidthsArray(fontDictionary.GetAsArray(PdfName.Widths), firstChar, fontProgram
                                                             .GetMissingWidth());
            fontProgram.avgWidth = 0;
            int glyphsWithWidths = 0;

            for (int i = 0; i < 256; i++)
            {
                Glyph glyph = new Glyph(i, widths[i], fontEncoding.GetUnicode(i));
                fontProgram.codeToGlyph[i] = glyph;
                if (glyph.HasValidUnicode())
                {
                    //FontEncoding.codeToUnicode table has higher priority
                    if (fontEncoding.ConvertToByte(glyph.GetUnicode()) == i)
                    {
                        fontProgram.unicodeToGlyph[glyph.GetUnicode()] = glyph;
                    }
                }
                else
                {
                    if (toUnicode != null)
                    {
                        glyph.SetChars(toUnicode.Lookup(i));
                    }
                }
                if (widths[i] > 0)
                {
                    glyphsWithWidths++;
                    fontProgram.avgWidth += widths[i];
                }
            }
            if (glyphsWithWidths != 0)
            {
                fontProgram.avgWidth /= glyphsWithWidths;
            }
            return(fontProgram);
        }
Ejemplo n.º 22
0
        /// <summary>Removes annotation content item from the tag structure.</summary>
        /// <remarks>
        /// Removes annotation content item from the tag structure.
        /// If annotation is not added to the document or is not tagged, nothing will happen.
        /// </remarks>
        /// <param name="annotation">
        /// the
        /// <see cref="iText.Kernel.Pdf.Annot.PdfAnnotation"/>
        /// that will be removed from the tag structure
        /// </param>
        /// <returns>
        ///
        /// <see cref="TagTreePointer"/>
        /// instance which points at annotation tag parent if annotation was removed,
        /// otherwise returns null
        /// </returns>
        public virtual TagTreePointer RemoveAnnotationTag(PdfAnnotation annotation)
        {
            PdfStructElem structElem        = null;
            PdfDictionary annotDic          = annotation.GetPdfObject();
            PdfNumber     structParentIndex = (PdfNumber)annotDic.Get(PdfName.StructParent);

            if (structParentIndex != null)
            {
                PdfObjRef objRef = document.GetStructTreeRoot().FindObjRefByStructParentIndex(annotDic.GetAsDictionary(PdfName
                                                                                                                       .P), structParentIndex.IntValue());
                if (objRef != null)
                {
                    PdfStructElem parent = (PdfStructElem)objRef.GetParent();
                    parent.RemoveKid(objRef);
                    structElem = parent;
                }
            }
            annotDic.Remove(PdfName.StructParent);
            annotDic.SetModified();
            if (structElem != null)
            {
                return(new TagTreePointer(document).SetCurrentStructElem(structElem));
            }
            return(null);
        }
Ejemplo n.º 23
0
        /// <summary>Gets the maximum length of the field's text, in characters.</summary>
        /// <remarks>
        /// Gets the maximum length of the field's text, in characters.
        /// This is an optional parameter, so if it is not specified, <code>null</code> will be returned.
        /// </remarks>
        /// <returns>the current maximum text length</returns>
        public virtual int GetMaxLen()
        {
            PdfNumber number = GetPdfObject().GetAsNumber(PdfName.MaxLen);

            return(number != null?number.IntValue() : 0);
        }
Ejemplo n.º 24
0
        private void RegisterMcr(PdfMcr mcr, bool registeringOnInit)
        {
            PdfIndirectReference mcrPageIndRef = mcr.GetPageIndirectReference();

            if (mcrPageIndRef == null || (!(mcr is PdfObjRef) && mcr.GetMcid() < 0))
            {
                ILog logger = LogManager.GetLogger(typeof(iText.Kernel.Pdf.Tagging.ParentTreeHandler));
                logger.Error(iText.IO.LogMessageConstant.ENCOUNTERED_INVALID_MCR);
                return;
            }
            ParentTreeHandler.PageMcrsContainer pageMcrs = pageToPageMcrs.Get(mcrPageIndRef);
            if (pageMcrs == null)
            {
                pageMcrs = new ParentTreeHandler.PageMcrsContainer();
                pageToPageMcrs.Put(mcrPageIndRef, pageMcrs);
            }
            PdfObject stm;

            if ((stm = GetStm(mcr)) != null)
            {
                PdfIndirectReference stmIndRef;
                PdfStream            xObjectStream;
                if (stm is PdfIndirectReference)
                {
                    stmIndRef     = (PdfIndirectReference)stm;
                    xObjectStream = (PdfStream)stmIndRef.GetRefersTo();
                }
                else
                {
                    if (stm.GetIndirectReference() == null)
                    {
                        stm.MakeIndirect(structTreeRoot.GetDocument());
                    }
                    stmIndRef     = stm.GetIndirectReference();
                    xObjectStream = (PdfStream)stm;
                }
                int?structParent = xObjectStream.GetAsInt(PdfName.StructParents);
                if (structParent != null)
                {
                    xObjectToStructParentsInd.Put(stmIndRef, structParent);
                }
                else
                {
                    // TODO DEVSIX-3351 an error is thrown here because right now no /StructParents will be created.
                    ILog logger = LogManager.GetLogger(typeof(iText.Kernel.Pdf.Tagging.ParentTreeHandler));
                    logger.Error(iText.IO.LogMessageConstant.XOBJECT_HAS_NO_STRUCT_PARENTS);
                }
                pageMcrs.PutXObjectMcr(stmIndRef, mcr);
                if (registeringOnInit)
                {
                    xObjectStream.Release();
                }
            }
            else
            {
                if (mcr is PdfObjRef)
                {
                    PdfDictionary obj = ((PdfDictionary)mcr.GetPdfObject()).GetAsDictionary(PdfName.Obj);
                    if (obj == null || obj.IsFlushed())
                    {
                        throw new PdfException(PdfException.WhenAddingObjectReferenceToTheTagTreeItMustBeConnectedToNotFlushedObject
                                               );
                    }
                    PdfNumber n = obj.GetAsNumber(PdfName.StructParent);
                    if (n != null)
                    {
                        pageMcrs.PutObjectReferenceMcr(n.IntValue(), mcr);
                    }
                    else
                    {
                        throw new PdfException(PdfException.StructParentIndexNotFoundInTaggedObject);
                    }
                }
                else
                {
                    pageMcrs.PutPageContentStreamMcr(mcr.GetMcid(), mcr);
                }
            }
            if (!registeringOnInit)
            {
                structTreeRoot.SetModified();
            }
        }
Ejemplo n.º 25
0
        public override int GetMcid()
        {
            PdfNumber mcidNumber = ((PdfDictionary)GetPdfObject()).GetAsNumber(PdfName.MCID);

            return(mcidNumber != null?mcidNumber.IntValue() : -1);
        }
Ejemplo n.º 26
0
        internal static void FillFontDescriptor(iText.Kernel.Font.DocTrueTypeFont font, PdfDictionary fontDesc)
        {
            if (fontDesc == null)
            {
                ILog logger = LogManager.GetLogger(typeof(FontUtil));
                logger.Warn(iText.IO.LogMessageConstant.FONT_DICTIONARY_WITH_NO_FONT_DESCRIPTOR);
                return;
            }
            PdfNumber v = fontDesc.GetAsNumber(PdfName.Ascent);

            if (v != null)
            {
                font.SetTypoAscender(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.Descent);
            if (v != null)
            {
                font.SetTypoDescender(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.CapHeight);
            if (v != null)
            {
                font.SetCapHeight(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.XHeight);
            if (v != null)
            {
                font.SetXHeight(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.ItalicAngle);
            if (v != null)
            {
                font.SetItalicAngle(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.StemV);
            if (v != null)
            {
                font.SetStemV(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.StemH);
            if (v != null)
            {
                font.SetStemH(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.FontWeight);
            if (v != null)
            {
                font.SetFontWeight(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.MissingWidth);
            if (v != null)
            {
                font.missingWidth = v.IntValue();
            }
            PdfName fontStretch = fontDesc.GetAsName(PdfName.FontStretch);

            if (fontStretch != null)
            {
                font.SetFontStretch(fontStretch.GetValue());
            }
            PdfArray bboxValue = fontDesc.GetAsArray(PdfName.FontBBox);

            if (bboxValue != null)
            {
                int[] bbox = new int[4];
                bbox[0] = bboxValue.GetAsNumber(0).IntValue();
                //llx
                bbox[1] = bboxValue.GetAsNumber(1).IntValue();
                //lly
                bbox[2] = bboxValue.GetAsNumber(2).IntValue();
                //urx
                bbox[3] = bboxValue.GetAsNumber(3).IntValue();
                //ury
                if (bbox[0] > bbox[2])
                {
                    int t = bbox[0];
                    bbox[0] = bbox[2];
                    bbox[2] = t;
                }
                if (bbox[1] > bbox[3])
                {
                    int t = bbox[1];
                    bbox[1] = bbox[3];
                    bbox[3] = t;
                }
                font.SetBbox(bbox);
                // If ascender or descender in font descriptor are zero, we still want to get more or less correct valuee for
                // text extraction, stamping etc. Thus we rely on font bbox in this case
                if (font.GetFontMetrics().GetTypoAscender() == 0 && font.GetFontMetrics().GetTypoDescender() == 0)
                {
                    float maxAscent  = Math.Max(bbox[3], font.GetFontMetrics().GetTypoAscender());
                    float minDescent = Math.Min(bbox[1], font.GetFontMetrics().GetTypoDescender());
                    font.SetTypoAscender((int)(maxAscent * 1000 / (maxAscent - minDescent)));
                    font.SetTypoDescender((int)(minDescent * 1000 / (maxAscent - minDescent)));
                }
            }
            PdfString fontFamily = fontDesc.GetAsString(PdfName.FontFamily);

            if (fontFamily != null)
            {
                font.SetFontFamily(fontFamily.GetValue());
            }
            PdfNumber flagsValue = fontDesc.GetAsNumber(PdfName.Flags);

            if (flagsValue != null)
            {
                int flags = flagsValue.IntValue();
                if ((flags & 1) != 0)
                {
                    font.SetFixedPitch(true);
                }
                if ((flags & 262144) != 0)
                {
                    font.SetBold(true);
                }
            }
            PdfName[] fontFileNames = new PdfName[] { PdfName.FontFile, PdfName.FontFile2, PdfName.FontFile3 };
            foreach (PdfName fontFile in fontFileNames)
            {
                if (fontDesc.ContainsKey(fontFile))
                {
                    font.fontFileName = fontFile;
                    font.fontFile     = fontDesc.GetAsStream(fontFile);
                    break;
                }
            }
        }
        /// <summary>
        /// A code specifying the form of quadding (justification) that is used in displaying the annotation's text:
        /// 0 - Left-justified, 1 - Centered, 2 - Right-justified.
        /// </summary>
        /// <remarks>
        /// A code specifying the form of quadding (justification) that is used in displaying the annotation's text:
        /// 0 - Left-justified, 1 - Centered, 2 - Right-justified. Default value: 0 (left-justified).
        /// </remarks>
        /// <returns>a code specifying the form of quadding (justification), returns the default value if not explicitly specified.
        ///     </returns>
        public virtual int GetJustification()
        {
            PdfNumber q = GetPdfObject().GetAsNumber(PdfName.Q);

            return(q == null ? 0 : q.IntValue());
        }
Ejemplo n.º 28
0
        public virtual void UnregisterMcr(PdfMcr mcrToUnregister)
        {
            PdfDictionary pageDict = mcrToUnregister.GetPageObject();

            if (pageDict == null)
            {
                // invalid mcr, ignore
                return;
            }
            if (pageDict.IsFlushed())
            {
                throw new PdfException(PdfException.CannotRemoveMarkedContentReferenceBecauseItsPageWasAlreadyFlushed);
            }
            ParentTreeHandler.PageMcrsContainer pageMcrs = pageToPageMcrs.Get(pageDict.GetIndirectReference());
            if (pageMcrs != null)
            {
                PdfObject stm;
                if ((stm = GetStm(mcrToUnregister)) != null)
                {
                    PdfIndirectReference xObjectReference = stm is PdfIndirectReference ? (PdfIndirectReference)stm : stm.GetIndirectReference
                                                                ();
                    pageMcrs.GetPageResourceXObjects().Get(xObjectReference).JRemove(mcrToUnregister.GetMcid());
                    if (pageMcrs.GetPageResourceXObjects().Get(xObjectReference).IsEmpty())
                    {
                        pageMcrs.GetPageResourceXObjects().JRemove(xObjectReference);
                        xObjectToStructParentsInd.JRemove(xObjectReference);
                    }
                    structTreeRoot.SetModified();
                }
                else
                {
                    if (mcrToUnregister is PdfObjRef)
                    {
                        PdfDictionary obj = ((PdfDictionary)mcrToUnregister.GetPdfObject()).GetAsDictionary(PdfName.Obj);
                        if (obj != null && !obj.IsFlushed())
                        {
                            PdfNumber n = obj.GetAsNumber(PdfName.StructParent);
                            if (n != null)
                            {
                                pageMcrs.GetObjRefs().JRemove(n.IntValue());
                                structTreeRoot.SetModified();
                                return;
                            }
                        }
                        foreach (KeyValuePair <int, PdfMcr> entry in pageMcrs.GetObjRefs())
                        {
                            if (entry.Value.GetPdfObject() == mcrToUnregister.GetPdfObject())
                            {
                                pageMcrs.GetObjRefs().JRemove(entry.Key);
                                structTreeRoot.SetModified();
                                break;
                            }
                        }
                    }
                    else
                    {
                        pageMcrs.GetPageContentStreamsMcrs().JRemove(mcrToUnregister.GetMcid());
                        structTreeRoot.SetModified();
                    }
                }
            }
        }
Ejemplo n.º 29
0
        public virtual byte[] Decode(byte[] b, PdfName filterName, PdfObject decodeParams, PdfDictionary streamDictionary
                                     )
        {
            PdfNumber wn = streamDictionary.GetAsNumber(PdfName.Width);
            PdfNumber hn = streamDictionary.GetAsNumber(PdfName.Height);

            if (wn == null || hn == null)
            {
                throw new PdfException(PdfException.FilterCcittfaxdecodeIsOnlySupportedForImages);
            }
            int           width     = wn.IntValue();
            int           height    = hn.IntValue();
            PdfDictionary param     = decodeParams is PdfDictionary ? (PdfDictionary)decodeParams : null;
            int           k         = 0;
            bool          blackIs1  = false;
            bool          byteAlign = false;

            if (param != null)
            {
                PdfNumber kn = param.GetAsNumber(PdfName.K);
                if (kn != null)
                {
                    k = kn.IntValue();
                }
                PdfBoolean bo = param.GetAsBoolean(PdfName.BlackIs1);
                if (bo != null)
                {
                    blackIs1 = bo.GetValue();
                }
                bo = param.GetAsBoolean(PdfName.EncodedByteAlign);
                if (bo != null)
                {
                    byteAlign = bo.GetValue();
                }
            }
            byte[] outBuf = new byte[(width + 7) / 8 * height];
            TIFFFaxDecompressor decoder = new TIFFFaxDecompressor();

            if (k == 0 || k > 0)
            {
                int tiffT4Options = k > 0 ? TIFFConstants.GROUP3OPT_2DENCODING : 0;
                tiffT4Options |= byteAlign ? TIFFConstants.GROUP3OPT_FILLBITS : 0;
                decoder.SetOptions(1, TIFFConstants.COMPRESSION_CCITTFAX3, tiffT4Options, 0);
                decoder.DecodeRaw(outBuf, b, width, height);
                if (decoder.fails > 0)
                {
                    byte[] outBuf2  = new byte[(width + 7) / 8 * height];
                    int    oldFails = decoder.fails;
                    decoder.SetOptions(1, TIFFConstants.COMPRESSION_CCITTRLE, tiffT4Options, 0);
                    decoder.DecodeRaw(outBuf2, b, width, height);
                    if (decoder.fails < oldFails)
                    {
                        outBuf = outBuf2;
                    }
                }
            }
            else
            {
                TIFFFaxDecoder deca = new TIFFFaxDecoder(1, width, height);
                deca.DecodeT6(outBuf, b, 0, height, 0);
            }
            if (!blackIs1)
            {
                int len = outBuf.Length;
                for (int t = 0; t < len; ++t)
                {
                    outBuf[t] ^= 0xff;
                }
            }
            b = outBuf;
            return(b);
        }
        /// <summary>Parses the samples of the image from the underlying content parser, ignoring all filters.</summary>
        /// <remarks>
        /// Parses the samples of the image from the underlying content parser, ignoring all filters.
        /// The parser must be positioned immediately after the ID operator that ends the inline image's dictionary.
        /// The parser will be left positioned immediately following the EI operator.
        /// This is primarily useful if no filters have been applied.
        /// </remarks>
        /// <param name="imageDictionary">the dictionary of the inline image</param>
        /// <param name="ps">the content parser</param>
        /// <returns>the samples of the image</returns>
        /// <exception cref="System.IO.IOException">if anything bad happens during parsing</exception>
        private static byte[] ParseUnfilteredSamples(PdfDictionary imageDictionary, PdfDictionary colorSpaceDic, PdfCanvasParser
                                                     ps)
        {
            // special case:  when no filter is specified, we just read the number of bits
            // per component, multiplied by the width and height.
            if (imageDictionary.ContainsKey(PdfName.Filter))
            {
                throw new ArgumentException("Dictionary contains filters");
            }
            PdfNumber h           = imageDictionary.GetAsNumber(PdfName.Height);
            int       bytesToRead = ComputeBytesPerRow(imageDictionary, colorSpaceDic) * h.IntValue();

            byte[]       bytes              = new byte[bytesToRead];
            PdfTokenizer tokeniser          = ps.GetTokeniser();
            int          shouldBeWhiteSpace = tokeniser.Read();
            // skip next character (which better be a whitespace character - I suppose we could check for this)
            // from the PDF spec:  Unless the image uses ASCIIHexDecode or ASCII85Decode as one of its filters, the ID operator shall be followed by a single white-space character, and the next character shall be interpreted as the first byte of image data.
            // unfortunately, we've seen some PDFs where there is no space following the ID, so we have to capture this case and handle it
            int startIndex = 0;

            if (!PdfTokenizer.IsWhitespace(shouldBeWhiteSpace) || shouldBeWhiteSpace == 0)
            {
                // tokeniser treats 0 as whitespace, but for our purposes, we shouldn't
                bytes[0] = (byte)shouldBeWhiteSpace;
                startIndex++;
            }
            for (int i = startIndex; i < bytesToRead; i++)
            {
                int ch = tokeniser.Read();
                if (ch == -1)
                {
                    throw new InlineImageParsingUtils.InlineImageParseException(PdfException.EndOfContentStreamReachedBeforeEndOfImageData
                                                                                );
                }
                bytes[i] = (byte)ch;
            }
            PdfObject ei = ps.ReadObject();

            if (!ei.ToString().Equals("EI"))
            {
                // Some PDF producers seem to add another non-whitespace character after the image data.
                // Let's try to handle that case here.
                PdfObject ei2 = ps.ReadObject();
                if (!ei2.ToString().Equals("EI"))
                {
                    throw new InlineImageParsingUtils.InlineImageParseException(PdfException.OperatorEINotFoundAfterEndOfImageData
                                                                                );
                }
            }
            return(bytes);
        }