示例#1
0
    /**
     * Convert the underlying Set of rich text Runs into java.text.AttributedString
     */
    public AttributedString GetAttributedString(TextRun txRun){
        String text = txRun.GetText();
        //TODO: properly process tabs
        text = text.Replace('\t', ' ');
        text = text.Replace((char)160, ' ');

        AttributedString at = new AttributedString(text);
        RichTextRun[] rt = txRun.GetRichTextRuns();
        for (int i = 0; i < rt.Length; i++) {
            int start = rt[i].GetStartIndex();
            int end = rt[i].GetEndIndex();
            if(start == end) {
                logger.log(POILogger.INFO,  "Skipping RichTextRun with zero length");
                continue;
            }

            at.AddAttribute(TextAttribute.FAMILY, rt[i].GetFontName(), start, end);
            at.AddAttribute(TextAttribute.SIZE, new Float(rt[i].GetFontSize()), start, end);
            at.AddAttribute(TextAttribute.FOREGROUND, rt[i].GetFontColor(), start, end);
            if(rt[i].IsBold()) at.AddAttribute(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD, start, end);
            if(rt[i].IsItalic()) at.AddAttribute(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE, start, end);
            if(rt[i].IsUnderlined()) {
                at.AddAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON, start, end);
                at.AddAttribute(TextAttribute.INPUT_METHOD_UNDERLINE, TextAttribute.UNDERLINE_LOW_TWO_PIXEL, start, end);
            }
            if(rt[i].IsStrikethrough()) at.AddAttribute(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON, start, end);
            int superScript = rt[i].GetSuperscript();
            if(superScript != 0) at.AddAttribute(TextAttribute.SUPERSCRIPT, superScript > 0 ? TextAttribute.SUPERSCRIPT_SUPER : TextAttribute.SUPERSCRIPT_SUB, start, end);

        }
        return at;
    }
示例#2
0
        //-------------------------------------------------------------------
        // GetTextRun
        //-------------------------------------------------------------------
        public override TextRun GetTextRun(int textSourceCharacterIndex)
        {
            Debug.Assert(Context != null, "TextFormatter host is not initialized.");
            Debug.Assert(textSourceCharacterIndex >= 0, "Character index must be non-negative.");
            TextRun run = Context.GetTextRun(textSourceCharacterIndex);

            if (run.Properties != null)
            {
                run.Properties.PixelsPerDip = PixelsPerDip;
            }

            return(run);
        }
示例#3
0
        internal static void SetRichTextFontSize(List <TextParagraph> richText, double fontSize)
        {
            TextRun       firstRun       = GetFirstRun(richText);
            TextParagraph firstParagraph = GetFirstParagraph(richText);

            if ((firstRun != null) && (fontSize > 0.0))
            {
                firstRun.FontSize = new double?(UnitHelper.PixelToPoint(fontSize));
            }
            else if ((firstParagraph != null) && (fontSize > 0.0))
            {
                firstParagraph.FontSize = new double?(UnitHelper.PixelToPoint(fontSize));
            }
        }
示例#4
0
        internal static void SetRichTextFill(List <TextParagraph> richText, Brush fillBrush)
        {
            TextRun       firstRun       = GetFirstRun(richText);
            TextParagraph firstParagraph = GetFirstParagraph(richText);

            if ((firstRun != null) && (fillBrush != null))
            {
                firstRun.FillFormat = fillBrush.ToExcelFillFormat();
            }
            else if ((firstParagraph != null) && (fillBrush != null))
            {
                firstParagraph.FillFormat = fillBrush.ToExcelFillFormat();
            }
        }
示例#5
0
        internal static void SetRichTextFontStyle(List <TextParagraph> richText, bool italics)
        {
            TextRun       firstRun       = GetFirstRun(richText);
            TextParagraph firstParagraph = GetFirstParagraph(richText);

            if ((firstRun != null) && italics)
            {
                firstRun.Italics = new bool?(italics);
            }
            else if ((firstParagraph != null) && italics)
            {
                firstParagraph.Italics = new bool?(italics);
            }
        }
示例#6
0
        private Size MeasureText(TextRun text)
        {
            if (string.IsNullOrWhiteSpace(text.Text))
            {
                return(new Size(0, 0));
            }

            // TODO: Support text.Formatting.FormattingType
            var family = FontCollection.SystemFonts.Find("Arial");
            var font   = new Font(family, (float)text.Formatting.Size, FontStyle.Regular);
            var size   = textMeasurer.MeasureText(text.Text, font, 72);

            return(new Size(size.Width, size.Height));
        }
		internal static int GetInlineObjectCount(TextRun firstRun, TextRun? lastRun)
		{
			TextRun next = firstRun.GetNext();
			int num = 0;
			while (!next.IsEnd() && (lastRun == null || next.Position < lastRun.Value.Position))
			{
				if (next.Type == TextRunType.FirstShort)
				{
					num++;
				}
				next.MoveNext();
			}
			return num;
		}
        HyperlinkInfo GetHyperlinkInfo(TextRun run)
        {
            RunIndex runIndex = run.GetRunIndex();
            Field    field    = PieceTable.FindFieldByRunIndex(runIndex);

            System.Diagnostics.Debug.Assert(field != null);
            HyperlinkInfo hyperlinkInfo = null;

            if (PieceTable.HyperlinkInfos.TryGetHyperlinkInfo(field.Index, out hyperlinkInfo))
            {
                return(hyperlinkInfo);
            }
            return(null);
        }
示例#9
0
        protected virtual Size MeasureText(TextRun text)
        {
            if (string.IsNullOrWhiteSpace(text.Text))
            {
                return(new Size(0, 0));
            }

            // TODO: Support text.Formatting.FormattingType
            var family = SystemFonts.Find("Arial");
            var font   = new Font(family, (float)text.Formatting.Size, FontStyle.Regular);
            var size   = TextMeasurer.Measure(text.Text, new RendererOptions(font, 72));

            return(new Size(size.Width, size.Height));
        }
示例#10
0
        private static bool IsListNumberOrBullet(TextRun textRun)
        {
            char wordChar = textRun.GetWordChar(0);

            switch (wordChar)
            {
            case '*':
            case '+':
                return(textRun.WordLength == 1);

            case ',':
            case '-':
            case '.':
            case '/':
            case '0':
                break;

            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                if (textRun.WordLength == 2)
                {
                    return(textRun.GetWordChar(1) == '.' || textRun.GetWordChar(1) == ')' || textRun.GetWordChar(1) == ':');
                }
                return(textRun.WordLength == 3 && char.IsDigit(textRun.GetWordChar(1)) && (textRun.GetWordChar(2) == '.' || textRun.GetWordChar(2) == ')' || textRun.GetWordChar(2) == ':'));

            default:
                switch (wordChar)
                {
                case 'a':
                case 'b':
                case 'c':
                case 'd':
                case 'e':
                case 'f':
                case 'g':
                case 'h':
                    return(textRun.WordLength == 2 && (textRun.GetWordChar(1) == '.' || textRun.GetWordChar(1) == ')'));
                }
                break;
            }
            return(false);
        }
示例#11
0
        public void Setup(int canvasW, int canvasH)
        {
            //--------------------------------------
            //TODO: review here again

            DrawingGL.Text.Utility.SetLoadFontDel(
                fontfile =>
            {
                using (Stream s = MainActivity.AssetManager.Open(fontfile))
                    using (var ms = new MemoryStream())// This is a simple hack because on Xamarin.Android, a `Stream` created by `AssetManager.Open` is not seekable.
                    {
                        s.CopyTo(ms);
                        return(new MemoryStream(ms.ToArray()));
                    }
            });

            //--------------------------------------
            simpleCanvas = new SimpleCanvas(canvasW, canvasH);
            var text = "Typography";

            //optional ....
            //var directory = AndroidOS.Environment.ExternalStorageDirectory;
            //var fullFileName = Path.Combine(directory.ToString(), "TypographyTest.txt");
            //if (File.Exists(fullFileName))
            //{
            //    text = File.ReadAllText(fullFileName);
            //}
            //--------------------------------------------------------------------------
            //we want to create a prepared visual object ***
            //textContext = new TypographyTextContext()
            //{
            //    FontFamily = "DroidSans.ttf", //corresponding to font file Assets/DroidSans.ttf
            //    FontSize = 64,//size in Points
            //    FontStretch = FontStretch.Normal,
            //    FontStyle = FontStyle.Normal,
            //    FontWeight = FontWeight.Normal,
            //    Alignment = DrawingGL.Text.TextAlignment.Leading
            //};
            //--------------------------------------------------------------------------
            //create blank text run
            textRun = new TextRun();
            TextPrinter textPrinter = simpleCanvas.TextPrinter;

            textPrinter.FontFilename     = "DroidSans.ttf"; //corresponding to font file Assets/DroidSans.ttf
            textPrinter.FontSizeInPoints = 64;
            //
            simpleCanvas.TextPrinter.GenerateGlyphRuns(textRun, text.ToCharArray(), 0, text.Length);
            //--------------------------------------------------------------------------
        }
示例#12
0
        internal static void SetRichtTextFontWeight(List <TextParagraph> richText, bool bold)
        {
            TextRun       firstRun       = GetFirstRun(richText);
            TextParagraph firstParagraph = GetFirstParagraph(richText);
            FontWeight    normal         = FontWeights.Normal;

            if (firstRun != null)
            {
                firstRun.Bold = new bool?(bold);
            }
            else if (firstParagraph != null)
            {
                firstParagraph.Bold = new bool?(bold);
            }
        }
        static void Main(string[] args)
        {
            using (Library lib = new Library())
            {
                String sOutput = "../CalRGB-out.pdf";

                if (args.Length > 0)
                {
                    sOutput = args[0];
                }

                Console.WriteLine("Writing to output " + sOutput);

                Document doc     = new Document();
                Page     page    = doc.CreatePage(Document.BeforeFirstPage, new Rect(0, 0, 5 * 72, 4 * 72));
                Content  content = page.Content;
                Font     font    = new Font("Times-Roman", FontCreateFlags.Embedded | FontCreateFlags.Subset);

                // a CalRGB color space for the CCIR XA/11-recommended D65
                // white point with 1.8 gammas and Sony Trinitron phosphor
                // chromaticities
                //
                // Plus a dummy value for testing the black point

                Double[]   whitePoint = { 0.9505, 1.0000, 1.0890 };
                Double[]   blackPoint = { 0.0, 0.0, 0.0 };
                Double[]   gamma      = { 1.8, 1.8, 1.8 };
                Double[]   matrix     = { 0.4497, 0.2446, 0.0252, 0.3163, 0.6720, 0.1412, 0.1845, 0.0833, 0.9227 };
                ColorSpace cs         = new CalRGBColorSpace(whitePoint, blackPoint, gamma, matrix);


                GraphicState gs = new GraphicState();
                gs.FillColor = new Color(cs, new Double[] { 0.3, 0.7, 0.3 });


                Matrix textMatrix = new Matrix(24, 0, 0, 24,    // Set font width and height to 24 point size
                                               1 * 72, 2 * 72); // x, y coordinate on page, 1" x 2"

                TextRun textRun = new TextRun("Hello World!", font, gs, new TextState(), textMatrix);
                Text    text    = new Text();
                text.AddRun(textRun);
                content.AddElement(text);
                page.UpdateContent();

                doc.EmbedFonts();
                doc.Save(SaveFlags.Full, sOutput);
            }
        }
        // Token: 0x06006603 RID: 26115 RVA: 0x001CABCC File Offset: 0x001C8DCC
        internal override void Arrange(VisualCollection vc, Vector lineOffset)
        {
            int num = this._dcp;
            IList <TextSpan <TextRun> > textRunSpans = this._line.GetTextRunSpans();
            double num2 = lineOffset.X + base.CalculateXOffsetShift();

            foreach (TextSpan <TextRun> textSpan in textRunSpans)
            {
                TextRun value = textSpan.Value;
                if (value is InlineObject)
                {
                    InlineObject inlineObject = value as InlineObject;
                    Visual       visual       = VisualTreeHelper.GetParent(inlineObject.Element) as Visual;
                    if (visual != null)
                    {
                        ContainerVisual containerVisual = visual as ContainerVisual;
                        Invariant.Assert(containerVisual != null, "parent should always derives from ContainerVisual");
                        containerVisual.Children.Remove(inlineObject.Element);
                    }
                    FlowDirection   flowDirection;
                    Rect            boundsFromPosition = base.GetBoundsFromPosition(num, inlineObject.Length, out flowDirection);
                    ContainerVisual containerVisual2   = new ContainerVisual();
                    if (inlineObject.Element is FrameworkElement)
                    {
                        FlowDirection    childFD = this._owner.FlowDirection;
                        DependencyObject parent  = ((FrameworkElement)inlineObject.Element).Parent;
                        if (parent != null)
                        {
                            childFD = (FlowDirection)parent.GetValue(FrameworkElement.FlowDirectionProperty);
                        }
                        PtsHelper.UpdateMirroringTransform(this._owner.FlowDirection, childFD, containerVisual2, boundsFromPosition.Width);
                    }
                    vc.Add(containerVisual2);
                    if (this._owner.UseLayoutRounding)
                    {
                        DpiScale dpi = this._owner.GetDpi();
                        containerVisual2.Offset = new Vector(UIElement.RoundLayoutValue(lineOffset.X + boundsFromPosition.Left, dpi.DpiScaleX), UIElement.RoundLayoutValue(lineOffset.Y + boundsFromPosition.Top, dpi.DpiScaleY));
                    }
                    else
                    {
                        containerVisual2.Offset = new Vector(lineOffset.X + boundsFromPosition.Left, lineOffset.Y + boundsFromPosition.Top);
                    }
                    containerVisual2.Children.Add(inlineObject.Element);
                    inlineObject.Element.Arrange(new Rect(inlineObject.Element.DesiredSize));
                }
                num += textSpan.Length;
            }
        }
示例#15
0
        internal static FontStyle GetRichTextFontStyle(List <TextParagraph> richText)
        {
            TextRun       firstRun       = GetFirstRun(richText);
            TextParagraph firstParagraph = GetFirstParagraph(richText);
            FontStyle     normal         = FontStyle.Normal;

            if (((firstRun != null) && firstRun.Italics.HasValue) && firstRun.Italics.Value)
            {
                return(FontStyle.Italic);
            }
            if (((firstParagraph != null) && firstParagraph.Italics.HasValue) && firstParagraph.Italics.Value)
            {
                normal = FontStyle.Italic;
            }
            return(normal);
        }
        protected override Size MeasureText(TextRun text)
        {
            var paint = new SKPaint
            {
                Color       = SKColors.Black,
                IsAntialias = true,
                Style       = SKPaintStyle.Fill,
                TextSize    = (float)text.Formatting.Size,
            };

            var bounds = new SKRect();

            paint.MeasureText(Encoding.UTF8.GetBytes(text.Text), ref bounds);

            return(new Size(bounds.Width, bounds.Height));
        }
示例#17
0
        internal static FontWeight GetRichTextFontWeight(List <TextParagraph> richText, FontWeight defaultFontWeight)
        {
            TextRun       firstRun       = GetFirstRun(richText);
            TextParagraph firstParagraph = GetFirstParagraph(richText);
            FontWeight    bold           = defaultFontWeight;

            if (((firstRun != null) && firstRun.Bold.HasValue) && firstRun.Bold.Value)
            {
                return(FontWeights.Bold);
            }
            if (((firstParagraph != null) && firstParagraph.Bold.HasValue) && firstParagraph.Bold.Value)
            {
                bold = FontWeights.Bold;
            }
            return(bold);
        }
示例#18
0
        internal static double?GetRichTextFontSize(List <TextParagraph> richText)
        {
            double?       nullable       = null;
            TextRun       firstRun       = GetFirstRun(richText);
            TextParagraph firstParagraph = GetFirstParagraph(richText);

            if ((firstRun != null) && firstRun.FontSize.HasValue)
            {
                return(new double?(UnitHelper.PointToPixel(firstRun.FontSize.Value)));
            }
            if ((firstParagraph != null) && firstParagraph.FontSize.HasValue)
            {
                nullable = new double?(UnitHelper.PointToPixel(firstParagraph.FontSize.Value));
            }
            return(nullable);
        }
示例#19
0
		internal static int GetFormatCrc(FormatStore formatStore, FormatNode formatNode)
		{
			int num = 0;
			TextRun textRun = formatStore.GetTextRun(formatNode.BeginTextPosition);
			if (!textRun.Equals(TextRun.Invalid))
			{
				while (!textRun.IsEnd() && textRun.Type != TextRunType.NonSpace)
				{
					textRun.MoveNext();
				}
				if (!textRun.IsEnd())
				{
					num = (int)textRun.GetWordChar(0);
				}
			}
			Dictionary<PropertyId, List<PropertyValue>> dictionary = new Dictionary<PropertyId, List<PropertyValue>>();
			do
			{
				if (formatNode.Properties != null)
				{
					foreach (Property property in formatNode.Properties)
					{
						if (!property.IsNull)
						{
							List<PropertyValue> list;
							if (!dictionary.TryGetValue(property.Id, out list))
							{
								list = new List<PropertyValue>();
								dictionary.Add(property.Id, list);
							}
							list.Add(property.Value);
						}
					}
				}
				formatNode = formatNode.Parent;
			}
			while (formatNode.Parent != FormatNode.Null);
			foreach (KeyValuePair<PropertyId, List<PropertyValue>> keyValuePair in dictionary)
			{
				int propertyCrc = BodyFragmentInfo.GetPropertyCrc(formatStore, keyValuePair.Key, keyValuePair.Value);
				if (propertyCrc != 0)
				{
					num ^= propertyCrc;
				}
			}
			return num;
		}
示例#20
0
        private static TablixRow CreateThirdTablixRow()
        {
            var textRun = new TextRun {
                Value = CreateHyperLinkExpression(), MarkupType = MarkupType.HTML
            };
            var paragraph = new Paragraph(new TextRuns(textRun))
            {
                TextAlign = TextAlign.Center
            };
            var textbox = new Textbox(paragraph)
            {
                TextboxStyle = new TextboxStyle()
            };
            var tablixCells = new TablixCells(new TablixCell(new CellContents(textbox)));

            return(new TablixRow(new Inch(0.18), tablixCells));
        }
示例#21
0
        private static TablixRow CreateFourthTablixRow()
        {
            var textRun = new TextRun {
                Value = CreateRelativeAtomicMassExpression()
            };
            var paragraph = new Paragraph(new TextRuns(textRun))
            {
                TextAlign = TextAlign.Right
            };
            var textbox = new Textbox(paragraph)
            {
                TextboxStyle = new TextboxStyle()
            };
            var tablixCells = new TablixCells(new TablixCell(new CellContents(textbox)));

            return(new TablixRow(new Inch(0.15), tablixCells));
        }
示例#22
0
        static void Main(string[] args)
        {
            using (Library lib = new Library())
            {
                String sOutput = "../Separation-out.pdf";

                if (args.Length > 0)
                {
                    sOutput = args[0];
                }

                Console.WriteLine("Writing to output " + sOutput);

                Document doc     = new Document();
                Page     page    = doc.CreatePage(Document.BeforeFirstPage, new Rect(0, 0, 5 * 72, 4 * 72));
                Content  content = page.Content;
                Font     font    = new Font("Times-Roman", FontCreateFlags.Embedded | FontCreateFlags.Subset);

                ColorSpace alternate = ColorSpace.DeviceRGB;

                Double[] domain        = { 0.0, 1.0 };
                int      nOutputs      = 3;
                Double[] range         = { 0.0, 1.0, 0.0, 1.0, 0.0, 1.0 };
                Double[] C0            = { 0.0, 0.0, 0.0 };
                Double[] C1            = { 1.0, 0.0, 0.0 };
                Function tintTransform = new ExponentialFunction(domain, nOutputs, C0, C1, 1.0);
                tintTransform.Range = range;

                ColorSpace   cs = new SeparationColorSpace("DLColor", alternate, tintTransform);
                GraphicState gs = new GraphicState();
                gs.FillColor = new Color(cs, new Double[] { 1.0 });

                Matrix textMatrix = new Matrix(24, 0, 0, 24,    // Set font width and height to 24 point size
                                               1 * 72, 2 * 72); // x, y coordinate on page, 1" x 2"

                TextRun textRun = new TextRun("Hello World!", font, gs, new TextState(), textMatrix);
                Text    text    = new Text();
                text.AddRun(textRun);
                content.AddElement(text);
                page.UpdateContent();

                doc.EmbedFonts();
                doc.Save(SaveFlags.Full, sOutput);
            }
        }
示例#23
0
        static void Main(string[] args)
        {
            using (Library lib = new Library())
            {
                String sOutput = "../Lab-out.pdf";

                if (args.Length > 0)
                {
                    sOutput = args[0];
                }

                Console.WriteLine("Writing to output " + sOutput);

                Document doc     = new Document();
                Page     page    = doc.CreatePage(Document.BeforeFirstPage, new Rect(0, 0, 5 * 72, 4 * 72));
                Content  content = page.Content;
                Font     font    = new Font("Times-Roman", FontCreateFlags.Embedded | FontCreateFlags.Subset);

                // CIE 1976 L*a*b* space with the CCIR XA/11-recommended D65
                // white point. The a* and b* components, although
                // theoretically unbounded, are defined to lie in the useful
                // range -128 to +127

                Double[]   whitePoint = { 0.9505, 1.0000, 1.0890 };
                Double[]   blackPoint = { 0.0, 0.0, 0.0 };
                Double[]   range      = { -128.0, 127.0, -128.0, 127.0 };
                ColorSpace cs         = new LabColorSpace(whitePoint, blackPoint, range);

                GraphicState gs = new GraphicState();
                gs.FillColor = new Color(cs, new Double[] { 55, -54, 55 });


                Matrix textMatrix = new Matrix(24, 0, 0, 24,    // Set font width and height to 24 point size
                                               1 * 72, 2 * 72); // x, y coordinate on page, 1" x 2"

                TextRun textRun = new TextRun("Hello World!", font, gs, new TextState(), textMatrix);
                Text    text    = new Text();
                text.AddRun(textRun);
                content.AddElement(text);
                page.UpdateContent();

                doc.EmbedFonts();
                doc.Save(SaveFlags.Full, sOutput);
            }
        }
示例#24
0
        // ------------------------------------------------------------------
        // Fetch the next run at element close edge position.
        //
        //      position - current position in the text array
        // ------------------------------------------------------------------
        private TextRun HandleElementEndEdge(StaticTextPointer position)
        {
            Debug.Assert(position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.ElementEnd, "TextPointer does not point to element end edge.");

            TextRun run = null;

            TextElement element = (TextElement)position.GetAdjacentElement(LogicalDirection.Forward);

            Debug.Assert(element != null, "Element should be here.");
            Inline inline = element as Inline;

            if (inline == null)
            {
                run = new TextHidden(_elementEdgeCharacterLength);
            }
            else
            {
                DependencyObject parent = inline.Parent;
                FlowDirection    parentFlowDirection = inline.FlowDirection;

                if (parent != null)
                {
                    parentFlowDirection = (FlowDirection)parent.GetValue(FrameworkElement.FlowDirectionProperty);
                }

                if (inline.FlowDirection != parentFlowDirection)
                {
                    run = new TextEndOfSegment(_elementEdgeCharacterLength);
                }
                else
                {
                    TextDecorationCollection textDecorations = DynamicPropertyReader.GetTextDecorations(inline);
                    if (textDecorations == null || textDecorations.Count == 0)
                    {
                        // (2) End of inline element, hide CloseEdge character and continue
                        run = new TextHidden(_elementEdgeCharacterLength);
                    }
                    else
                    {
                        run = new TextEndOfSegment(_elementEdgeCharacterLength);
                    }
                }
            }
            return(run);
        }
示例#25
0
 public override TextRun GetTextRun(int textSourceCharacterIndex)
 {
     try
     {
         foreach (VisualLineElement element in VisualLine.Elements)
         {
             if (textSourceCharacterIndex >= element.VisualColumn &&
                 textSourceCharacterIndex < element.VisualColumn + element.VisualLength)
             {
                 int     relativeOffset = textSourceCharacterIndex - element.VisualColumn;
                 TextRun run            = element.CreateTextRun(textSourceCharacterIndex, this);
                 if (run == null)
                 {
                     throw new ArgumentNullException(element.GetType().Name + ".CreateTextRun");
                 }
                 if (run.Length == 0)
                 {
                     throw new ArgumentException("The returned TextRun must not have length 0.", element.GetType().Name + ".Length");
                 }
                 if (relativeOffset + run.Length > element.VisualLength)
                 {
                     throw new ArgumentException("The returned TextRun is too long.", element.GetType().Name + ".CreateTextRun");
                 }
                 InlineObjectRun inlineRun = run as InlineObjectRun;
                 if (inlineRun != null)
                 {
                     inlineRun.VisualLine        = VisualLine;
                     VisualLine.hasInlineObjects = true;
                     TextView.AddInlineObject(inlineRun);
                 }
                 return(run);
             }
         }
         if (TextView.Options.ShowEndOfLine && textSourceCharacterIndex == VisualLine.VisualLength)
         {
             return(CreateTextRunForNewLine());
         }
         return(new TextEndOfParagraph(1));
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex.ToString());
         throw;
     }
 }
示例#26
0
        /// <summary>
        /// Converts a hybrid text to CEDICT-formatted plain text (marking up hanzi+pinyin sections).
        /// </summary>
        public static string HybridToCedict(HybridText ht)
        {
            StringBuilder sb    = new StringBuilder();
            bool          first = true;

            for (int i = 0; i != ht.RunCount; ++i)
            {
                TextRun tr = ht.GetRunAt(i);
                if (tr is TextRunLatin)
                {
                    string strRun = tr.GetPlainText();
                    if (!first && strRun != string.Empty && !char.IsPunctuation(strRun[0]))
                    {
                        sb.Append(' ');
                    }
                    sb.Append(strRun);
                }
                else
                {
                    if (!first)
                    {
                        sb.Append(' ');
                    }
                    TextRunZho trz = tr as TextRunZho;
                    if (!string.IsNullOrEmpty(trz.Simp))
                    {
                        sb.Append(trz.Simp);
                    }
                    if (trz.Trad != trz.Simp && !string.IsNullOrEmpty(trz.Trad))
                    {
                        sb.Append('|');
                        sb.Append(trz.Trad);
                    }
                    if (trz.Pinyin != null)
                    {
                        sb.Append('[');
                        sb.Append(GetPinyinCedict(trz.Pinyin));
                        sb.Append(']');
                    }
                }
                first = false;
            }
            return(sb.ToString());
        }
示例#27
0
        static void Main(string[] args)
        {
            using (Library lib = new Library())
            {
                String sOutput = "../CalGray-out.pdf";

                if (args.Length > 0)
                {
                    sOutput = args[0];
                }

                Console.WriteLine("Writing to output " + sOutput);

                Document doc     = new Document();
                Page     page    = doc.CreatePage(Document.BeforeFirstPage, new Rect(0, 0, 5 * 72, 4 * 72));
                Content  content = page.Content;
                Font     font    = new Font("Times-Roman", FontCreateFlags.Embedded | FontCreateFlags.Subset);

                // a space consisting of the Y dimension of the CIE 1931 XYZ
                // space with the CCIR XA/11-recommended D65 white point and
                // opto-electronic transfer function.

                Double[] whitePoint = { 0.9505, 1.0000, 1.0890 };
                Double[] blackPoint = { 0.0, 0.0, 0.0 };
                double   gamma      = 2.2222;

                ColorSpace   cs = new CalGrayColorSpace(whitePoint, blackPoint, gamma);
                GraphicState gs = new GraphicState();
                gs.FillColor = new Color(cs, new Double[] { 0.5 });


                Matrix textMatrix = new Matrix(24, 0, 0, 24,    // Set font width and height to 24 point size
                                               1 * 72, 2 * 72); // x, y coordinate on page, 1" x 2"

                TextRun textRun = new TextRun("Hello World!", font, gs, new TextState(), textMatrix);
                Text    text    = new Text();
                text.AddRun(textRun);
                content.AddElement(text);
                page.UpdateContent();

                doc.EmbedFonts();
                doc.Save(SaveFlags.Full, sOutput);
            }
        }
示例#28
0
        static void Main(string[] args)
        {
            using (Library lib = new Library())
            {
                String sInput  = Library.ResourceDirectory + "Sample_Input/sRGB_IEC61966-2-1_noBPC.icc";
                String sOutput = "../ICCBased-out.pdf";

                if (args.Length > 0)
                {
                    sInput = args[0];
                }
                if (args.Length > 1)
                {
                    sOutput = args[1];
                }

                Console.WriteLine("Writing to output " + sOutput);

                Document doc     = new Document();
                Page     page    = doc.CreatePage(Document.BeforeFirstPage, new Rect(0, 0, 5 * 72, 4 * 72));
                Content  content = page.Content;
                Font     font    = new Font("Times-Roman", FontCreateFlags.Embedded | FontCreateFlags.Subset);

                FileStream stream    = new FileStream(sInput, FileMode.Open);
                PDFStream  pdfStream = new PDFStream(stream, doc, null, null);

                ColorSpace   cs = new ICCBasedColorSpace(pdfStream, 3);
                GraphicState gs = new GraphicState();
                gs.FillColor = new Color(cs, new Double[] { 1.0, 0.0, 0.0 });


                Matrix textMatrix = new Matrix(24, 0, 0, 24,    // Set font width and height to 24 point size
                                               1 * 72, 2 * 72); // x, y coordinate on page, 1" x 2"

                TextRun textRun = new TextRun("Hello World!", font, gs, new TextState(), textMatrix);
                Text    text    = new Text();
                text.AddRun(textRun);
                content.AddElement(text);
                page.UpdateContent();

                doc.EmbedFonts();
                doc.Save(SaveFlags.Full, sOutput);
            }
        }
示例#29
0
        protected override void ExportTextRun(TextRun run)
        {
            string text = run.GetPlainText(PieceTable.TextBuffer);

            text = text.Replace("\v", "<br/>");

            if (!hyperlinkExporting)
            {
                var span = @"<span style=""";
                if (run.FontBold)
                {
                    span += "font-weight: bold; ";
                }
                if (run.FontItalic)
                {
                    span += "font-style: italic; ";
                }
                if (run.FontUnderlineType != UnderlineType.None)
                {
                    span += "text-decoration: underline; ";
                }
                if (run.FontStrikeoutType != StrikeoutType.None)
                {
                    span += "text-decoration: line-through; ";
                }
                if (run.ForeColorIndex != DevExpress.Office.Model.ColorModelInfoCache.EmptyColorIndex)
                {
                    span += $"color: #{ColorTranslator.ToHtml(DocumentModel.GetColor(run.ForeColorIndex))}; ";
                }
                if (run.DoubleFontSize != DocumentModel.DefaultCharacterProperties.DoubleFontSize)
                {
                    span += $"font-size: {Math.Min(run.DoubleFontSize, 39)}px; ";
                }

                span += $"\">{text}</span>";
                DocumentContentWriter.Write(span);
            }
            else
            {
                DocumentContentWriter.Write(text);
            }

            base.ExportTextRun(run);
        }
示例#30
0
        public DependencyObject Visit(TextRun run)
        {
            var result = new Run(run.Text);

            if ((run.Style & RunStyle.Bold) > 0)
            {
                result.FontWeight = FontWeight.FromOpenTypeWeight(700);
            }
            if ((run.Style & RunStyle.Italic) > 0)
            {
                result.FontStyle = FontStyles.Italic;
            }
            if ((run.Style & RunStyle.Code) > 0)
            {
                result.FontFamily = new FontFamily("Consolas");
                result.Foreground = Brushes.DarkGray;
            }
            return(result);
        }
        static void Main(string[] args)
        {
            using (Library lib = new Library())
            {
                String sOutput = "../DeviceN-out.pdf";

                if (args.Length > 0)
                {
                    sOutput = args[0];
                }

                Console.WriteLine("Writing to output " + sOutput);

                Document doc     = new Document();
                Page     page    = doc.CreatePage(Document.BeforeFirstPage, new Rect(0, 0, 5 * 72, 4 * 72));
                Content  content = page.Content;
                Font     font    = new Font("Times-Roman", FontCreateFlags.Embedded | FontCreateFlags.Subset);

                ColorSpace alternate = ColorSpace.DeviceRGB;

                Double[] domain        = { 0.0, 1.0, 0.0, 1.0 };
                Double[] range         = { 0.0, 1.0, 0.0, 1.0, 0.0, 1.0 };
                string   code          = "{ 0 exch }";
                Function tintTransform = new PostScriptCalculatorFunction(domain, range, code);

                ColorSpace   cs = new DeviceNColorSpace(new string[] { "DLRed", "DLBlue" }, alternate, tintTransform);
                GraphicState gs = new GraphicState();
                gs.FillColor = new Color(cs, new Double[] { 0.75, 0.75 });


                Matrix textMatrix = new Matrix(24, 0, 0, 24,    // Set font width and height to 24 point size
                                               1 * 72, 2 * 72); // x, y coordinate on page, 1" x 2"

                TextRun textRun = new TextRun("Hello World!", font, gs, new TextState(), textMatrix);
                Text    text    = new Text();
                text.AddRun(textRun);
                content.AddElement(text);
                page.UpdateContent();

                doc.EmbedFonts();
                doc.Save(SaveFlags.Full, sOutput);
            }
        }
示例#32
0
文件: Sheet.cs 项目: ctddjyds/npoi
    /**
     * Scans through the supplied record array, looking for
     * a TextHeaderAtom followed by one of a TextBytesAtom or
     * a TextCharsAtom. Builds up TextRuns from these
     *
     * @param records the records to build from
     * @param found   vector to add any found to
     */
    protected static void FindTextRuns(Record[] records, Vector found) {
        // Look for a TextHeaderAtom
        for (int i = 0, slwtIndex=0; i < (records.Length - 1); i++) {
            if (records[i] is TextHeaderAtom) {
                TextRun trun = null;
                TextHeaderAtom tha = (TextHeaderAtom) records[i];
                StyleTextPropAtom stpa = null;

                // Look for a subsequent StyleTextPropAtom
                if (i < (records.Length - 2)) {
                    if (records[i + 2] is StyleTextPropAtom) {
                        stpa = (StyleTextPropAtom) records[i + 2];
                    }
                }

                // See what follows the TextHeaderAtom
                if (records[i + 1] is TextCharsAtom) {
                    TextCharsAtom tca = (TextCharsAtom) records[i + 1];
                    trun = new TextRun(tha, tca, stpa);
                } else if (records[i + 1] is TextBytesAtom) {
                    TextBytesAtom tba = (TextBytesAtom) records[i + 1];
                    trun = new TextRun(tha, tba, stpa);
                } else if (records[i + 1].GetRecordType() == 4001l) {
                    // StyleTextPropAtom - Safe to ignore
                } else if (records[i + 1].GetRecordType() == 4010l) {
                    // TextSpecInfoAtom - Safe to ignore
                } else {
                    System.err.println("Found a TextHeaderAtom not followed by a TextBytesAtom or TextCharsAtom: Followed by " + records[i + 1].GetRecordType());
                }

                if (trun != null) {
                    ArrayList lst = new ArrayList();
                    for (int j = i; j < records.Length; j++) {
                        if(j > i && records[j] is TextHeaderAtom) break;
                        lst.Add(records[j]);
                    }
                    Record[] recs = new Record[lst.Count];
                    lst.ToArray(recs);
                    tRun._records = recs;
                    tRun.SetIndex(slwtIndex);

                    found.Add(tRun);
                    i++;
                } else {
                    // Not a valid one, so skip on to next and look again
                }
                slwtIndex++;
            }
        }
    }
示例#33
0
        public void TextRun_Replace()
        {
            var run = new TextRun("سلومی چو بوی خوش آشنایی");
            var newRuns = run.Replace(0, 5, "سلام").ToList();

            Assert.AreEqual(newRuns.Count, 2);

            Assert.AreEqual(newRuns[0].Text, "سلام");
            Assert.AreEqual(newRuns[0].OriginalLength, "سلومی".Length);

            Assert.AreEqual(newRuns.Text(), "سلام چو بوی خوش آشنایی");
        }
示例#34
0
			public Builder AddText(string text, params object[] objects)
			{
				Contract.Requires(text != null);
				Contract.Ensures(Contract.Result<Builder>() != null);

				if(objects != null)
				{
					text = string.Format(text, objects);
				}

				TextRun newRun = new TextRun(
					_ActiveTextRange,
					_ActiveCulture,
					_ActiveFamily,
					_ActiveStretch,
					_ActiveStyle,
					_ActiveWeight,
					_ActivePointSize,
					_ActiveHAlignment,
					_ActiveVAlignment,
					_ActiveInline,
					_ActiveFeatures);

				if(_Runs.Count > 0)
				{
					TextRun oldRun = _Runs[_Runs.Count - 1];

					if((newRun.Culture == oldRun.Culture) && (newRun.Family == oldRun.Family) &&
					   (newRun.Stretch == oldRun.Stretch) && (newRun.Style == oldRun.Style) &&
					   (newRun.Weight == oldRun.Weight) && (newRun.PointSize.Equals(oldRun.PointSize)) &&
					   (newRun.HAlignment == oldRun.HAlignment) && (newRun.VAlignment == oldRun.VAlignment) &&
					   (newRun.Inline == oldRun.Inline) && (newRun.Features == oldRun.Features))
					{
						// modify the existing run to include the appended text
						_Runs[_Runs.Count - 1] =
							new TextRun(
								new IndexedRange(oldRun.TextRange.StartIndex, oldRun.TextRange.Length + text.Length),
								oldRun.Culture,
								oldRun.Family,
								oldRun.Stretch,
								oldRun.Style,
								oldRun.Weight,
								oldRun.PointSize,
								oldRun.HAlignment,
								oldRun.VAlignment,
								oldRun.Inline,
								oldRun.Features);

						try
						{
							_Text.Append(text);
						}
						catch
						{
							// rollback the change to run on failure
							_Runs.RemoveAt(_Runs.Count - 1);

							// rethrow the exception
							throw;
						}

						return this;
					}
				}

				// append a run at the current text position
				_Runs.Add(
					new TextRun(
						new IndexedRange(_Text.Length, text.Length),
						newRun.Culture,
						newRun.Family,
						newRun.Stretch,
						newRun.Style,
						newRun.Weight,
						newRun.PointSize,
						newRun.HAlignment,
						newRun.VAlignment,
						newRun.Inline,
						newRun.Features));

				try
				{
					_Text.Append(text);
				}
				catch
				{
					// rollback the change to runs on failure
					_Runs.RemoveAt(_Runs.Count - 1);

					// rethrow the exception
					throw;
				}

				return this;
			}
示例#35
0
文件: TextBox.cs 项目: ctddjyds/npoi
 protected void SetDefaultTextProperties(TextRun _txtRun){
     SetVerticalAlignment(TextBox.AnchorTop);
     SetEscherProperty(EscherProperties.TEXT__SIZE_TEXT_TO_FIT_SHAPE, 0x20002);
 }
示例#36
0
    protected void onAddTextShape(TextShape shape) {
        TextRun run = shape.GetTextRun();

        if(_Runs == null) _Runs = new TextRun[]{Run};
        else {
            TextRun[] tmp = new TextRun[_Runs.Length + 1];
            Array.Copy(_Runs, 0, tmp, 0, _Runs.Length);
            tmp[tmp.Length-1] = Run;
            _Runs = tmp;
        }
    }
示例#37
0
    /**
     * Set default properties for the  TextRun.
     * Depending on the text and shape type the defaults are different:
     *   TextBox: align=left, valign=top
     *   AutoShape: align=center, valign=middle
     *
     */
    protected void SetDefaultTextProperties(TextRun _txtRun){

    }
示例#38
0
    public TextRun CreateTextRun(){
        _txtbox = GetEscherTextboxWrapper();
        if(_txtbox == null) _txtbox = new EscherTextboxWrapper();

        _txtrun = GetTextRun();
        if(_txtrun == null){
            TextHeaderAtom tha = new TextHeaderAtom();
            tha.SetParentRecord(_txtbox);
            _txtbox.AppendChildRecord(tha);

            TextCharsAtom tca = new TextCharsAtom();
            _txtbox.AppendChildRecord(tca);

            StyleTextPropAtom sta = new StyleTextPropAtom(0);
            _txtbox.AppendChildRecord(sta);

            _txtrun = new TextRun(tha,tca,sta);
            _txtRun._records = new Record[]{tha, tca, sta};
            _txtRun.SetText("");

            _escherContainer.AddChildRecord(_txtbox.GetEscherRecord());

            SetDefaultTextProperties(_txtRun);
        }

        return _txtRun;
    }
示例#39
0
文件: Sheet.cs 项目: ctddjyds/npoi
    /**
     * For a given PPDrawing, grab all the TextRuns
     */
    public static TextRun[] FindTextRuns(PPDrawing ppdrawing) {
        Vector RunsV = new Vector();
        EscherTextboxWrapper[] wrappers = ppdrawing.GetTextboxWrappers();
        for (int i = 0; i < wrappers.Length; i++) {
            int s1 = RunsV.Count;

            // propagate parents to parent-aware records
            RecordContainer.handleParentAwareRecords(wrappers[i]);
            FindTextRuns(wrappers[i].GetChildRecords(), RunsV);
            int s2 = RunsV.Count;
            if (s2 != s1){
                TextRun t = (TextRun) RunsV.Get(RunsV.Count-1);
                t.SetShapeId(wrappers[i].GetShapeId());
            }
        }
        TextRun[] Runs = new TextRun[RunsV.Count];
        for (int i = 0; i < Runs.Length; i++) {
            Runs[i] = (TextRun) RunsV.Get(i);
        }
        return Runs;
    }
示例#40
0
 protected void SetDefaultTextProperties(TextRun _txtRun){
     SetVerticalAlignment(TextBox.AnchorMiddle);
     SetHorizontalAlignment(TextBox.AlignCenter);
     SetWordWrap(TextBox.WrapNone);
 }
示例#41
0
    /**
     * Find hyperlinks in a text run
     *
     * @param run  <code>TextRun</code> to lookup hyperlinks in
     * @return found hyperlinks or <code>null</code> if not found
     */
    protected static Hyperlink[] Find(TextRun Run){
        ArrayList lst = new ArrayList();
        SlideShow ppt = Run.Sheet.GetSlideShow();
        //document-level Container which stores info about all links in a presentation
        ExObjList exobj = ppt.GetDocumentRecord().GetExObjList();
        if (exobj == null) {
            return null;
        }
        Record[] records = Run._records;
        if(records != null) Find(records, exobj, lst);

        Hyperlink[] links = null;
        if (lst.Count > 0){
            links = new Hyperlink[lst.Count];
            lst.ToArray(links);
        }
        return links;
    }
示例#42
0
		public TextRunComponent( TextRun textRun )
		{
			this.textRun = textRun;
		}