Ejemplo n.º 1
0
   internal JavaScript(
 PdfDirectObject baseObject,
 PdfString name
 )
       : base(baseObject, name)
   {
   }
Ejemplo n.º 2
0
   internal RemoteDestination(
 PdfDirectObject baseObject,
 PdfString name
 )
       : base(baseObject, name)
   {
   }
Ejemplo n.º 3
0
 public PdfDictionary GetEncrypt(PdfObjectId objectId)
 {
     PdfDictionary encrypt = new PdfDictionary(objectId);
     encrypt[PdfName.Names.Filter] = PdfName.Names.Standard;
     encrypt[PdfName.Names.V] = new PdfNumeric(1);
     encrypt[PdfName.Names.Length] = new PdfNumeric(40);
     encrypt[PdfName.Names.R] = new PdfNumeric(2);
     PdfString o = new PdfString(ownerEntry);
     o.NeverEncrypt = true;
     encrypt[PdfName.Names.O] = o;
     PdfString u = new PdfString(userEntry);
     u.NeverEncrypt = true;
     encrypt[PdfName.Names.U] = u;
     encrypt[PdfName.Names.P] = new PdfNumeric(permissions);
     return encrypt;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="FreeTextAnnotation"/> class.
        /// </summary>
        /// <param name="color">The text color.</param>
        /// <param name="font">The font name.</param>
        /// <param name="fontSize">Size of the font.</param>
        public FreeTextAnnotation(XColor color, string font, double fontSize)
        {
            Elements.SetName(Keys.Subtype, "/FreeText");
            
            string daString = string.Format(CultureInfo.InvariantCulture,
                "{0} {1} {2} rg /{3} {4} Tf /BG []",
                color.R / (double)byte.MaxValue,
                color.G / (double)byte.MaxValue,
                color.B / (double)byte.MaxValue,
                font, fontSize);
            Elements["/DA"] = new PdfString(daString);

            // no border
            var border = new PdfArray();
            border.Elements.Add(new PdfInteger(0));
            border.Elements.Add(new PdfInteger(0));
            border.Elements.Add(new PdfInteger(0));
            Elements[Keys.Border] = border;
        }
Ejemplo n.º 5
0
 /**
  * Split PDF string into array of single character PDF strings.
  * @param string    PDF string to be splitted.
  * @return          splitted PDF string.
  */
 private PdfString[] SplitString(PdfString @string) {
     List<PdfString> strings = new List<PdfString>();
     String stringValue = @string.ToString();
     for (int i = 0; i < stringValue.Length; i++) {
         PdfString newString = new PdfString(stringValue.Substring(i, 1), @string.Encoding);
         String text = DecodeSingleCharacter(newString);
         if (text.Length == 0 && i < stringValue.Length - 1) {
             newString = new PdfString(stringValue.Substring(i, 2), @string.Encoding);
             i++;
         }
         strings.Add(newString);
     }
     return strings.ToArray();
 }
Ejemplo n.º 6
0
 public virtual PdfObject Visit(
     PdfString obj,
     object data
     )
 {
     return obj;
 }
Ejemplo n.º 7
0
 /// <summary>The default appearance string that shall be used in formatting the text.</summary>
 /// <remarks>The default appearance string that shall be used in formatting the text. See ISO-32001 12.7.3.3, “Variable Text”.
 ///     </remarks>
 /// <param name="appearanceString">
 /// a
 /// <see cref="iText.Kernel.Pdf.PdfString"/>
 /// that specifies the default appearance.
 /// </param>
 /// <returns>
 /// this
 /// <see cref="PdfMarkupAnnotation"/>
 /// instance.+
 /// </returns>
 public virtual iText.Kernel.Pdf.Annot.PdfRedactAnnotation SetDefaultAppearance(PdfString appearanceString)
 {
     return((iText.Kernel.Pdf.Annot.PdfRedactAnnotation)Put(PdfName.DA, appearanceString));
 }
Ejemplo n.º 8
0
 /**
  * Calculates width and word spacing of a single character PDF string.
  * @param string            a character to calculate width.
  * @param singleCharString  true if PDF string represents single character, false otherwise.
  * @return                  array of 2 items: first item is a character width, second item is a calculated word spacing.
  */
 private float[] GetWidthAndWordSpacing(PdfString @string, bool singleCharString) {
     if (singleCharString == false)
         throw new InvalidOperationException();
     float[] result = new float[2];
     String decoded = DecodeSingleCharacter(@string);
     result[0] = (float) (gs.font.GetWidth(GetCharCode(decoded)) * fontMatrix[0]);
     result[1] = decoded.Equals(" ") ? gs.wordSpacing : 0;
     return result;
 }
Ejemplo n.º 9
0
        internal static void FillFontDescriptor(iText.Kernel.Font.DocType1Font font, PdfDictionary fontDesc)
        {
            if (fontDesc == null)
            {
                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];
                //llx
                bbox[0] = bboxValue.GetAsNumber(0).IntValue();
                //lly
                bbox[1] = bboxValue.GetAsNumber(1).IntValue();
                //urx
                bbox[2] = bboxValue.GetAsNumber(2).IntValue();
                //ury
                bbox[3] = bboxValue.GetAsNumber(3).IntValue();
                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;
                }
            }
        }
Ejemplo n.º 10
0
 public abstract String Decode(PdfString content);
Ejemplo n.º 11
0
 public virtual iText.Kernel.Pdf.Annot.PdfCaretAnnotation SetSymbol(PdfString symbol)
 {
     return((iText.Kernel.Pdf.Annot.PdfCaretAnnotation)Put(PdfName.Sy, symbol));
 }
Ejemplo n.º 12
0
 /// <summary>Sets a human-readable text string that described this trap network to the user.</summary>
 /// <remarks>
 /// Sets a human-readable text string that described this trap network to the user.
 /// <see cref="iText.Kernel.Pdf.PdfName.TrapStyles"/>
 /// key.
 /// </remarks>
 /// <param name="trapStyles">
 /// a
 /// <see cref="iText.Kernel.Pdf.PdfString"/>
 /// value.
 /// </param>
 /// <returns>object itself.</returns>
 public virtual iText.Kernel.Pdf.Xobject.PdfFormXObject SetTrapStyles(PdfString trapStyles)
 {
     return(Put(PdfName.TrapStyles, trapStyles));
 }
Ejemplo n.º 13
0
 /**
  * Text that shall be concatenated after the label specified by setLabel. An
  * empty string indicates that no text shall be added.<br />
  * Default value: A single ASCII SPACE character "\u0020"
  *
  * @param ss
  */
 virtual public void SetLabelRightString(PdfString ss)
 {
     base.Put(PdfName.SS, ss);
 }
Ejemplo n.º 14
0
 /**
  * A text string specifying a label for displaying the units represented by
  * this NumberFormat in a user interface; the label should use a universally
  * recognized abbreviation.
  *
  * @param label
  */
 virtual public void SetLabel(PdfString label)
 {
     base.Put(PdfName.U, label);
 }
Ejemplo n.º 15
0
 /**
  * Text that shall be concatenated to the left of the label specified by
  * setLabel. An empty string indicates that no text shall be added.<br />
  * Default value: A single ASCII SPACE character "\u0020"
  *
  * @param ps
  */
 virtual public void SetLabelLeftString(PdfString ps)
 {
     base.Put(PdfName.PS, ps);
 }
Ejemplo n.º 16
0
 /**
  * Text that shall be used as the decimal position in displaying numerical
  * values. An empty string indicates that the default shall be used.<br />
  * Default value: PERIOD "\u002E"
  *
  * @param dc
  */
 virtual public void SetDecimalChartacter(PdfString dc)
 {
     base.Put(PdfName.RD, dc);
 }
Ejemplo n.º 17
0
 /**
  * Text that shall be used between orders of thousands in display of
  * numerical values. An empty string indicates that no text shall be added.<br />
  * Default value: COMMA "\u002C"
  *
  * @param rt
  */
 virtual public void SetCipherGroupingCharacter(PdfString rt)
 {
     base.Put(PdfName.RT, rt);
 }
Ejemplo n.º 18
0
        /**
         * Displays text.
         * @param string    the text to display
         */
        private void DisplayPdfString(PdfString str){

            String unicode = Decode(str);

            TextRenderInfo renderInfo = new TextRenderInfo(unicode, Gs(), textMatrix, markedContentStack);

            renderListener.RenderText(renderInfo);

            textMatrix = new Matrix(renderInfo.GetUnscaledWidth(), 0).Multiply(textMatrix);
        }
Ejemplo n.º 19
0
        /**
         * Converts an annotation structure item to a Form XObject annotation.
         * @param item the structure item
         * @throws IOException
         */
        virtual protected void ConvertToXObject(StructureObject item)
        {
            PdfDictionary structElem = item.GetStructElem();

            if (structElem == null)
            {
                return;
            }
            PdfDictionary dict = item.GetObjAsDict();

            if (dict == null || !dict.CheckType(PdfName.ANNOT))
            {
                return;
            }
            PdfDictionary ap = dict.GetAsDict(PdfName.AP);

            if (ap == null)
            {
                return;
            }
            PdfNumber structParent = dict.GetAsNumber(PdfName.STRUCTPARENT);

            if (structParent == null)
            {
                return;
            }
            PdfStream stream = ap.GetAsStream(PdfName.N);

            if (stream == null)
            {
                return;
            }
            stream.Put(PdfName.STRUCTPARENT, structParent);
            PdfIndirectReference xobjr = ap.GetAsIndirectObject(PdfName.N);

            if (xobjr == null)
            {
                return;
            }
            // remove the annotation from the page
            for (int i = 0; i < annots.Length; i++)
            {
                PdfIndirectReference annotref = annots.GetAsIndirectObject(i);
                if (item.GetObjRef().Number == annotref.Number)
                {
                    annots.Remove(i);
                    break;
                }
            }
            // replace the existing attributes by a PrintField attribute
            PdfDictionary attribute = new PdfDictionary();

            attribute.Put(PdfName.O, PdfName.PRINTFIELD);
            PdfString description = dict.GetAsString(PdfName.TU);

            if (description == null)
            {
                description = dict.GetAsString(PdfName.T);
            }
            if (PdfName.BTN.Equals(dict.Get(PdfName.FT)))
            {
                PdfNumber fflags = dict.GetAsNumber(PdfName.FF);
                if (fflags != null)
                {
                    int ff = fflags.IntValue;
                    if ((ff & PdfFormField.FF_PUSHBUTTON) != 0)
                    {
                        attribute.Put(PdfName.ROLE, PdfName.PB);
                    }
                    // I don't think the condition below will ever be true
                    if ((ff & PdfFormField.FF_RADIO) != 0)
                    {
                        attribute.Put(PdfName.ROLE, PdfName.rb);
                    }
                    else
                    {
                        attribute.Put(PdfName.ROLE, PdfName.CB);
                    }
                }
            }
            else
            {
                attribute.Put(PdfName.ROLE, PdfName.TV);
            }
            attribute.Put(PdfName.DESC, description);
            // Updating the values of the StructElem dictionary
            PdfString t = structElem.GetAsString(PdfName.T);

            if (t == null || t.ToString().Trim().Length == 0)
            {
                structElem.Put(PdfName.T, dict.GetAsString(PdfName.T));
            }
            structElem.Put(PdfName.A, attribute);
            structElem.Put(PdfName.S, PdfName.P);
            structElem.Put(PdfName.PG, pageref);
            // Defining a new MCID
            int mcid = items.ProcessMCID(structParents, item.GetRef());

            LOGGER.Info("Using MCID " + mcid);
            structElem.Put(PdfName.K, new PdfNumber(mcid));
            // removing the annotation from the parent tree
            items.RemoveFromParentTree(structParent);
            // Adding the XObject to the page
            PdfName xobj = new PdfName("XObj" + structParent.IntValue);

            LOGGER.Info("Creating XObject with name " + xobj);
            xobjects.Put(xobj, xobjr);
            PdfArray array = dict.GetAsArray(PdfName.RECT);
            // Getting the position of the annotation
            Rectangle rect = new Rectangle(
                array.GetAsNumber(0).FloatValue, array.GetAsNumber(1).FloatValue,
                array.GetAsNumber(2).FloatValue, array.GetAsNumber(3).FloatValue);

            rect.Normalize();
            // A Do operator is forbidden inside a text block
            if (inText && !btWrite)
            {
                LOGGER.Debug("Introducing extra ET");
                byte[] bytes = Encoding.ASCII.GetBytes("ET\n");
                baos.Write(bytes, 0, bytes.Length);
                etExtra = true;
            }
            // Writing the marked-content sequence with the Do operator
            // Note that the position assumes that the CTM wasn't changed in the graphics state
            // TODO: do the math if the CTM did change!
            ByteBuffer buf = new ByteBuffer();

            buf.Append("/P <</MCID ");
            buf.Append(mcid);
            buf.Append(">> BDC\n");
            buf.Append("q 1 0 0 1 ");
            buf.Append(rect.Left.ToString(CultureInfo.InvariantCulture));
            buf.Append(" ");
            buf.Append(rect.Bottom.ToString(CultureInfo.InvariantCulture));
            buf.Append(" cm ");
            buf.Append(xobj.GetBytes());
            buf.Append(" Do Q\n");
            buf.Append("EMC\n");
            buf.Flush();
            buf.WriteTo(baos);
            // if we were inside a text block, we've introduced an ET, so we'll need to write a BT
            if (inText)
            {
                btWrite = true;
            }
        }
Ejemplo n.º 20
0
        private PdfFormField MergeFieldsWithTheSameName(PdfFormField newField)
        {
            String    fullFieldName = newField.GetFieldName().ToUnicodeString();
            PdfString fieldName     = newField.GetPdfObject().GetAsString(PdfName.T);

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

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

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

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

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

            if (value != null)
            {
                mergedField.Put(PdfName.V, existingField.GetPdfObject().Get(PdfName.V));
            }
            return(mergedField);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Parses a stream object and removes OCGs. </summary>
        /// <param name="stream">	a stream object </param>
        /// <param name="resources">	the resources dictionary of that object (containing info about the OCGs) </param>
        public virtual void Parse(PRStream stream, PdfDictionary resources)
        {
            baos       = new MemoryStream();
            properties = resources.GetAsDict(PdfName.PROPERTIES);
            xobj       = new HashSet2 <PdfName>();
            PdfDictionary xobjects = resources.GetAsDict(PdfName.XOBJECT);

            if (xobjects != null)
            {
                // remove XObject (form or image) that belong to an OCG that needs to be removed
                foreach (PdfName name in xobjects.Keys)
                {
                    PRStream      xobject = (PRStream)xobjects.GetAsStream(name);
                    PdfDictionary oc      = xobject.GetAsDict(PdfName.OC);
                    if (oc != null)
                    {
                        PdfString ocname = oc.GetAsString(PdfName.NAME);
                        if (ocname != null && ocgs.Contains(ocname.ToString()))
                        {
                            xobj.Add(name);
                        }
                    }
                }
                foreach (PdfName name in xobj)
                {
                    xobjects.Remove(name);
                }
            }
            // parse the content stream
            byte[]           contentBytes = PdfReader.GetStreamBytes(stream);
            PRTokeniser      tokeniser    = new PRTokeniser(new RandomAccessFileOrArray(contentBytes));
            PdfContentParser ps           = new PdfContentParser(tokeniser);
            List <PdfObject> operands     = new List <PdfObject>();

            while (ps.Parse(operands).Count > 0)
            {
                PdfLiteral @operator = (PdfLiteral)operands[operands.Count - 1];
                ProcessOperator(this, @operator, operands);
                if ("BI".Equals(@operator.ToString()))
                {
                    int  found = 0;
                    int  ch;
                    bool immediateAfterBI = true;
                    while ((ch = tokeniser.Read()) != -1)
                    {
                        if (!immediateAfterBI || !PRTokeniser.IsWhitespace(ch))
                        {
                            baos.WriteByte((byte)ch);
                        }
                        immediateAfterBI = false;
                        if (found == 0 && PRTokeniser.IsWhitespace(ch))
                        {
                            found++;
                        }
                        else if (found == 1 && ch == 'E')
                        {
                            found++;
                        }
                        else if (found == 1 && PRTokeniser.IsWhitespace(ch))
                        {
                            // this clause is needed if we have a white space character that is part of the image data
                            // followed by a whitespace character that precedes the EI operator.  In this case, we need
                            // to flush the first whitespace, then treat the current whitespace as the first potential
                            // character for the end of stream check. Note that we don't increment 'found' here.
                        }
                        else if (found == 2 && ch == 'I')
                        {
                            found++;
                        }
                        else if (found == 3 && PRTokeniser.IsWhitespace(ch))
                        {
                            break;
                        }
                        else
                        {
                            found = 0;
                        }
                    }
                }
            }
            baos.Flush();
            baos.Close();
            stream.SetData(baos.GetBuffer());
        }
Ejemplo n.º 22
0
 //-----Additional entries in form dictionary for Printer Mark annotation
 /// <summary>Sets a text string representing the printer’s mark in human-readable form.</summary>
 /// <param name="markStyle">a string value.</param>
 /// <returns>object itself.</returns>
 public virtual iText.Kernel.Pdf.Xobject.PdfFormXObject SetMarkStyle(PdfString markStyle)
 {
     return(Put(PdfName.MarkStyle, markStyle));
 }
Ejemplo n.º 23
0
        private void RefreshAppearance(
      )
        {
            Widget widget = Widgets[0];
              FormXObject normalAppearance;
              {
            AppearanceStates normalAppearances = widget.Appearance.Normal;
            normalAppearance = normalAppearances[null];
            if(normalAppearance == null)
            {normalAppearances[null] = normalAppearance = new FormXObject(Document, widget.Box.Size);}
              }
              PdfName fontName = null;
              double fontSize = 0;
              {
            PdfString defaultAppearanceState = DefaultAppearanceState;
            if(defaultAppearanceState == null)
            {
              // Retrieving the font to define the default appearance...
              fonts::Font defaultFont = null;
              PdfName defaultFontName = null;
              {
            // Field fonts.
            FontResources normalAppearanceFonts = normalAppearance.Resources.Fonts;
            foreach(KeyValuePair<PdfName,fonts::Font> entry in normalAppearanceFonts)
            {
              if(!entry.Value.Symbolic)
              {
                defaultFont = entry.Value;
                defaultFontName = entry.Key;
                break;
              }
            }
            if(defaultFontName == null)
            {
              // Common fonts.
              FontResources formFonts = Document.Form.Resources.Fonts;
              foreach(KeyValuePair<PdfName,fonts::Font> entry in formFonts)
              {
                if(!entry.Value.Symbolic)
                {
                  defaultFont = entry.Value;
                  defaultFontName = entry.Key;
                  break;
                }
              }
              if(defaultFontName == null)
              {
                //TODO:manage name collision!
                formFonts[
                  defaultFontName = new PdfName("default")
                  ] = defaultFont = new fonts::StandardType1Font(
                    Document,
                    fonts::StandardType1Font.FamilyEnum.Helvetica,
                    false,
                    false
                    );
              }
              normalAppearanceFonts[defaultFontName] = defaultFont;
            }
              }
              bytes::Buffer buffer = new bytes::Buffer();
              new SetFont(defaultFontName, IsMultiline ? 10 : 0).WriteTo(buffer, Document);
              widget.BaseDataObject[PdfName.DA] = defaultAppearanceState = new PdfString(buffer.ToByteArray());
            }

            // Retrieving the font to use...
            ContentParser parser = new ContentParser(defaultAppearanceState.ToByteArray());
            foreach(ContentObject content in parser.ParseContentObjects())
            {
              if(content is SetFont)
              {
            SetFont setFontOperation = (SetFont)content;
            fontName = setFontOperation.Name;
            fontSize = setFontOperation.Size;
            break;
              }
            }
            normalAppearance.Resources.Fonts[fontName] = Document.Form.Resources.Fonts[fontName];
              }

              // Refreshing the field appearance...
              /*
               * TODO: resources MUST be resolved both through the apperance stream resource dictionary and
               * from the DR-entry acroform resource dictionary
               */
              PrimitiveComposer baseComposer = new PrimitiveComposer(normalAppearance);
              BlockComposer composer = new BlockComposer(baseComposer);
              ContentScanner currentLevel = composer.Scanner;
              bool textShown = false;
              while(currentLevel != null)
              {
            if(!currentLevel.MoveNext())
            {
              currentLevel = currentLevel.ParentLevel;
              continue;
            }

            ContentObject content = currentLevel.Current;
            if(content is MarkedContent)
            {
              MarkedContent markedContent = (MarkedContent)content;
              if(PdfName.Tx.Equals(((BeginMarkedContent)markedContent.Header).Tag))
              {
            // Remove old text representation!
            markedContent.Objects.Clear();
            // Add new text representation!
            baseComposer.Scanner = currentLevel.ChildLevel; // Ensures the composer places new contents within the marked content block.
            ShowText(composer, fontName, fontSize);
            textShown = true;
              }
            }
            else if(content is Text)
            {currentLevel.Remove();}
            else if(currentLevel.ChildLevel != null)
            {currentLevel = currentLevel.ChildLevel;}
              }
              if(!textShown)
              {
            baseComposer.BeginMarkedContent(PdfName.Tx);
            ShowText(composer, fontName, fontSize);
            baseComposer.End();
              }
              baseComposer.Flush();
        }
Ejemplo n.º 24
0
 /**
  * Creates a RichMediaCommand dictionary.
  * @param   command a text string specifying the script command
  * (a primitive ActionScript or JavaScript function name).
  */
 public RichMediaCommand(PdfString command) : base(PdfName.RICHMEDIACOMMAND)
 {
     Put(PdfName.C, command);
 }
Ejemplo n.º 25
0
 /**
  * Used for creating sub-TextRenderInfos for each individual character
  * @param parent the parent TextRenderInfo
  * @param string the content of a TextRenderInfo
  * @param horizontalOffset the unscaled horizontal offset of the character that this TextRenderInfo represents
  * @since 5.3.3
  */
 private TextRenderInfo(TextRenderInfo parent, PdfString @string, float horizontalOffset) {
     this.@string = @string;
     this.textToUserSpaceTransformMatrix = new Matrix(horizontalOffset, 0).Multiply(parent.textToUserSpaceTransformMatrix);
     this.gs = parent.gs;
     this.markedContentInfos = parent.markedContentInfos;
     this.fontMatrix = gs.font.GetFontMatrix();
 }
Ejemplo n.º 26
0
 /// <summary>Gets bytes of String-value without considering encoding.</summary>
 /// <param name="string">
 /// a
 /// <see cref="iText.Kernel.Pdf.PdfString"/>
 /// to get bytes from it
 /// </param>
 /// <returns>byte array</returns>
 protected internal virtual byte[] GetIsoBytes(PdfString @string)
 {
     return(ByteUtils.GetIsoBytes(@string.GetValue()));
 }
Ejemplo n.º 27
0
 public virtual iText.Kernel.Pdf.Annot.PdfRedactAnnotation SetOverlayText(PdfString text)
 {
     return((iText.Kernel.Pdf.Annot.PdfRedactAnnotation)Put(PdfName.OverlayText, text));
 }
Ejemplo n.º 28
0
 /**
  * A text string expressing the scale ratio of the drawing in the region
  * corresponding to this dictionary. Universally recognized unit
  * abbreviations should be used, either matching those of the number format
  * arrays in this dictionary or those of commonly used scale ratios.<br />
  * If the scale ratio differs in the x and y directions, both scales should
  * be specified.
  *
  * @param scaleratio
  */
 virtual public void SetScaleRatio(PdfString scaleratio)
 {
     Put(new PdfName("R"), scaleratio);
 }
Ejemplo n.º 29
0
 protected internal abstract void CheckPdfString(PdfString @string);
Ejemplo n.º 30
0
    /// <summary>
    /// Writes the specified value to the PDF stream.
    /// </summary>
    public void Write(PdfString value)
    {
      WriteSeparator(CharCat.Delimiter);
#if true
      PdfStringEncoding encoding = (PdfStringEncoding)(value.Flags & PdfStringFlags.EncodingMask);
      string pdf;
      if ((value.Flags & PdfStringFlags.HexLiteral) == 0)
        pdf = PdfEncoders.ToStringLiteral(value.Value, encoding, SecurityHandler);
      else
        pdf = PdfEncoders.ToHexStringLiteral(value.Value, encoding, SecurityHandler);
      WriteRaw(pdf);
#else
      switch (value.Flags & PdfStringFlags.EncodingMask)
      {
        case PdfStringFlags.Undefined:
        case PdfStringFlags.PDFDocEncoding:
          if ((value.Flags & PdfStringFlags.HexLiteral) == 0)
            WriteRaw(PdfEncoders.DocEncode(value.Value, false));
          else
            WriteRaw(PdfEncoders.DocEncodeHex(value.Value, false));
          break;

        case PdfStringFlags.WinAnsiEncoding:
          throw new NotImplementedException("Unexpected encoding: WinAnsiEncoding");

        case PdfStringFlags.Unicode:
          if ((value.Flags & PdfStringFlags.HexLiteral) == 0)
            WriteRaw(PdfEncoders.DocEncode(value.Value, true));
          else
            WriteRaw(PdfEncoders.DocEncodeHex(value.Value, true));
          break;

        case PdfStringFlags.StandardEncoding:
        case PdfStringFlags.MacRomanEncoding:
        case PdfStringFlags.MacExpertEncoding:
        default:
          throw new NotImplementedException("Unexpected encoding");
      }
#endif
      this.lastCat = CharCat.Delimiter;
    }
Ejemplo n.º 31
0
        public void OneFile_LinksToTheNextFile_UpdatesLink(string exeFileName)
        {
            HtmlToPdfRunner runner = new HtmlToPdfRunner(exeFileName);

            string htmlFile2Contents = @"
<html>
  <head>
  </head>
  <body>
   Page 2
  </body>
</html>";

            using (TempHtmlFile htmlFile2 = new TempHtmlFile(htmlFile2Contents))
            {
                string htmlFile1Contents = $@"
<html>
  <head>
  </head>
  <body>
   Page 1
   <br/>
   <a href=""{htmlFile2.FilePath}"">Page 2</a>
  </body>
</html>";
                using (TempHtmlFile htmlFile1 = new TempHtmlFile(htmlFile1Contents))
                {
                    using (TempPdfFile pdfFile = new TempPdfFile(this.TestContext))
                    {
                        string             commandLine = $"\"{htmlFile1.FilePath}\" \"{htmlFile2.FilePath}\" \"{pdfFile.FilePath}\"";
                        HtmlToPdfRunResult result      = runner.Run(commandLine);
                        Assert.AreEqual(0, result.ExitCode, result.Output);

                        using (PdfReader pdfReader = new PdfReader(pdfFile.FilePath))
                        {
                            using (PdfDocument pdfDocument = new PdfDocument(pdfReader))
                            {
                                Assert.AreEqual(2, pdfDocument.GetNumberOfPages());

                                // get the first page
                                PdfPage pdfPage = pdfDocument.GetPage(1);

                                // get link annotations
                                List <PdfLinkAnnotation> linkAnnotations = pdfPage.GetAnnotations().OfType <PdfLinkAnnotation>().ToList();
                                Assert.AreEqual(1, linkAnnotations.Count);

                                // get the first link annotation
                                PdfLinkAnnotation linkAnnotation = linkAnnotations.ElementAt(0);
                                Assert.IsNotNull(linkAnnotation);

                                // get action
                                PdfDictionary action = linkAnnotation.GetAction();
                                Assert.IsNotNull(action);

                                // get GoTo sub-type
                                PdfName s = action.GetAsName(PdfName.S);

                                if (exeFileName == HtmlToPdfRunner.HtmlToPdfExe)
                                {
                                    Assert.AreEqual(PdfName.GoTo, s);

                                    // get destination
                                    PdfArray             destination = action.GetAsArray(PdfName.D);
                                    PdfIndirectReference destinationPageReference = destination.GetAsDictionary(0).GetIndirectReference();
                                    PdfName   zoom       = destination.GetAsName(1);
                                    PdfNumber pageOffset = destination.GetAsNumber(2);

                                    // get expected values
                                    PdfPage              pdfPage2              = pdfDocument.GetPage(2);
                                    PdfDictionary        page2Dictionary       = pdfPage2.GetPdfObject();
                                    PdfIndirectReference expectedPageReference = page2Dictionary.GetIndirectReference();
                                    PdfName              expectedZoom          = PdfName.FitH;
                                    float expectedPageOffset = pdfPage2.GetPageSize().GetTop();

                                    // assert
                                    Assert.AreEqual(expectedPageReference, destinationPageReference);
                                    Assert.AreEqual(expectedZoom, zoom);
                                    Assert.AreEqual(expectedPageOffset, pageOffset.FloatValue());
                                }
                                else if (exeFileName == HtmlToPdfRunner.WkhtmltopdfExe)
                                {
                                    Assert.AreEqual(PdfName.URI, s);

                                    PdfString uri = action.GetAsString(PdfName.URI);
                                    Assert.AreEqual(htmlFile2.FilePath, HttpUtility.UrlDecode(uri.ToString()));
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 32
0
 /**
  * Gets the width of a PDF string in text space units
  * @param string        the string that needs measuring
  * @return  the width of a String in text space units
  */
 private float GetPdfStringWidth(PdfString @string, bool singleCharString) {
     if (singleCharString) {
         float[] widthAndWordSpacing = GetWidthAndWordSpacing(@string, singleCharString);
         return (widthAndWordSpacing[0]*gs.fontSize + gs.characterSpacing + widthAndWordSpacing[1])*gs.horizontalScaling;
     } else {
         float totalWidth = 0;
         foreach (PdfString str in SplitString(@string)) {
             totalWidth += GetPdfStringWidth(str, true);
         }
         return totalWidth;
     }
 }
Ejemplo n.º 33
0
        public virtual String GetValueAsText()
        {
            PdfString str = GetPdfObject().GetAsString(PdfName.V);

            return(str != null?str.ToUnicodeString() : null);
        }
Ejemplo n.º 34
0
 /**
  * ! .NET SPECIFIC; this method is used to avoid unecessary using of StringBuilder because it is slow in .NET !
  * Decodes a single character PdfString (which will contain glyph ids encoded in the font's encoding)
  * based on the active font, and determine the unicode equivalent
  * @param in	the String that needs to be encoded
  * @return	    the encoded String
  */
 private String DecodeSingleCharacter(PdfString @in) {
     byte[] bytes = @in.GetBytes();
     return gs.font.DecodeSingleCharacter(bytes, 0, bytes.Length);
 }
Ejemplo n.º 35
0
        public virtual String GetValueFormattedRepresentation()
        {
            PdfString f = GetPdfObject().GetAsString(PdfName.F);

            return(f != null?f.ToUnicodeString() : null);
        }
Ejemplo n.º 36
0
 /**
  * Creates a new TextRenderInfo object
  * @param string the PDF string that should be displayed
  * @param gs the graphics state (note: at this time, this is not immutable, so don't cache it)
  * @param textMatrix the text matrix at the time of the render operation
  * @param markedContentInfo the marked content sequence, if available
  */
 internal TextRenderInfo(PdfString @string, GraphicsState gs, Matrix textMatrix, ICollection markedContentInfo) {
     this.@string = @string;
     this.textToUserSpaceTransformMatrix = textMatrix.Multiply(gs.ctm);
     this.gs = gs;
     this.markedContentInfos = new List<MarkedContentInfo>();
     if (markedContentInfo.Count > 0) { // check for performance purposes, as markedContentInfo.GetEnumerator is a costly operation for some reason
         foreach (MarkedContentInfo m in markedContentInfo) {
             this.markedContentInfos.Add(m);
         }
     }
     this.fontMatrix = gs.font.GetFontMatrix();
 }
 /**
  * Decodes a PdfString (which will contain glyph ids encoded in the font's encoding)
  * based on the active font, and determine the unicode equivalent
  * @param in    the String that needs to be encoded
  * @return  the encoded String
  * @since 2.1.7
  */
 private String Decode(PdfString inp)
 {
     byte[] bytes = inp.GetBytes();
     return(Gs().font.Decode(bytes, 0, bytes.Length));
 }
Ejemplo n.º 38
0
 /**
  * Decodes a PdfString (which will contain glyph ids encoded in the font's encoding)
  * based on the active font, and determine the unicode equivalent
  * @param in    the String that needs to be encoded
  * @return  the encoded String
  * @since 2.1.7
  */
 private String Decode(PdfString inp){
     byte[] bytes = inp.GetBytes();
     return Gs().font.Decode(bytes, 0, bytes.Length);
 }
            public void Invoke(PdfContentStreamProcessor processor, PdfLiteral oper, List <PdfObject> operands)
            {
                PdfString str = (PdfString)operands[0];

                processor.DisplayPdfString(str);
            }
Ejemplo n.º 40
0
   /**
     <see cref="GetPath(PdfName)"/>
   */
   private void SetPath(
 PdfName key,
 string value
 )
   {
       BaseDictionary[key] = new PdfString(value);
   }
Ejemplo n.º 41
0
 public PdfStringDestination(PdfString pdfObject)
     : base(pdfObject)
 {
 }