Пример #1
0
        /**
          <summary>Gets a specific filter object.</summary>
          <param name="name">Name of the requested filter.</param>
          <returns>Filter object associated to the name.</returns>
        */
        public static Filter Get(
            PdfName name
            )
        {
            /*
            NOTE: This is a factory singleton method for any filter-derived object.
              */
              if(name == null)
            return null;

              if(name.Equals(PdfName.FlateDecode)
            || name.Equals(PdfName.Fl))
            return FlateDecode;
              else if(name.Equals(PdfName.LZWDecode)
            || name.Equals(PdfName.LZW))
            throw new NotImplementedException("LZWDecode");
              else if(name.Equals(PdfName.ASCIIHexDecode)
            || name.Equals(PdfName.AHx))
            throw new NotImplementedException("ASCIIHexDecode");
              else if(name.Equals(PdfName.ASCII85Decode)
            || name.Equals(PdfName.A85))
            return ASCII85Filter;
              else if(name.Equals(PdfName.RunLengthDecode)
            || name.Equals(PdfName.RL))
            throw new NotImplementedException("RunLengthDecode");
              else if(name.Equals(PdfName.CCITTFaxDecode)
            || name.Equals(PdfName.CCF))
            throw new NotImplementedException("CCITTFaxDecode");
              else if(name.Equals(PdfName.JBIG2Decode))
            throw new NotImplementedException("JBIG2Decode");
              else if(name.Equals(PdfName.DCTDecode)
            || name.Equals(PdfName.DCT))
            throw new NotImplementedException("DCTDecode");
              else if(name.Equals(PdfName.JPXDecode))
            throw new NotImplementedException("JPXDecode");
              else if(name.Equals(PdfName.Crypt))
            throw new NotImplementedException("Crypt");

              return null;
        }
Пример #2
0
        protected void EmbedFont(String merged, String fontfile, String result)
        {
            // The font file
            FileStream raf = new FileStream(fontfile, FileMode.Open, FileAccess.Read);

            byte[] fontbytes = new byte[(int)raf.Length];
            raf.Read(fontbytes, 0, fontbytes.Length);
            raf.Close();

            // Create a new stream for the font file
            PdfStream stream = new PdfStream(fontbytes);

            stream.SetCompressionLevel(CompressionConstants.DEFAULT_COMPRESSION);
            stream.Put(PdfName.Length1, new PdfNumber(fontbytes.Length));

            PdfDocument pdfDoc             = new PdfDocument(new PdfReader(merged), new PdfWriter(result));
            int         numberOfPdfObjects = pdfDoc.GetNumberOfPdfObjects();

            // Search for the font dictionary
            for (int i = 0; i < numberOfPdfObjects; i++)
            {
                PdfObject pdfObject = pdfDoc.GetPdfObject(i);
                if (pdfObject == null || !pdfObject.IsDictionary())
                {
                    continue;
                }

                PdfDictionary fontDictionary = (PdfDictionary)pdfObject;
                PdfFont       font           = PdfFontFactory.CreateFont(fontfile, PdfEncodings.WINANSI);
                PdfName       fontname       = new PdfName(font.GetFontProgram().GetFontNames().GetFontName());
                if (PdfName.FontDescriptor.Equals(fontDictionary.Get(PdfName.Type)) &&
                    fontname.Equals(fontDictionary.Get(PdfName.FontName)))
                {
                    // Embed the passed font to the pdf document
                    fontDictionary.Put(PdfName.FontFile2, stream.MakeIndirect(pdfDoc).GetIndirectReference());
                }
            }

            pdfDoc.Close();
        }
Пример #3
0
        /**
         * Extracts locations from the redact annotations contained in the document and applied to the given page.
         */
        private IList <PdfCleanUpLocation> ExtractLocationsFromRedactAnnots(int page, PdfDictionary pageDict)
        {
            List <PdfCleanUpLocation> locations = new List <PdfCleanUpLocation>();

            if (pageDict.Contains(PdfName.ANNOTS))
            {
                PdfArray annotsArray = pageDict.GetAsArray(PdfName.ANNOTS);

                for (int i = 0; i < annotsArray.Size; ++i)
                {
                    PdfIndirectReference annotIndirRef = annotsArray.GetAsIndirectObject(i);
                    PdfDictionary        annotDict     = annotsArray.GetAsDict(i);
                    PdfName annotSubtype = annotDict.GetAsName(PdfName.SUBTYPE);

                    if (annotSubtype.Equals(PdfName.REDACT))
                    {
                        SaveRedactAnnotIndirRef(page, annotIndirRef.ToString());
                        locations.AddRange(ExtractLocationsFromRedactAnnot(page, i, annotDict));
                    }
                }
            }

            return(locations);
        }
Пример #4
0
        public void SetMKIconFit(PdfName scale, PdfName scalingType, float leftoverLeft, float leftoverBottom, bool fitInBounds)
        {
            PdfDictionary dic = new PdfDictionary();

            if (!scale.Equals(PdfName.A))
            {
                dic.Put(PdfName.SW, scale);
            }
            if (!scalingType.Equals(PdfName.P))
            {
                dic.Put(PdfName.S, scalingType);
            }
            if (leftoverLeft != 0.5f || leftoverBottom != 0.5f)
            {
                PdfArray array = new PdfArray(new PdfNumber(leftoverLeft));
                array.Add(new PdfNumber(leftoverBottom));
                dic.Put(PdfName.A, array);
            }
            if (fitInBounds)
            {
                dic.Put(PdfName.FB, PdfBoolean.PDFTRUE);
            }
            MK.Put(PdfName.IF, dic);
        }
Пример #5
0
 protected override void CheckAction(PdfWriter writer, int key, Object obj1)
 {
     if (obj1 is PdfAction)
     {
         PdfAction action = (PdfAction)obj1;
         PdfName   s      = action.GetAsName(PdfName.S);
         if (setState.Equals(s) || noOp.Equals(s))
         {
             throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("deprecated.setstate.and.noop.actions.are.not.allowed"));
         }
         if (restrictedActions.Contains(s))
         {
             throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("launch.sound.movie.resetform.importdata.and.javascript.actions.are.not.allowed"));
         }
         if (PdfName.NAMED.Equals(s))
         {
             PdfName n = action.GetAsName(PdfName.N);
             if (n != null && !allowedNamedActions.Contains(n))
             {
                 throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("named.action.type.1.not.allowed", n.ToString()));
             }
         }
     }
 }
Пример #6
0
        internal void MergeField(String name, AcroFields.Item item)
        {
            Hashtable       map = fieldTree;
            StringTokenizer tk  = new StringTokenizer(name, ".");

            if (!tk.HasMoreTokens())
            {
                return;
            }
            while (true)
            {
                String s   = tk.NextToken();
                Object obj = map[s];
                if (tk.HasMoreTokens())
                {
                    if (obj == null)
                    {
                        obj    = new Hashtable();
                        map[s] = obj;
                        map    = (Hashtable)obj;
                        continue;
                    }
                    else if (obj is Hashtable)
                    {
                        map = (Hashtable)obj;
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    if (obj is Hashtable)
                    {
                        return;
                    }
                    PdfDictionary merged = item.GetMerged(0);
                    if (obj == null)
                    {
                        PdfDictionary field = new PdfDictionary();
                        if (PdfName.SIG.Equals(merged.Get(PdfName.FT)))
                        {
                            hasSignature = true;
                        }
                        foreach (PdfName key in merged.Keys)
                        {
                            if (fieldKeys.ContainsKey(key))
                            {
                                field.Put(key, merged.Get(key));
                            }
                        }
                        ArrayList list = new ArrayList();
                        list.Add(field);
                        CreateWidgets(list, item);
                        map[s] = list;
                    }
                    else
                    {
                        ArrayList     list  = (ArrayList)obj;
                        PdfDictionary field = (PdfDictionary)list[0];
                        PdfName       type1 = (PdfName)field.Get(PdfName.FT);
                        PdfName       type2 = (PdfName)merged.Get(PdfName.FT);
                        if (type1 == null || !type1.Equals(type2))
                        {
                            return;
                        }
                        int       flag1 = 0;
                        PdfObject f1    = field.Get(PdfName.FF);
                        if (f1 != null && f1.IsNumber())
                        {
                            flag1 = ((PdfNumber)f1).IntValue;
                        }
                        int       flag2 = 0;
                        PdfObject f2    = merged.Get(PdfName.FF);
                        if (f2 != null && f2.IsNumber())
                        {
                            flag2 = ((PdfNumber)f2).IntValue;
                        }
                        if (type1.Equals(PdfName.BTN))
                        {
                            if (((flag1 ^ flag2) & PdfFormField.FF_PUSHBUTTON) != 0)
                            {
                                return;
                            }
                            if ((flag1 & PdfFormField.FF_PUSHBUTTON) == 0 && ((flag1 ^ flag2) & PdfFormField.FF_RADIO) != 0)
                            {
                                return;
                            }
                        }
                        else if (type1.Equals(PdfName.CH))
                        {
                            if (((flag1 ^ flag2) & PdfFormField.FF_COMBO) != 0)
                            {
                                return;
                            }
                        }
                        CreateWidgets(list, item);
                    }
                    return;
                }
            }
        }
Пример #7
0
        public override void Draw(DrawContext drawContext)
        {
            PdfDocument document = drawContext.GetDocument();

            ApplyDestination(document);
            ApplyAction(document);
            bool               isTagged          = drawContext.IsTaggingEnabled() && GetModelElement() is IAccessibleElement;
            TagTreePointer     tagPointer        = null;
            IAccessibleElement accessibleElement = null;

            if (isTagged)
            {
                accessibleElement = (IAccessibleElement)GetModelElement();
                PdfName role = accessibleElement.GetRole();
                if (role != null && !PdfName.Artifact.Equals(role))
                {
                    tagPointer = document.GetTagStructureContext().GetAutoTaggingPointer();
                    if (!tagPointer.IsElementConnectedToTag(accessibleElement))
                    {
                        AccessibleAttributesApplier.ApplyLayoutAttributes(role, this, document);
                        if (role.Equals(PdfName.TD))
                        {
                            AccessibleAttributesApplier.ApplyTableAttributes(this);
                        }
                        if (role.Equals(PdfName.List))
                        {
                            AccessibleAttributesApplier.ApplyListAttributes(this);
                        }
                    }
                    tagPointer.AddTag(accessibleElement, true);
                }
                else
                {
                    isTagged = false;
                }
            }
            bool isRelativePosition = IsRelativePosition();

            if (isRelativePosition)
            {
                ApplyAbsolutePositioningTranslation(false);
            }
            BeginRotationIfApplied(drawContext.GetCanvas());
            DrawBackground(drawContext);
            DrawBorder(drawContext);
            DrawChildren(drawContext);
            EndRotationIfApplied(drawContext.GetCanvas());
            if (isRelativePosition)
            {
                ApplyAbsolutePositioningTranslation(true);
            }
            if (isTagged)
            {
                tagPointer.MoveToParent();
                if (isLastRendererForModelElement)
                {
                    document.GetTagStructureContext().RemoveElementConnectionToTag(accessibleElement);
                }
            }
            flushed = true;
        }
Пример #8
0
        /**
         *  Checks if a <CODE>Dictionary</CODE> is of the type OUTLINES.
         *
         * @return        <CODE>true</CODE> if it is, <CODE>false</CODE> if it isn't.
         */

        public bool IsOutlineTree()
        {
            return(OUTLINES.Equals(dictionaryType));
        }
Пример #9
0
        /**
         *  Checks if a <CODE>Dictionary</CODE> is of the type PAGES.
         *
         * @return        <CODE>true</CODE> if it is, <CODE>false</CODE> if it isn't.
         */

        public bool IsPages()
        {
            return(PAGES.Equals(dictionaryType));
        }
    /* Parse PDf file annotations
     */
    static void parseAnnotations(PdfReader reader, List <cMark> markers)
    {
        markers.Clear();

        // on each page
        for (int pg = 1; pg < reader.NumberOfPages + 1; pg++)
        {
            PdfDictionary pagedic = reader.GetPageN(pg);
            // get annotations array
            PdfArray annotarray = (PdfArray)PdfReader.GetPdfObject(pagedic.Get(PdfName.ANNOTS));
            // if no annotation ...
            if (annotarray == null || annotarray.Size == 0)
            {
                continue;
            }

            // on each annotation reference...
            foreach (PdfIndirectReference annot in annotarray.ArrayList)
            {
                PdfDictionary annotationDic = (PdfDictionary)PdfReader.GetPdfObject(annot);

                PdfName subType = (PdfName)annotationDic.Get(PdfName.SUBTYPE);

                PdfString contents = annotationDic.GetAsString(PdfName.CONTENTS);

                // if simple text...
                if ((contents != null) &&
                    ((subType.Equals(PdfName.TEXT)) ||
                     (subType.Equals(PdfName.FREETEXT))
                    )
                    )
                {
                    String value = contents.ToString();

                    // single marker element
                    cMark mrk = new cMark(cMark.TypeMarker.TypeAnnotation, cMark.TypeAnnotationSubType.TypeAnnotation_NONE);
                    mrk.pageNum = pg;
                    mrk.title   = value;

                    if (annotationDic.Get(PdfName.RECT) != null)
                    {
                        PdfArray     coord    = annotationDic.GetAsArray(PdfName.RECT);
                        PdfRectangle textRect = new PdfRectangle(
                            ((PdfNumber)coord[0]).FloatValue,
                            ((PdfNumber)coord[1]).FloatValue,
                            ((PdfNumber)coord[2]).FloatValue,
                            ((PdfNumber)coord[3]).FloatValue);

                        mrk.annotRect = textRect.Rectangle;
                    }

                    markers.Add(mrk);
                }

                // if decorated text...
                if ((subType.Equals(PdfName.UNDERLINE)) ||
                    (subType.Equals(PdfName.HIGHLIGHT)) ||
                    (subType.Equals(PdfName.STRIKEOUT)) ||
                    (subType.Equals(PdfName.SQUIGGLY)))
                {
                    cMark mrk = new cMark(cMark.TypeMarker.TypeAnnotation, cMark.TypeAnnotationSubType.TypeAnnotation_NONE);
                    mrk.pageNum = pg;

                    if (subType.Equals(PdfName.UNDERLINE))
                    {
                        mrk.eAnnotationSubType = cMark.TypeAnnotationSubType.TypeAnnotation_UNDERLINE;
                    }
                    else if (subType.Equals(PdfName.HIGHLIGHT))
                    {
                        mrk.eAnnotationSubType = cMark.TypeAnnotationSubType.TypeAnnotation_HIGHLIGHT;
                    }
                    else if (subType.Equals(PdfName.STRIKEOUT))
                    {
                        mrk.eAnnotationSubType = cMark.TypeAnnotationSubType.TypeAnnotation_STRIKEOUT;
                    }
                    else if (subType.Equals(PdfName.SQUIGGLY))
                    {
                        mrk.eAnnotationSubType = cMark.TypeAnnotationSubType.TypeAnnotation_SQUIGGLY;
                    }

                    PdfObject pdfObjectQuad = annotationDic.Get(PdfName.QUADPOINTS);
                    if (pdfObjectQuad != null)
                    {
                        PdfArray rect = annotationDic.GetAsArray(PdfName.QUADPOINTS);
                        // float llx, float lly, float urx, float ury
                        float lowX = Math.Min(((PdfNumber)rect[0]).FloatValue, ((PdfNumber)rect[2]).FloatValue);
                        lowX = Math.Min(lowX, ((PdfNumber)rect[4]).FloatValue);
                        lowX = Math.Min(lowX, ((PdfNumber)rect[6]).FloatValue);

                        float lowY = Math.Min(((PdfNumber)rect[1]).FloatValue, ((PdfNumber)rect[3]).FloatValue);
                        lowY = Math.Min(lowY, ((PdfNumber)rect[5]).FloatValue);
                        lowY = Math.Min(lowY, ((PdfNumber)rect[7]).FloatValue);

                        float upX = Math.Max(((PdfNumber)rect[0]).FloatValue, ((PdfNumber)rect[2]).FloatValue);
                        upX = Math.Max(upX, ((PdfNumber)rect[4]).FloatValue);
                        upX = Math.Max(upX, ((PdfNumber)rect[6]).FloatValue);

                        float upY = Math.Max(((PdfNumber)rect[1]).FloatValue, ((PdfNumber)rect[3]).FloatValue);
                        upY = Math.Max(upY, ((PdfNumber)rect[5]).FloatValue);
                        upY = Math.Max(upY, ((PdfNumber)rect[7]).FloatValue);

                        PdfRectangle            textRect = new PdfRectangle(lowX, lowY, upX, upY);
                        RenderFilter[]          filter   = { new RegionTextRenderFilter(textRect.Rectangle) };
                        ITextExtractionStrategy strategy;
                        StringBuilder           sb = new StringBuilder();
                        for (int i = 1; i <= reader.NumberOfPages; i++)
                        {
                            strategy = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), filter);
                            sb.AppendLine(PdfTextExtractor.GetTextFromPage(reader, i, strategy));
                        }
                        String result = sb.ToString();
                        mrk.title     = result;
                        mrk.annotRect = textRect.Rectangle;
                        markers.Add(mrk);
                    }
                }
            }
        }
    }
Пример #11
0
        /**
         * <summary>Wraps an annotation base object into an annotation object.</summary>
         * <param name="baseObject">Annotation base object.</param>
         * <returns>Annotation object associated to the base object.</returns>
         */
        public static Annotation Wrap(PdfDirectObject baseObject)
        {
            if (baseObject == null)
            {
                return(null);
            }
            if (baseObject.Wrapper is Annotation annotation)
            {
                return(annotation);
            }
            if (baseObject is PdfReference reference && reference.DataObject?.Wrapper is Annotation referenceAnnotation)
            {
                baseObject.Wrapper = referenceAnnotation;
                return(referenceAnnotation);
            }
            var dictionary = baseObject.Resolve() as PdfDictionary;

            if (dictionary == null)
            {
                return(null);
            }
            PdfName annotationType = (PdfName)dictionary[PdfName.Subtype];

            if (annotationType.Equals(PdfName.Text))
            {
                return(new StickyNote(baseObject));
            }
            else if (annotationType.Equals(PdfName.Link))
            {
                return(new Link(baseObject));
            }
            else if (annotationType.Equals(PdfName.FreeText))
            {
                return(new FreeText(baseObject));
            }
            else if (annotationType.Equals(PdfName.Line))
            {
                return(new Line(baseObject));
            }
            else if (annotationType.Equals(PdfName.Square))
            {
                return(new Rectangle(baseObject));
            }
            else if (annotationType.Equals(PdfName.Circle))
            {
                return(new Ellipse(baseObject));
            }
            else if (annotationType.Equals(PdfName.Polygon))
            {
                return(new Polygon(baseObject));
            }
            else if (annotationType.Equals(PdfName.PolyLine))
            {
                return(new Polyline(baseObject));
            }
            else if (annotationType.Equals(PdfName.Highlight) ||
                     annotationType.Equals(PdfName.Underline) ||
                     annotationType.Equals(PdfName.Squiggly) ||
                     annotationType.Equals(PdfName.StrikeOut))
            {
                return(new TextMarkup(baseObject));
            }
            else if (annotationType.Equals(PdfName.Stamp))
            {
                return(new Stamp(baseObject));
            }
            else if (annotationType.Equals(PdfName.Caret))
            {
                return(new Caret(baseObject));
            }
            else if (annotationType.Equals(PdfName.Ink))
            {
                return(new Scribble(baseObject));
            }
            else if (annotationType.Equals(PdfName.Popup))
            {
                return(new Popup(baseObject));
            }
            else if (annotationType.Equals(PdfName.FileAttachment))
            {
                return(new FileAttachment(baseObject));
            }
            else if (annotationType.Equals(PdfName.Sound))
            {
                return(new Sound(baseObject));
            }
            else if (annotationType.Equals(PdfName.Movie))
            {
                return(new Movie(baseObject));
            }
            else if (annotationType.Equals(PdfName.Widget))
            {
                return(new Widget(baseObject));
            }
            else if (annotationType.Equals(PdfName.Screen))
            {
                return(new Screen(baseObject));
            }
            //TODO
            //     else if(annotationType.Equals(PdfName.PrinterMark)) return new PrinterMark(baseObject);
            //     else if(annotationType.Equals(PdfName.TrapNet)) return new TrapNet(baseObject);
            //     else if(annotationType.Equals(PdfName.Watermark)) return new Watermark(baseObject);
            //     else if(annotationType.Equals(PdfName.3DAnnotation)) return new 3DAnnotation(baseObject);
            else // Other annotation type.
            {
                return(new GenericAnnotation(baseObject));
            }
        }
Пример #12
0
        /// <summary>Check if view is in details mode.</summary>
        /// <returns>true if view is in details mode and false otherwise</returns>
        public virtual bool IsViewDetails()
        {
            PdfName view = GetPdfObject().GetAsName(PdfName.View);

            return(view == null || view.Equals(PdfName.D));
        }
Пример #13
0
        /**
         * @param colorSpaceName the name of the color space. If null, a bi-tonal (black and white) color space is assumed.
         * @return the components per pixel for the specified color space
         */
        private static int GetComponentsPerPixel(PdfName colorSpaceName, PdfDictionary colorSpaceDic){
            if (colorSpaceName == null)
                return 1;
            if (colorSpaceName.Equals(PdfName.DEVICEGRAY))
                return 1;
            if (colorSpaceName.Equals(PdfName.DEVICERGB))
                return 3;
            if (colorSpaceName.Equals(PdfName.DEVICECMYK))
                return 4;
            
            if (colorSpaceDic != null){
                PdfArray colorSpace = colorSpaceDic.GetAsArray(colorSpaceName);
                if (colorSpace != null){
                    if (PdfName.INDEXED.Equals(colorSpace.GetAsName(0))){
                        return 1;
                    }
                }
            }

            throw new ArgumentException("Unexpected color space " + colorSpaceName);
        }
Пример #14
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.Equals(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.Equals(PdfName.COLORSPACE)){
         if (value is PdfName){
             PdfName altValue;
             inlineImageColorSpaceAbbreviationMap.TryGetValue((PdfName)value, out altValue);
             if (altValue != null)
                 return altValue;
         }
     }
     
     return value;
 }
Пример #15
0
// ---------------------------------------------------------------------------

        /**
         * Manipulates a PDF file src with the byte array as result
         */
        public byte[] ManipulatePdf(byte[] pdf)
        {
            PdfName key   = new PdfName("ITXT_SpecialId");
            PdfName value = new PdfName("123456789");
            // Read the file
            PdfReader reader = new PdfReader(pdf);
            int       n      = reader.XrefSize;
            PdfObject pdfObject;
            PRStream  prStream;

            // Look for image and manipulate image prStream
            for (int i = 0; i < n; i++)
            {
                pdfObject = reader.GetPdfObject(i);
                if (pdfObject == null || !pdfObject.IsStream())
                {
                    continue;
                }

                prStream = (PRStream)pdfObject;
                byte[] imageBytes;
                if (value.Equals(prStream.Get(key)))
                {
                    PdfImageObject image = new PdfImageObject(prStream);
                    using (System.Drawing.Image original = image.GetDrawingImage()) {
                        if (original == null)
                        {
                            continue;
                        }
                        int width  = (int)(original.Width * FACTOR);
                        int height = (int)(original.Height * FACTOR);

                        using (System.Drawing.Image thumb = new Bitmap(width, height)) {
                            using (Graphics graphic = Graphics.FromImage(thumb)) {
                                graphic.DrawImage(original, 0, 0, width, height);
                                using (MemoryStream ms = new MemoryStream()) {
                                    thumb.Save(ms, ImageFormat.Jpeg);
                                    imageBytes = ms.ToArray();
                                }
                            }
                        }
                        prStream.Clear();
                        prStream.SetData(imageBytes, false, PRStream.NO_COMPRESSION);
                        prStream.Put(PdfName.TYPE, PdfName.XOBJECT);
                        prStream.Put(PdfName.SUBTYPE, PdfName.IMAGE);
                        prStream.Put(key, value);
                        prStream.Put(PdfName.FILTER, PdfName.DCTDECODE);
                        prStream.Put(PdfName.WIDTH, new PdfNumber(width));
                        prStream.Put(PdfName.HEIGHT, new PdfNumber(height));
                        prStream.Put(PdfName.BITSPERCOMPONENT, new PdfNumber(8));
                        prStream.Put(PdfName.COLORSPACE, PdfName.DEVICERGB);
                    }
                }
            }
            // Save altered PDF
            using (MemoryStream ms = new MemoryStream()) {
                using (PdfStamper stamper = new PdfStamper(reader, ms)) {
                }
                return(ms.ToArray());
            }
        }
Пример #16
0
        /**
         * <summary>Wraps an action base object into an action object.</summary>
         * <param name="baseObject">Action base object.</param>
         * <returns>Action object associated to the base object.</returns>
         */
        public static Action Wrap(PdfDirectObject baseObject)
        {
            if (baseObject == null)
            {
                return(null);
            }
            if (baseObject.Wrapper is Action action)
            {
                return(action);
            }
            if (baseObject is PdfReference pdfReference && pdfReference.DataObject?.Wrapper is Action referenceAction)
            {
                baseObject.Wrapper = referenceAction;
                return(referenceAction);
            }

            PdfDictionary dataObject = (PdfDictionary)baseObject.Resolve();
            PdfName       actionType = (PdfName)dataObject[PdfName.S];

            if (actionType == null ||
                (dataObject.ContainsKey(PdfName.Type) &&
                 !dataObject[PdfName.Type].Equals(PdfName.Action)))
            {
                return(null);
            }

            if (actionType.Equals(PdfName.GoTo))
            {
                return(new GoToLocal(baseObject));
            }
            else if (actionType.Equals(PdfName.GoToR))
            {
                return(new GoToRemote(baseObject));
            }
            else if (actionType.Equals(PdfName.GoToE))
            {
                return(new GoToEmbedded(baseObject));
            }
            else if (actionType.Equals(PdfName.Launch))
            {
                return(new Launch(baseObject));
            }
            else if (actionType.Equals(PdfName.Thread))
            {
                return(new GoToThread(baseObject));
            }
            else if (actionType.Equals(PdfName.URI))
            {
                return(new GoToURI(baseObject));
            }
            else if (actionType.Equals(PdfName.Sound))
            {
                return(new PlaySound(baseObject));
            }
            else if (actionType.Equals(PdfName.Movie))
            {
                return(new PlayMovie(baseObject));
            }
            else if (actionType.Equals(PdfName.Hide))
            {
                return(new ToggleVisibility(baseObject));
            }
            else if (actionType.Equals(PdfName.Named))
            {
                PdfName actionName = (PdfName)dataObject[PdfName.N];
                if (actionName.Equals(PdfName.NextPage))
                {
                    return(new GoToNextPage(baseObject));
                }
                else if (actionName.Equals(PdfName.PrevPage))
                {
                    return(new GoToPreviousPage(baseObject));
                }
                else if (actionName.Equals(PdfName.FirstPage))
                {
                    return(new GoToFirstPage(baseObject));
                }
                else if (actionName.Equals(PdfName.LastPage))
                {
                    return(new GoToLastPage(baseObject));
                }
                else // Custom named action.
                {
                    return(new NamedAction(baseObject));
                }
            }
            else if (actionType.Equals(PdfName.SubmitForm))
            {
                return(new SubmitForm(baseObject));
            }
            else if (actionType.Equals(PdfName.ResetForm))
            {
                return(new ResetForm(baseObject));
            }
            else if (actionType.Equals(PdfName.ImportData))
            {
                return(new ImportData(baseObject));
            }
            else if (actionType.Equals(PdfName.JavaScript))
            {
                return(new JavaScript(baseObject));
            }
            else if (actionType.Equals(PdfName.SetOCGState))
            {
                return(new SetLayerState(baseObject));
            }
            else if (actionType.Equals(PdfName.Rendition))
            {
                return(new Render(baseObject));
            }
            else if (actionType.Equals(PdfName.Trans))
            {
                return(new DoTransition(baseObject));
            }
            else if (actionType.Equals(PdfName.GoTo3DView))
            {
                return(new GoTo3dView(baseObject));
            }
            else // Custom action.
            {
                return(new Action(baseObject));
            }
        }
Пример #17
0
        /// <summary>Retrieves the names stored in the name tree</summary>
        /// <returns>Map containing the PdfObjects stored in the tree</returns>
        public virtual IDictionary <String, PdfObject> GetNames()
        {
            if (items.Count > 0)
            {
                return(items);
            }
            PdfDictionary dictionary = catalog.GetPdfObject().GetAsDictionary(PdfName.Names);

            if (dictionary != null)
            {
                dictionary = dictionary.GetAsDictionary(treeType);
                if (dictionary != null)
                {
                    items = ReadTree(dictionary);
                    //@TODO It's done for auto porting to itextsharp, cuz u cannot change collection which you iterate
                    // in for loop (even if you change only value of a Map entry) in .NET. Java doesn't have such a problem.
                    // We should find a better solution in the future.
                    ICollection <String> keys = new HashSet <String>();
                    keys.AddAll(items.Keys);
                    foreach (String key in keys)
                    {
                        if (treeType.Equals(PdfName.Dests))
                        {
                            PdfArray arr = GetDestArray(items.Get(key));
                            if (arr != null)
                            {
                                items.Put(key, arr);
                            }
                            else
                            {
                                items.JRemove(key);
                            }
                        }
                        else
                        {
                            if (items.Get(key) == null)
                            {
                                items.JRemove(key);
                            }
                        }
                    }
                }
            }
            if (treeType.Equals(PdfName.Dests))
            {
                PdfDictionary destinations = catalog.GetPdfObject().GetAsDictionary(PdfName.Dests);
                if (destinations != null)
                {
                    ICollection <PdfName> keys = destinations.KeySet();
                    foreach (PdfName key in keys)
                    {
                        PdfArray array = GetDestArray(destinations.Get(key));
                        if (array == null)
                        {
                            continue;
                        }
                        items.Put(key.GetValue(), array);
                    }
                }
            }
            return(items);
        }
Пример #18
0
        /// <summary>Retrieves the names stored in the name tree</summary>
        /// <returns>Map containing the PdfObjects stored in the tree</returns>
        public virtual IDictionary <String, PdfObject> GetNames()
        {
            if (items.Count > 0)
            {
                return(items);
            }
            PdfDictionary dictionary = catalog.GetPdfObject().GetAsDictionary(PdfName.Names);

            if (dictionary != null)
            {
                dictionary = dictionary.GetAsDictionary(treeType);
                if (dictionary != null)
                {
                    items = ReadTree(dictionary);
                    // A separate collection for keys is used for auto porting to C#, because in C#
                    // it is impossible to change the collection which you iterate in for loop
                    ICollection <String> keys = new HashSet <String>();
                    keys.AddAll(items.Keys);
                    foreach (String key in keys)
                    {
                        if (treeType.Equals(PdfName.Dests))
                        {
                            PdfArray arr = GetDestArray(items.Get(key));
                            if (arr != null)
                            {
                                items.Put(key, arr);
                            }
                            else
                            {
                                items.JRemove(key);
                            }
                        }
                        else
                        {
                            if (items.Get(key) == null)
                            {
                                items.JRemove(key);
                            }
                        }
                    }
                }
            }
            if (treeType.Equals(PdfName.Dests))
            {
                PdfDictionary destinations = catalog.GetPdfObject().GetAsDictionary(PdfName.Dests);
                if (destinations != null)
                {
                    ICollection <PdfName> keys = destinations.KeySet();
                    foreach (PdfName key in keys)
                    {
                        PdfArray array = GetDestArray(destinations.Get(key));
                        if (array == null)
                        {
                            continue;
                        }
                        items.Put(key.GetValue(), array);
                    }
                }
            }
            return(items);
        }
Пример #19
0
 private static void ApplyBlockLevelLayoutAttributes(PdfName role, AbstractRenderer renderer, PdfDictionary
      attributes, PdfDocument doc) {
     float?[] margins = new float?[] { renderer.GetPropertyAsFloat(Property.MARGIN_TOP), renderer.GetPropertyAsFloat
         (Property.MARGIN_BOTTOM), renderer.GetPropertyAsFloat(Property.MARGIN_LEFT), renderer.GetPropertyAsFloat
         (Property.MARGIN_RIGHT) };
     int[] marginsOrder = new int[] { 0, 1, 2, 3 };
     //TODO set depending on writing direction
     float? spaceBefore = margins[marginsOrder[0]];
     if (spaceBefore != null && spaceBefore != 0) {
         attributes.Put(PdfName.SpaceBefore, new PdfNumber((float)spaceBefore));
     }
     float? spaceAfter = margins[marginsOrder[1]];
     if (spaceAfter != null && spaceAfter != 0) {
         attributes.Put(PdfName.SpaceAfter, new PdfNumber((float)spaceAfter));
     }
     float? startIndent = margins[marginsOrder[2]];
     if (startIndent != null && startIndent != 0) {
         attributes.Put(PdfName.StartIndent, new PdfNumber((float)startIndent));
     }
     float? endIndent = margins[marginsOrder[3]];
     if (endIndent != null && endIndent != 0) {
         attributes.Put(PdfName.EndIndent, new PdfNumber((float)endIndent));
     }
     float? firstLineIndent = renderer.GetProperty<float?>(Property.FIRST_LINE_INDENT);
     if (firstLineIndent != null && firstLineIndent != 0) {
         attributes.Put(PdfName.TextIndent, new PdfNumber((float)firstLineIndent));
     }
     TextAlignment? textAlignment = renderer.GetProperty<TextAlignment?>(Property.TEXT_ALIGNMENT);
     if (textAlignment != null && (!role.Equals(PdfName.TH) && !role.Equals(PdfName.TD))) {
         //for table cells there is an InlineAlign attribute (see below)
         attributes.Put(PdfName.TextAlign, TransformTextAlignmentValueToName(textAlignment));
     }
     bool connectedToTag = doc.GetTagStructureContext().IsElementConnectedToTag((IAccessibleElement)renderer.GetModelElement
         ());
     bool elementIsOnSinglePage = !connectedToTag && renderer.isLastRendererForModelElement;
     if (elementIsOnSinglePage) {
         Rectangle bbox = renderer.GetOccupiedArea().GetBBox();
         attributes.Put(PdfName.BBox, new PdfArray(bbox));
     }
     if (role.Equals(PdfName.TH) || role.Equals(PdfName.TD) || role.Equals(PdfName.Table)) {
         UnitValue width = renderer.GetProperty<UnitValue>(Property.WIDTH);
         if (width != null && width.IsPointValue()) {
             attributes.Put(PdfName.Width, new PdfNumber(width.GetValue()));
         }
         float? height = renderer.GetPropertyAsFloat(Property.HEIGHT);
         if (height != null) {
             attributes.Put(PdfName.Height, new PdfNumber((float)height));
         }
     }
     if (role.Equals(PdfName.TH) || role.Equals(PdfName.TD)) {
         HorizontalAlignment? horizontalAlignment = renderer.GetProperty<HorizontalAlignment?>(Property.HORIZONTAL_ALIGNMENT
             );
         if (horizontalAlignment != null) {
             attributes.Put(PdfName.BlockAlign, TransformBlockAlignToName(horizontalAlignment));
         }
         if (textAlignment != null && (textAlignment != TextAlignment.JUSTIFIED && textAlignment != TextAlignment.JUSTIFIED_ALL
             )) {
             //there is no justified alignment for InlineAlign attribute
             attributes.Put(PdfName.InlineAlign, TransformTextAlignmentValueToName(textAlignment));
         }
     }
 }
Пример #20
0
 private static bool CheckTypeOfPdfDictionary(PdfObject dictionary, PdfName expectedType)
 {
     return(dictionary.IsDictionary() && expectedType.Equals(((PdfDictionary)dictionary).GetAsName(PdfName.Type
                                                                                                   )));
 }
Пример #21
0
    protected override void LoadEncoding(
      )
    {
      OpenFontParser parser;
      {
        PdfDictionary descriptor = Descriptor;
        if(descriptor.ContainsKey(PdfName.FontFile2)) // Embedded TrueType font file (without 'glyf' table).
        {
          PdfStream fontFileStream = (PdfStream)descriptor.Resolve(PdfName.FontFile2);
          parser = new OpenFontParser(fontFileStream.Body);
        }
        else if(descriptor.ContainsKey(PdfName.FontFile3))
        {
          PdfStream fontFileStream = (PdfStream)descriptor.Resolve(PdfName.FontFile3);
          PdfName fontFileSubtype = (PdfName)fontFileStream.Header[PdfName.Subtype];
          if(fontFileSubtype.Equals(PdfName.OpenType)) // Embedded OpenFont/TrueType font file (with 'glyf' table).
          {parser = new OpenFontParser(fontFileStream.Body);}
          else // Unknown.
            throw new NotSupportedException("Unknown embedded font file format: " + fontFileSubtype);
        }
        else
        {parser = null;}
      }
      if(parser != null) // Embedded font file.
      {
        // Glyph indexes.
        glyphIndexes = parser.GlyphIndexes;
        if(codes != null
          && parser.Metrics.IsCustomEncoding)
        {
          /*
            NOTE: In case of symbolic font,
            glyph indices are natively mapped to character codes,
            so they must be remapped to Unicode whenever possible
            (i.e. when ToUnicode stream is available).
          */
          Dictionary<int,int> unicodeGlyphIndexes = new Dictionary<int,int>();
          foreach(KeyValuePair<int,int> glyphIndexEntry in glyphIndexes)
          {
            int code;
            if(!codes.TryGetValue(new ByteArray(new byte[]{(byte)(int)glyphIndexEntry.Key}),out code))
              continue;

            unicodeGlyphIndexes[code] = glyphIndexEntry.Value;
          }
          glyphIndexes = unicodeGlyphIndexes;
        }
      }

      PdfDataObject encodingObject = BaseDataObject.Resolve(PdfName.Encoding);
      FlagsEnum flags = Flags;
      if((flags & FlagsEnum.Symbolic) != 0
        || ((flags & FlagsEnum.Nonsymbolic) == 0 && encodingObject == null)) // Symbolic.
      {
        symbolic = true;

        if(glyphIndexes == null)
        {
          /*
            NOTE: In case no font file is available, we have to synthesize its metrics
            from existing entries.
          */
          glyphIndexes = new Dictionary<int,int>();
          PdfArray glyphWidthObjects = (PdfArray)BaseDataObject.Resolve(PdfName.Widths);
          if(glyphWidthObjects != null)
          {
            int code = ((PdfInteger)BaseDataObject[PdfName.FirstChar]).RawValue;
            foreach(PdfDirectObject glyphWidthObject in glyphWidthObjects)
            {
              if(((PdfInteger)glyphWidthObject).RawValue > 0)
              {glyphIndexes[code] = code;}

              code++;
            }
          }
        }

        if(this.codes == null)
        {
          Dictionary<ByteArray,int> codes = new Dictionary<ByteArray,int>();
          foreach(KeyValuePair<int,int> glyphIndexEntry in glyphIndexes)
          {
            if(glyphIndexEntry.Value > 0)
            {
              int glyphCharCode = glyphIndexEntry.Key;
              byte[] charCode = new byte[]{(byte)glyphCharCode};
              codes[new ByteArray(charCode)] = glyphCharCode;
            }
          }
          this.codes = new BiDictionary<ByteArray,int>(codes);
        }
      }
      else // Nonsymbolic.
      {
        symbolic = false;

        if(this.codes == null)
        {
          Dictionary<ByteArray,int> codes;
          if(encodingObject == null) // Default encoding.
          {codes = Encoding.Get(PdfName.StandardEncoding).GetCodes();}
          else if(encodingObject is PdfName) // Predefined encoding.
          {codes = Encoding.Get((PdfName)encodingObject).GetCodes();}
          else // Custom encoding.
          {
            PdfDictionary encodingDictionary = (PdfDictionary)encodingObject;

            // 1. Base encoding.
            PdfName baseEncodingName = (PdfName)encodingDictionary[PdfName.BaseEncoding];
            if(baseEncodingName == null) // Default base encoding.
            {codes = Encoding.Get(PdfName.StandardEncoding).GetCodes();}
            else // Predefined base encoding.
            {codes = Encoding.Get(baseEncodingName).GetCodes();}

            // 2. Differences.
            LoadEncodingDifferences(encodingDictionary, codes);
          }
          this.codes = new BiDictionary<ByteArray,int>(codes);
        }

        if(glyphIndexes == null)
        {
          /*
            NOTE: In case no font file is available, we have to synthesize its metrics
            from existing entries.
          */
          glyphIndexes = new Dictionary<int,int>();
          PdfArray glyphWidthObjects = (PdfArray)BaseDataObject.Resolve(PdfName.Widths);
          if(glyphWidthObjects != null)
          {
            ByteArray charCode = new ByteArray(
              new byte[]
              {(byte)(int)((PdfInteger)BaseDataObject[PdfName.FirstChar]).RawValue}
              );
            foreach(PdfDirectObject glyphWidthObject in glyphWidthObjects)
            {
              if(((PdfInteger)glyphWidthObject).RawValue > 0)
              {
                int code;
                if(codes.TryGetValue(charCode,out code))
                {glyphIndexes[code] = (int)charCode.Data[0];}
              }
              charCode.Data[0]++;
            }
          }
        }
      }
    }
Пример #22
0
        protected internal override void CheckAnnotation(PdfDictionary annotDic)
        {
            PdfName subtype = annotDic.GetAsName(PdfName.Subtype);

            if (subtype == null)
            {
                throw new PdfAConformanceException(PdfAConformanceException.AnnotationType1IsNotPermitted).SetMessageParams
                          ("null");
            }
            if (forbiddenAnnotations.Contains(subtype))
            {
                throw new PdfAConformanceException(PdfAConformanceException.AnnotationType1IsNotPermitted).SetMessageParams
                          (subtype.GetValue());
            }
            PdfNumber ca = annotDic.GetAsNumber(PdfName.CA);

            if (ca != null && ca.FloatValue() != 1.0)
            {
                throw new PdfAConformanceException(PdfAConformanceException.AnAnnotationDictionaryShallNotContainTheCaKeyWithAValueOtherThan1
                                                   );
            }
            if (!annotDic.ContainsKey(PdfName.F))
            {
                throw new PdfAConformanceException(PdfAConformanceException.AnnotationShallContainKeyF);
            }
            int flags = (int)annotDic.GetAsInt(PdfName.F);

            if (!CheckFlag(flags, PdfAnnotation.PRINT) || CheckFlag(flags, PdfAnnotation.HIDDEN) || CheckFlag(flags, PdfAnnotation
                                                                                                              .INVISIBLE) || CheckFlag(flags, PdfAnnotation.NO_VIEW))
            {
                throw new PdfAConformanceException(PdfAConformanceException.TheFKeysPrintFlagBitShallBeSetTo1AndItsHiddenInvisibleAndNoviewFlagBitsShallBeSetTo0
                                                   );
            }
            if (subtype.Equals(PdfName.Text) && (!CheckFlag(flags, PdfAnnotation.NO_ZOOM) || !CheckFlag(flags, PdfAnnotation
                                                                                                        .NO_ROTATE)))
            {
                throw new PdfAConformanceException(PdfAConformanceException.TextAnnotationsShouldSetTheNozoomAndNorotateFlagBitsOfTheFKeyTo1
                                                   );
            }
            if (annotDic.ContainsKey(PdfName.C) || annotDic.ContainsKey(PdfName.IC))
            {
                if (!ICC_COLOR_SPACE_RGB.Equals(pdfAOutputIntentColorSpace))
                {
                    throw new PdfAConformanceException(PdfAConformanceException.DestoutputprofileInThePdfa1OutputintentDictionaryShallBeRgb
                                                       );
                }
            }
            PdfDictionary ap = annotDic.GetAsDictionary(PdfName.AP);

            if (ap != null)
            {
                if (ap.ContainsKey(PdfName.D) || ap.ContainsKey(PdfName.R))
                {
                    throw new PdfAConformanceException(PdfAConformanceException.AppearanceDictionaryShallContainOnlyTheNKeyWithStreamValue
                                                       );
                }
                PdfStream n = ap.GetAsStream(PdfName.N);
                if (n == null)
                {
                    throw new PdfAConformanceException(PdfAConformanceException.AppearanceDictionaryShallContainOnlyTheNKeyWithStreamValue
                                                       );
                }
                CheckResourcesOfAppearanceStreams(ap);
            }
            if (PdfName.Widget.Equals(subtype) && (annotDic.ContainsKey(PdfName.AA) || annotDic.ContainsKey(PdfName.A)
                                                   ))
            {
                throw new PdfAConformanceException(PdfAConformanceException.WidgetAnnotationDictionaryOrFieldDictionaryShallNotIncludeAOrAAEntry
                                                   );
            }
            if (annotDic.ContainsKey(PdfName.AA))
            {
                throw new PdfAConformanceException(PdfAConformanceException.AnAnnotationDictionaryShallNotContainAAKey);
            }
            if (CheckStructure(conformanceLevel))
            {
                if (contentAnnotations.Contains(subtype) && !annotDic.ContainsKey(PdfName.Contents))
                {
                    throw new PdfAConformanceException(PdfAConformanceException.AnnotationOfType1ShouldHaveContentsKey).SetMessageParams
                              (subtype);
                }
            }
        }
Пример #23
0
        /// <summary>Verifies a signature.</summary>
        /// <remarks>
        /// Verifies a signature. Further verification can be done on the returned
        /// <see cref="PdfPKCS7"/>
        /// object.
        /// </remarks>
        /// <param name="name">the signature field name</param>
        /// <param name="provider">the provider or null for the default provider</param>
        /// <returns>PdfPKCS7 object to continue the verification</returns>
        public virtual PdfPKCS7 VerifySignature(String name)
        {
            PdfDictionary v = GetSignatureDictionary(name);

            if (v == null)
            {
                return(null);
            }
            try {
                PdfName   sub      = v.GetAsName(PdfName.SubFilter);
                PdfString contents = v.GetAsString(PdfName.Contents);
                PdfPKCS7  pk       = null;
                if (sub.Equals(PdfName.Adbe_x509_rsa_sha1))
                {
                    PdfString cert = v.GetAsString(PdfName.Cert);
                    if (cert == null)
                    {
                        cert = v.GetAsArray(PdfName.Cert).GetAsString(0);
                    }
                    pk = new PdfPKCS7(PdfEncodings.ConvertToBytes(contents.GetValue(), null), cert.GetValueBytes());
                }
                else
                {
                    pk = new PdfPKCS7(PdfEncodings.ConvertToBytes(contents.GetValue(), null), sub);
                }
                UpdateByteRange(pk, v);
                PdfString str = v.GetAsString(PdfName.M);
                if (str != null)
                {
                    pk.SetSignDate(PdfDate.Decode(str.ToString()));
                }
                PdfObject obj = v.Get(PdfName.Name);
                if (obj != null)
                {
                    if (obj.IsString())
                    {
                        pk.SetSignName(((PdfString)obj).ToUnicodeString());
                    }
                    else
                    {
                        if (obj.IsName())
                        {
                            pk.SetSignName(((PdfName)obj).GetValue());
                        }
                    }
                }
                str = v.GetAsString(PdfName.Reason);
                if (str != null)
                {
                    pk.SetReason(str.ToUnicodeString());
                }
                str = v.GetAsString(PdfName.Location);
                if (str != null)
                {
                    pk.SetLocation(str.ToUnicodeString());
                }
                return(pk);
            }
            catch (Exception e) {
                throw new PdfException(e);
            }
        }
Пример #24
0
        private static void ParseCid(String cmapName, AbstractCMap cmap, ICidLocation location, int level)
        {
            if (level >= MAXLEVEL)
            {
                return;
            }
            PRTokeniser inp = location.GetLocation(cmapName);

            try {
                List <PdfObject> list = new List <PdfObject>();
                PdfContentParser cp   = new PdfContentParser(inp);
                int maxExc            = 50;
                while (true)
                {
                    try {
                        cp.Parse(list);
                    }
                    catch {
                        if (--maxExc < 0)
                        {
                            break;
                        }
                        continue;
                    }
                    if (list.Count == 0)
                    {
                        break;
                    }
                    String last = list[list.Count - 1].ToString();
                    if (level == 0 && list.Count == 3 && last.Equals(DEF))
                    {
                        PdfObject key = list[0];
                        if (PdfName.REGISTRY.Equals(key))
                        {
                            cmap.Registry = list[1].ToString();
                        }
                        else if (PdfName.ORDERING.Equals(key))
                        {
                            cmap.Ordering = list[1].ToString();
                        }
                        else if (CMAPNAME.Equals(key))
                        {
                            cmap.Name = list[1].ToString();
                        }
                        else if (PdfName.SUPPLEMENT.Equals(key))
                        {
                            try {
                                cmap.Supplement = ((PdfNumber)list[1]).IntValue;
                            }
                            catch {}
                        }
                    }
                    else if ((last.Equals(ENDCIDCHAR) || last.Equals(ENDBFCHAR)) && list.Count >= 3)
                    {
                        int lmax = list.Count - 2;
                        for (int k = 0; k < lmax; k += 2)
                        {
                            if (list[k] is PdfString)
                            {
                                cmap.AddChar((PdfString)list[k], list[k + 1]);
                            }
                        }
                    }
                    else if ((last.Equals(ENDCIDRANGE) || last.Equals(ENDBFRANGE)) && list.Count >= 4)
                    {
                        int lmax = list.Count - 3;
                        for (int k = 0; k < lmax; k += 3)
                        {
                            if (list[k] is PdfString && list[k + 1] is PdfString)
                            {
                                cmap.AddRange((PdfString)list[k], (PdfString)list[k + 1], list[k + 2]);
                            }
                        }
                    }
                    else if (last.Equals(USECMAP) && list.Count == 2 && list[0] is PdfName)
                    {
                        ParseCid(PdfName.DecodeName(list[0].ToString()), cmap, location, level + 1);
                    }
                }
            }
            finally {
                inp.Close();
            }
        }
Пример #25
0
        /**
         * <summary>Wraps a font reference into a font object.</summary>
         * <param name="baseObject">Font base object.</param>
         * <returns>Font object associated to the reference.</returns>
         */
        public static Font Wrap(
            PdfDirectObject baseObject
            )
        {
            if (baseObject == null)
            {
                return(null);
            }

            PdfReference reference = (PdfReference)baseObject;
            {
                // Has the font been already instantiated?

                /*
                 * NOTE: Font structures are reified as complex objects, both IO- and CPU-intensive to load.
                 * So, it's convenient to retrieve them from a common cache whenever possible.
                 */
                Dictionary <PdfReference, object> cache = reference.IndirectObject.File.Document.Cache;
                if (cache.ContainsKey(reference))
                {
                    return((Font)cache[reference]);
                }
            }

            PdfDictionary fontDictionary = (PdfDictionary)reference.DataObject;
            PdfName       fontType       = (PdfName)fontDictionary[PdfName.Subtype];

            if (fontType == null)
            {
                throw new Exception("Font type undefined (reference: " + reference + ")");
            }

            if (fontType.Equals(PdfName.Type1))                          // Type 1.
            {
                if (!fontDictionary.ContainsKey(PdfName.FontDescriptor)) // Standard Type 1.
                {
                    return(new StandardType1Font(reference));
                }
                else // Custom Type 1.
                {
                    PdfDictionary fontDescriptor = (PdfDictionary)fontDictionary.Resolve(PdfName.FontDescriptor);
                    if (fontDescriptor.ContainsKey(PdfName.FontFile3) &&
                        ((PdfName)((PdfStream)fontDescriptor.Resolve(PdfName.FontFile3)).Header.Resolve(PdfName.Subtype)).Equals(PdfName.OpenType)) // OpenFont/CFF.
                    {
                        throw new NotImplementedException();
                    }
                    else // Non-OpenFont Type 1.
                    {
                        return(new Type1Font(reference));
                    }
                }
            }
            else if (fontType.Equals(PdfName.TrueType)) // TrueType.
            {
                return(new TrueTypeFont(reference));
            }
            else if (fontType.Equals(PdfName.Type0)) // OpenFont.
            {
                PdfDictionary cidFontDictionary = (PdfDictionary)((PdfArray)fontDictionary.Resolve(PdfName.DescendantFonts)).Resolve(0);
                PdfName       cidFontType       = (PdfName)cidFontDictionary[PdfName.Subtype];
                if (cidFontType.Equals(PdfName.CIDFontType0)) // OpenFont/CFF.
                {
                    return(new Type0Font(reference));
                }
                else if (cidFontType.Equals(PdfName.CIDFontType2)) // OpenFont/TrueType.
                {
                    return(new Type2Font(reference));
                }
                else
                {
                    throw new NotImplementedException("Type 0 subtype " + cidFontType + " not supported yet.");
                }
            }
            else if (fontType.Equals(PdfName.Type3)) // Type 3.
            {
                return(new Type3Font(reference));
            }
            else if (fontType.Equals(PdfName.MMType1)) // MMType1.
            {
                return(new MMType1Font(reference));
            }
            else // Unknown.
            {
                throw new NotSupportedException("Unknown font type: " + fontType + " (reference: " + reference + ")");
            }
        }
Пример #26
0
        // methods concerning the type of Dictionary

        /**
         *  Checks if a <CODE>Dictionary</CODE> is of the type FONT.
         *
         * @return        <CODE>true</CODE> if it is, <CODE>false</CODE> if it isn't.
         */

        public bool IsFont()
        {
            return(FONT.Equals(dictionaryType));
        }
Пример #27
0
        /**
         * <summary>Gets a specific filter object.</summary>
         * <param name="name">Name of the requested filter.</param>
         * <returns>Filter object associated to the name.</returns>
         */
        public static Filter Get(
            PdfName name
            )
        {
            /*
             * NOTE: This is a factory singleton method for any filter-derived object.
             */
            if (name == null)
            {
                return(null);
            }

            if (name.Equals(PdfName.FlateDecode) ||
                name.Equals(PdfName.Fl))
            {
                return(FlateDecode);
            }
            else if (name.Equals(PdfName.LZWDecode) ||
                     name.Equals(PdfName.LZW))
            {
                throw new NotImplementedException("LZWDecode");
            }
            else if (name.Equals(PdfName.ASCIIHexDecode) ||
                     name.Equals(PdfName.AHx))
            {
                throw new NotImplementedException("ASCIIHexDecode");
            }
            else if (name.Equals(PdfName.ASCII85Decode) ||
                     name.Equals(PdfName.A85))
            {
                return(ASCII85Filter);
            }
            else if (name.Equals(PdfName.RunLengthDecode) ||
                     name.Equals(PdfName.RL))
            {
                throw new NotImplementedException("RunLengthDecode");
            }
            else if (name.Equals(PdfName.CCITTFaxDecode) ||
                     name.Equals(PdfName.CCF))
            {
                throw new NotImplementedException("CCITTFaxDecode");
            }
            else if (name.Equals(PdfName.JBIG2Decode))
            {
                throw new NotImplementedException("JBIG2Decode");
            }
            else if (name.Equals(PdfName.DCTDecode) ||
                     name.Equals(PdfName.DCT))
            {
                throw new NotImplementedException("DCTDecode");
            }
            else if (name.Equals(PdfName.JPXDecode))
            {
                throw new NotImplementedException("JPXDecode");
            }
            else if (name.Equals(PdfName.Crypt))
            {
                throw new NotImplementedException("Crypt");
            }

            return(null);
        }
Пример #28
0
        /**
         *  Checks if a <CODE>Dictionary</CODE> is of the type CATALOG.
         *
         * @return        <CODE>true</CODE> if it is, <CODE>false</CODE> if it isn't.
         */

        public bool IsCatalog()
        {
            return(CATALOG.Equals(dictionaryType));
        }
        public void GetRectAnno(int nPage)
        {
            string appRootDir = new DirectoryInfo(Environment.CurrentDirectory).Parent.Parent.FullName;

            string filePath = outputFile;
            int    pageFrom = 0;
            int    pageTo   = 0;

            listaRectangulos.Clear();
            try
            {
                using (PdfReader reader = new PdfReader(filePath))
                {
                    pageTo = reader.NumberOfPages;

                    //for (int i = 1; i <= reader.NumberOfPages; i++)// tomar un gripo de paginas

                    // {


                    PdfDictionary page   = reader.GetPageN(nPage);  // para grupo de pagina remplazar nPage por i
                    PdfArray      annots = page.GetAsArray(iTextSharp.text.pdf.PdfName.ANNOTS);
                    if (annots != null)
                    {
                        foreach (PdfObject annot in annots.ArrayList)
                        {
                            //abtiene Annotation de PDF File
                            PdfDictionary annotationDic = (PdfDictionary)PdfReader.GetPdfObject(annot);
                            PdfName       subType       = (PdfName)annotationDic.Get(PdfName.SUBTYPE);
                            //solo el subtype highlight
                            if (subType.Equals(PdfName.HIGHLIGHT))
                            {
                                // Obtiene Quadpoints y Rectángulo de texto resaltado
                                //Console.Write("HighLight at Rectangle {0} with QuadPoints {1}\n", annotationDic.GetAsArray(PdfName.RECT), annotationDic.GetAsArray(PdfName.QUADPOINTS));


                                outputData = "HighLight at Rectangle {0} with QuadPoints {1}\n" + annotationDic.GetAsArray(PdfName.RECT) + annotationDic.GetAsArray(PdfName.QUADPOINTS);
                                //Extraer texto usando la estrategia de rectángulo
                                PdfArray coordinates = annotationDic.GetAsArray(PdfName.RECT);

                                iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(float.Parse(coordinates.ArrayList[0].ToString(), CultureInfo.InvariantCulture.NumberFormat), float.Parse(coordinates.ArrayList[1].ToString(), CultureInfo.InvariantCulture.NumberFormat),
                                                                                               float.Parse(coordinates.ArrayList[2].ToString(), CultureInfo.InvariantCulture.NumberFormat), float.Parse(coordinates.ArrayList[3].ToString(), CultureInfo.InvariantCulture.NumberFormat));

                                listaRectangulos.Add(rect);


                                RenderFilter[]          filter = { new RegionTextRenderFilter(rect) };
                                ITextExtractionStrategy strategy;
                                StringBuilder           sb = new StringBuilder();


                                strategy = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), filter);
                                sb.AppendLine(PdfTextExtractor.GetTextFromPage(reader, nPage, strategy));    //para un grupo de paginas cambiar nPage por i
                            }
                        }
                    }
                }
                // }
            }
            catch (Exception ex)
            {
            }
        }
Пример #30
0
        /**
         * <summary>Wraps the specified color space base object into a color space object.</summary>
         * <param name="baseObject">Base object of a color space object.</param>
         * <returns>Color space object corresponding to the base object.</returns>
         */
        public static ColorSpace Wrap(
            PdfDirectObject baseObject
            )
        {
            if (baseObject == null)
            {
                return(null);
            }

            // Get the data object corresponding to the color space!
            PdfDataObject baseDataObject = baseObject.Resolve();

            /*
             * NOTE: A color space is defined by an array object whose first element
             * is a name object identifying the color space family [PDF:1.6:4.5.2].
             * For families that do not require parameters, the color space CAN be
             * specified simply by the family name itself instead of an array.
             */
            PdfName name = (PdfName)(baseDataObject is PdfArray
        ? ((PdfArray)baseDataObject)[0]
        : baseDataObject);

            if (name.Equals(PdfName.DeviceRGB))
            {
                return(new DeviceRGBColorSpace(baseObject));
            }
            else if (name.Equals(PdfName.DeviceCMYK))
            {
                return(new DeviceCMYKColorSpace(baseObject));
            }
            else if (name.Equals(PdfName.DeviceGray))
            {
                return(new DeviceGrayColorSpace(baseObject));
            }
            else if (name.Equals(PdfName.CalRGB))
            {
                return(new CalRGBColorSpace(baseObject));
            }
            else if (name.Equals(PdfName.CalGray))
            {
                return(new CalGrayColorSpace(baseObject));
            }
            else if (name.Equals(PdfName.ICCBased))
            {
                return(new ICCBasedColorSpace(baseObject));
            }
            else if (name.Equals(PdfName.Lab))
            {
                return(new LabColorSpace(baseObject));
            }
            else if (name.Equals(PdfName.DeviceN))
            {
                return(new DeviceNColorSpace(baseObject));
            }
            else if (name.Equals(PdfName.Indexed))
            {
                return(new IndexedColorSpace(baseObject));
            }
            else if (name.Equals(PdfName.Pattern))
            {
                return(new PatternColorSpace(baseObject));
            }
            else if (name.Equals(PdfName.Separation))
            {
                return(new SeparationColorSpace(baseObject));
            }
            else
            {
                throw new NotSupportedException("Color space " + name + " unknown.");
            }
        }
Пример #31
0
        protected internal override void CheckAnnotation(PdfDictionary annotDic)
        {
            PdfName subtype = annotDic.GetAsName(PdfName.Subtype);

            if (subtype == null)
            {
                throw new PdfAConformanceException(PdfAConformanceException.ANNOTATION_TYPE_0_IS_NOT_PERMITTED).SetMessageParams
                          ("null");
            }
            if (forbiddenAnnotations.Contains(subtype))
            {
                throw new PdfAConformanceException(PdfAConformanceException.ANNOTATION_TYPE_0_IS_NOT_PERMITTED).SetMessageParams
                          (subtype.GetValue());
            }
            PdfNumber ca = annotDic.GetAsNumber(PdfName.CA);

            if (ca != null && ca.FloatValue() != 1.0)
            {
                throw new PdfAConformanceException(PdfAConformanceException.AN_ANNOTATION_DICTIONARY_SHALL_NOT_CONTAIN_THE_CA_KEY_WITH_A_VALUE_OTHER_THAN_1
                                                   );
            }
            if (!annotDic.ContainsKey(PdfName.F))
            {
                throw new PdfAConformanceException(PdfAConformanceException.AN_ANNOTATION_DICTIONARY_SHALL_CONTAIN_THE_F_KEY
                                                   );
            }
            int flags = (int)annotDic.GetAsInt(PdfName.F);

            if (!CheckFlag(flags, PdfAnnotation.PRINT) || CheckFlag(flags, PdfAnnotation.HIDDEN) || CheckFlag(flags, PdfAnnotation
                                                                                                              .INVISIBLE) || CheckFlag(flags, PdfAnnotation.NO_VIEW))
            {
                throw new PdfAConformanceException(PdfAConformanceException.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 (subtype.Equals(PdfName.Text) && (!CheckFlag(flags, PdfAnnotation.NO_ZOOM) || !CheckFlag(flags, PdfAnnotation
                                                                                                        .NO_ROTATE)))
            {
                throw new PdfAConformanceException(PdfAConformanceLogMessageConstant.TEXT_ANNOTATIONS_SHOULD_SET_THE_NOZOOM_AND_NOROTATE_FLAG_BITS_OF_THE_F_KEY_TO_1
                                                   );
            }
            if (annotDic.ContainsKey(PdfName.C) || annotDic.ContainsKey(PdfName.IC))
            {
                if (!ICC_COLOR_SPACE_RGB.Equals(pdfAOutputIntentColorSpace))
                {
                    throw new PdfAConformanceException(PdfAConformanceException.DESTOUTPUTPROFILE_IN_THE_PDFA1_OUTPUTINTENT_DICTIONARY_SHALL_BE_RGB
                                                       );
                }
            }
            PdfDictionary ap = annotDic.GetAsDictionary(PdfName.AP);

            if (ap != null)
            {
                if (ap.ContainsKey(PdfName.D) || ap.ContainsKey(PdfName.R))
                {
                    throw new PdfAConformanceException(PdfAConformanceException.APPEARANCE_DICTIONARY_SHALL_CONTAIN_ONLY_THE_N_KEY_WITH_STREAM_VALUE
                                                       );
                }
                PdfStream n = ap.GetAsStream(PdfName.N);
                if (n == null)
                {
                    throw new PdfAConformanceException(PdfAConformanceException.APPEARANCE_DICTIONARY_SHALL_CONTAIN_ONLY_THE_N_KEY_WITH_STREAM_VALUE
                                                       );
                }
                CheckResourcesOfAppearanceStreams(ap);
            }
            if (PdfName.Widget.Equals(subtype) && (annotDic.ContainsKey(PdfName.AA) || annotDic.ContainsKey(PdfName.A)
                                                   ))
            {
                throw new PdfAConformanceException(PdfAConformanceException.WIDGET_ANNOTATION_DICTIONARY_OR_FIELD_DICTIONARY_SHALL_NOT_INCLUDE_A_OR_AA_ENTRY
                                                   );
            }
            if (annotDic.ContainsKey(PdfName.AA))
            {
                throw new PdfAConformanceException(PdfAConformanceException.AN_ANNOTATION_DICTIONARY_SHALL_NOT_CONTAIN_AA_KEY
                                                   );
            }
            if (CheckStructure(conformanceLevel))
            {
                if (contentAnnotations.Contains(subtype) && !annotDic.ContainsKey(PdfName.Contents))
                {
                    throw new PdfAConformanceException(PdfAConformanceException.ANNOTATION_OF_TYPE_0_SHOULD_HAVE_CONTENTS_KEY)
                          .SetMessageParams(subtype.GetValue());
                }
            }
        }
Пример #32
0
        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);
        }
Пример #33
0
        /**
         * <summary>Wraps an annotation base object into an annotation object.</summary>
         * <param name="baseObject">Annotation base object.</param>
         * <param name="container">Annotation base object container.</param>
         * <returns>Annotation object associated to the base object.</returns>
         */
        public static Annotation Wrap(
            PdfDirectObject baseObject,
            PdfIndirectObject container
            )
        {
            /*
             * NOTE: This is a factory method for any annotation-derived object.
             */
            if (baseObject == null)
            {
                return(null);
            }

            PdfDictionary dataObject = (PdfDictionary)File.Resolve(baseObject);

            if (!dataObject[PdfName.Type].Equals(PdfName.Annot))
            {
                return(null);
            }

            PdfName annotationType = (PdfName)dataObject[PdfName.Subtype];

            if (annotationType.Equals(PdfName.Text))
            {
                return(new Note(baseObject, container));
            }
            else if (annotationType.Equals(PdfName.Link))
            {
                return(new Link(baseObject, container));
            }
            else if (annotationType.Equals(PdfName.FreeText))
            {
                return(new CalloutNote(baseObject, container));
            }
            else if (annotationType.Equals(PdfName.Line))
            {
                return(new Line(baseObject, container));
            }
            else if (annotationType.Equals(PdfName.Square))
            {
                return(new Rectangle(baseObject, container));
            }
            else if (annotationType.Equals(PdfName.Circle))
            {
                return(new Ellipse(baseObject, container));
            }
            else if (annotationType.Equals(PdfName.Polygon))
            {
                return(new Polygon(baseObject, container));
            }
            else if (annotationType.Equals(PdfName.PolyLine))
            {
                return(new Polyline(baseObject, container));
            }
            else if (annotationType.Equals(PdfName.Highlight) ||
                     annotationType.Equals(PdfName.Underline) ||
                     annotationType.Equals(PdfName.Squiggly) ||
                     annotationType.Equals(PdfName.StrikeOut))
            {
                return(new TextMarkup(baseObject, container));
            }
            else if (annotationType.Equals(PdfName.Stamp))
            {
                return(new RubberStamp(baseObject, container));
            }
            else if (annotationType.Equals(PdfName.Caret))
            {
                return(new Caret(baseObject, container));
            }
            else if (annotationType.Equals(PdfName.Ink))
            {
                return(new Scribble(baseObject, container));
            }
            else if (annotationType.Equals(PdfName.Popup))
            {
                return(new Popup(baseObject, container));
            }
            else if (annotationType.Equals(PdfName.FileAttachment))
            {
                return(new FileAttachment(baseObject, container));
            }
            else if (annotationType.Equals(PdfName.Sound))
            {
                return(new Sound(baseObject, container));
            }
            else if (annotationType.Equals(PdfName.Movie))
            {
                return(new Movie(baseObject, container));
            }
            else if (annotationType.Equals(PdfName.Widget))
            {
                return(new Widget(baseObject, container));
            }
//TODO
//     else if(annotationType.Equals(PdfName.Screen)) return new Screen(baseObject,container);
//     else if(annotationType.Equals(PdfName.PrinterMark)) return new PrinterMark(baseObject,container);
//     else if(annotationType.Equals(PdfName.TrapNet)) return new TrapNet(baseObject,container);
//     else if(annotationType.Equals(PdfName.Watermark)) return new Watermark(baseObject,container);
//     else if(annotationType.Equals(PdfName.3DAnnotation)) return new 3DAnnotation(baseObject,container);
            else // Other annotation type.
            {
                return(new Annotation(baseObject, container));
            }
        }