Exemplo n.º 1
0
        /// <summary>
        ///   Initializes a new instance of the <see cref="DifferenceQuotientDialog" /> class.
        /// </summary>
        public DifferenceQuotientDialog()
        {
            this.InitializeComponent();

            var formulaParser   = new TexFormulaParser();
            var forwardFormula  = formulaParser.Parse("v(t)=\\frac{s(t+\\Delta t)-s(t)}{\\Delta t}");
            var centralFormula  = formulaParser.Parse("v(t)=\\frac{s(t+\\Delta t)-s(t-\\Delta t )}{2\\cdot \\Delta t}");
            var backwardFormula = formulaParser.Parse("v(t)=\\frac{s(t)-s(t-\\Delta t )}{\\Delta t}");

            // Render formula to visual.
            var forwardVisual   = new DrawingVisual();
            var forwardRenderer = forwardFormula.GetRenderer(TexStyle.Display, 14d);

            using (var drawingContext = forwardVisual.RenderOpen())
            {
                forwardRenderer.Render(drawingContext, 0, 1);
            }

            this.ForwardFormulaContainerElement.Visual = forwardVisual;

            // Render formula to visual.
            var centralVisual   = new DrawingVisual();
            var centralRenderer = centralFormula.GetRenderer(TexStyle.Display, 14d);

            using (var drawingContext = centralVisual.RenderOpen())
            {
                centralRenderer.Render(drawingContext, 0, 1);
            }

            this.CentralFormulaContainerElement.Visual = centralVisual;

            // Render formula to visual.
            var backwardVisual   = new DrawingVisual();
            var backwardRenderer = backwardFormula.GetRenderer(TexStyle.Display, 14d);

            using (var drawingContext = backwardVisual.RenderOpen())
            {
                backwardRenderer.Render(drawingContext, 0, 1);
            }

            this.BackwardFormulaContainerElement.Visual = backwardVisual;

            switch (Viana.Project.ProcessingData.DifferenceQuotientType)
            {
            case DifferenceQuotientType.Forward:
                this.ForwardRadioButton.IsChecked = true;
                break;

            case DifferenceQuotientType.Backward:
                this.BackwardRadioButton.IsChecked = true;
                break;

            case DifferenceQuotientType.Central:
                this.CentralRadioButton.IsChecked = true;
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Exemplo n.º 2
0
        protected override void Write(OpenXMLRenderer renderer, MathInline obj)
        {
            var text = obj.Content.Text.Substring(obj.Content.Start, obj.Content.Length);

            if (string.IsNullOrEmpty(text))
            {
                return;
            }

            TexFormula formula = null;

            try
            {
                formula = _formulaParser.Parse(text);
            }
            catch (Exception)
            {
                return;
            }

            var mathRenderer = new MathRendering.OpenXMLWpfMathRenderer();

            var mathObj = (DocumentFormat.OpenXml.OpenXmlCompositeElement)mathRenderer.Render(formula.RootAtom);

            renderer.Push(mathObj);
            renderer.PopTo(mathObj);
        }
Exemplo n.º 3
0
        private List <List <Atom> > ReadMatrixCells(
            TexFormulaParser parser,
            TexFormula formula,
            SourceSpan source,
            ICommandEnvironment parentEnvironment)
        {
            var rows = new List <List <Atom> > {
                new List <Atom>()
            };                                                    // enter first row by default

            // Commands from the environment will add all the finished cells to the matrix body, but the last one should
            // be extracted here.
            var environment  = new MatrixInternalEnvironment(parentEnvironment, rows);
            var lastCellAtom = parser.Parse(source, formula.TextStyle, environment).RootAtom;

            if (lastCellAtom != null)
            {
                var lastRow = rows.LastOrDefault();
                if (lastRow == null)
                {
                    rows.Add(lastRow = new List <Atom>());
                }

                lastRow.Add(lastCellAtom);
            }

            MakeRectangular(rows);

            return(rows);
        }
Exemplo n.º 4
0
        private void DisplayEquation()
        {
            var parser   = new TexFormulaParser();
            var formula  = parser.Parse(eqnLaTeX);
            var pngBytes = formula.RenderToPng(15.0, 0.0, 0.0, "Times New Roman");

            pictureBoxEquation.Image = ByteToImage(pngBytes);
        }
Exemplo n.º 5
0
        public BitmapSource RenderFormula(string data)
        {
            var parser   = new TexFormulaParser();
            var formula  = parser.Parse(data);
            var renderer = formula.GetRenderer(TexStyle.Display, 15.0, "Arial");

            return(renderer.RenderToBitmap(0.0, 0.0));
        }
        private string GenerateImage(string latex, string filename)
        {
            string fileName = System.AppDomain.CurrentDomain.BaseDirectory;

            fileName += filename;
            var parser   = new TexFormulaParser();
            var formula  = parser.Parse(latex);
            var pngBytes = formula.RenderToPng(100.0, 0.0, 0.0, "Times New Roman");

            File.WriteAllBytes(fileName, pngBytes);
            return(fileName);
        }
Exemplo n.º 7
0
        private void Button01_Click(object sender, RoutedEventArgs e)
        {
            //const string latex = @"\left(x^2 + 2 \cdot x + 2\right) = 0 \frac{2+2}{2} \text{Русские ЛаТеХ}";
            const string latex = @"\frac{Wt}{m ^{\circ} C}";
            // \text{Русские ЛаТеХ}
            const string fileName = @"D:\ProjectsVS2017\WPFTests\latex_out";

            var parser  = new TexFormulaParser();
            var formula = parser.Parse(latex);
//            var pngBytes = formula.RenderToPng(20.0, 0.0, 0.0, "Arial");
            var pngBytes = formula.RenderToPng(20.0, 0.0, 0.0, "Cambria Math");

            File.WriteAllBytes(fileName, pngBytes);
        }
Exemplo n.º 8
0
        public TexFormula Formula(string input)
        {
            TexFormula texFormula = null;

            try
            {
                texFormula = formulaParser.Parse(input);
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("{0}", ex));
            }

            return(texFormula);
        }
Exemplo n.º 9
0
 private bool TryParseAndRender(string text, IRtSpanStyle style, out byte[] pngBytes, out string error)
 {
     try
     {
         var formula = parser.Parse(text);
         pngBytes = formula.RenderToPng(1.6 * style.Size, 0, 0, "Arial");
         error    = null;
         return(true);
     }
     catch (Exception ex)
     {
         pngBytes = null;
         error    = ex.Message;
         return(false);
     }
 }
        public static Image RenderLatex(string latex, int maxWidth)
        {
            var formula      = parser.Parse(latex);
            var renderer     = formula.GetRenderer(WpfMath.TexStyle.Display, 60.0, "Arial");
            var bitmapSource = renderer.RenderToBitmap(0, 0);
            var encoder      = new System.Windows.Media.Imaging.PngBitmapEncoder();

            encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bitmapSource));

            MemoryStream stream = new MemoryStream();

            encoder.Save(stream);
            var rawRes = Image.FromStream(stream);

            return(maxWidth < rawRes.Width ? resizeImage(rawRes, new Size(maxWidth, maxWidth * rawRes.Height / rawRes.Width)) : rawRes);
        }
Exemplo n.º 11
0
 private Image GetImage()
 {
     try
     {
         _textLabel.Text = null;
         TexFormulaParser parser  = new TexFormulaParser();
         TexFormula       formula = parser.Parse(Template.FullTemplate);
         Byte[]           png     = formula.RenderToPng(15.0, 0.0, 0.0, "Times New Roman");
         return(ImageUtils.FromBytes(png));
     }
     catch (Exception)
     {
         _textLabel.Text = Globals.Localization.Error;
         return(null);
     }
 }
Exemplo n.º 12
0
        private void saveButton_Click(object sender, RoutedEventArgs e)
        {
            // Choose file
            SaveFileDialog saveFileDialog = new SaveFileDialog()
            {
                Filter = "SVG Files (*.svg)|*.svg|PNG Files (*.png)|*.png"
            };
            var result = saveFileDialog.ShowDialog();

            if (result == false)
            {
                return;
            }

            // Open stream
            var filename = saveFileDialog.FileName;

            switch (saveFileDialog.FilterIndex)
            {
            case 1:
                var svgConv = new SVGConverter(formula.Formula, formula.Scale)
                {
                    SystemTextFontName = formula.SystemTextFontName
                };
                svgConv.SaveGeometry(filename);
                break;

            case 2:
                using (var stream = new FileStream(filename, FileMode.Create))
                {
                    TexFormulaParser formulaParser = new TexFormulaParser();
                    var texFormula = formulaParser.Parse(formula.Formula);
                    var renderer   = texFormula.GetRenderer(TexStyle.Display, formula.Scale, formula.SystemTextFontName);

                    var bitmap  = renderer.RenderToBitmap(0, 0);
                    var encoder = new PngBitmapEncoder
                    {
                        Frames = { BitmapFrame.Create(bitmap) }
                    };
                    encoder.Save(stream);
                }
                break;

            default:
                return;
            }
        }
Exemplo n.º 13
0
        private static (string, byte[]) renderLatex(string latex, bool onlyReturnDpath = true)
        {
            var parser      = new TexFormulaParser();
            var formula     = parser.Parse(latex);
            var renderer    = formula.GetRenderer(TexStyle.Display, 20, "Arial");
            var pngBytes    = formula.RenderToPng(20.0, 0.0, 0.0, "Arial");
            var geometry    = renderer.RenderToGeometry(0, 0);
            var converter   = new SVGConverter();
            var svgPathText = converter.ConvertGeometry(geometry);

            if (!onlyReturnDpath)
            {
                return(AddSVGHeader(svgPathText), pngBytes);
            }
            var tmp1 = svgPathText.Split(new string[] { "d=\"" }, StringSplitOptions.None)[1];
            var tmp2 = tmp1.Split(new string[] { "\"" }, StringSplitOptions.None)[0];

            return(tmp2, pngBytes);
        }
Exemplo n.º 14
0
        private void LaTeX_to_File(string latex, string fileName)
        {
            var parser   = new TexFormulaParser();
            var formula  = parser.Parse(latex);
            var renderer = formula.GetRenderer(TexStyle.Display, 25.0, "Cambria Math"); // Math
            //var renderer = formula.GetRenderer(TexStyle.Display, 25.0, "Arial"); // Math
            var bitmapSource = renderer.RenderToBitmap(0.0, 0.0);
            //Console.WriteLine($"Image width: {bitmapSource.Width}");
            //Console.WriteLine($"Image height: {bitmapSource.Height}");

            var encoder = new PngBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
            using (var target = new FileStream(fileName, FileMode.Create))
            {
                encoder.Save(target);
                //Console.WriteLine($"File saved to {fileName}");
            }
        }
Exemplo n.º 15
0
        private static object CoerceFormula(DependencyObject d, object baseValue)
        {
            var control = (FormulaControl)d;
            var formula = (string)baseValue;

            try
            {
                control.HasError = false;
                control.Errors.Clear();
                control.texFormula = formulaParser.Parse(formula);
                return(baseValue);
            }
            catch (TexParseException e)
            {
                control.Errors.Add(e);
                control.HasError   = true;
                control.texFormula = null;
                return("");
            }
        }
Exemplo n.º 16
0
            internal static Bitmap TexPrinter(string latex, double scale)
            {
                try
                {
                    if (latex == "")
                    {
                        return(null);
                    }
                    while (latex.EndsWith(" ") || latex.EndsWith(" "))
                    {
                        latex = latex.Remove(latex.Length - 1, 1);
                    }
                    Bitmap bitmap = null;

                    var parser  = new TexFormulaParser();
                    var formula = parser.Parse(latex);
                    formula.TextStyle = "{StaticResource ClearTypeFormula}";
                    var renderer = formula.GetRenderer(TexStyle.Display, scale, "Arial");
                    if (renderer.RenderSize.Width == 0 || renderer.RenderSize.Height == 0)
                    {
                        return(bitmap);
                    }
                    var bitmapsourse = renderer.RenderToBitmap(0, 0);
                    var encoder      = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(bitmapsourse));
                    using (var ms = new MemoryStream())
                    {
                        encoder.Save(ms);
                        ms.Seek(0, SeekOrigin.Begin);
                        using (var temp = new Bitmap(ms))
                        {
                            bitmap = new Bitmap(temp);
                        }
                    }
                    return(bitmap);
                }
                catch (Exception e) when(e is TexParseException || e is TexCharacterMappingNotFoundException)
                {
                    return(Graphicer("!!TexError!!"));
                }
            }
Exemplo n.º 17
0
        protected override void Write([NotNull] WpfRenderer renderer, [NotNull] MathInline obj)
        {
            var text = obj.Content.Text.Substring(obj.Content.Start, obj.Content.Length);

            TexFormula formula = null;

            try
            {
                formula = formulaParser.Parse(text);
            }
            catch (Exception)
            {
                renderer.WriteInline(new Run("[!!FORMULA PARSE ERROR!!]")
                {
                    Tag = obj
                });
                return;
            }

            var fontSize        = renderer.CurrentFontSize();
            var formulaRenderer = formula.GetRenderer(TexStyle.Display, fontSize, "Arial");
            var geo             = formulaRenderer.RenderToGeometry(0, 0);
            var geoD            = new System.Windows.Media.GeometryDrawing(Brushes.Black, null, geo);
            var di      = new DrawingImage(geoD);
            var uiImage = new System.Windows.Controls.Image()
            {
                Source = di
            };

            uiImage.Height = formulaRenderer.RenderSize.Height;                                                                         // size image to match rendersize -> get a zoom of 100%
            uiImage.Margin = new System.Windows.Thickness(0, 0, 0, -formulaRenderer.RenderSize.Height * formulaRenderer.RelativeDepth); // Move image so that baseline matches that of text
            var uiInline = new System.Windows.Documents.InlineUIContainer()
            {
                Child             = uiImage,
                Background        = Brushes.Yellow,
                BaselineAlignment = System.Windows.BaselineAlignment.Baseline,
                Tag = obj,
            };

            renderer.WriteInline(uiInline);
        }
Exemplo n.º 18
0
        public void SaveGeometry(string filename)
        {
            TexFormulaParser formulaParser = new TexFormulaParser();

            if (filename == null)
            {
                return;
            }

            // Create formula object from input text.
            TexFormula formula = null;

            try
            {
                formula = formulaParser.Parse(Formula);
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred while parsing the given input:" + Environment.NewLine +
                                Environment.NewLine + ex.Message, "WPF-Math Example", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            // Create formula object from input text.

            if (formula == null)
            {
                return;
            }
            var renderer = formula.GetRenderer(TexStyle.Display, Scale, SystemTextFontName);

            using (var fs = new FileStream(filename, FileMode.Create, FileAccess.Write))
            {
                var geometry = renderer.RenderToGeometry(0, 0);

                var svgPathText = ConvertGeometry(geometry);
                var svgText     = AddSVGHeader(svgPathText);
                using (var writer = new StreamWriter(fs))
                    writer.WriteLine(svgText);
            }
        }
Exemplo n.º 19
0
        public MainWindow()
        {
            InitializeComponent();
            var a = Expr.Variable("a");
            var b = Expr.Variable("b");

            var diff = a.Differentiate(a);

            // string latex = Expr.Parse("a_1_2_3^a^3^b/b_1^3").ToLaTeX();
            var latex = Diff(a, a) + " = " + diff.ToLaTeX();


            string fileName = @"formula.png";


            var parser  = new TexFormulaParser();
            var formula = parser.Parse(latex);
            //var renderer = formula.GetRenderer(TexStyle.Display, 20.0, "Arial");
            //var bitmapSource = renderer.RenderToGeometry(0.0, 0.0);
            var pngBytes = formula.RenderToPng(20.0, 0.0, 0.0, "Arial");

            File.WriteAllBytes(fileName, pngBytes);
        }
Exemplo n.º 20
0
            public override void Parse(SourceSpan source, XElement element)
            {
                var name = element.AttributeValue("name");
                var args = element.Elements("Argument");

                var argTypes  = GetArgumentTypes(args);
                var argValues = GetArgumentValues(this.TempFormulas, args);

                Debug.Assert(argValues.Length == 1 || argValues.Length == 0);
                TexFormula formula = null;

                if (argValues.Length == 1)
                {
                    var parser = new TexFormulaParser();
                    formula = parser.Parse((string)argValues[0]);
                }
                else
                {
                    formula = new TexFormula();
                }

                this.TempFormulas.Add(name, formula);
            }
Exemplo n.º 21
0
        protected override void Write(OpenXMLRenderer renderer, MathBlock obj)
        {
            string text = string.Empty; // obj.Content.Text.Substring(obj.Content.Start, obj.Content.Length);

            for (int i = 0; i < obj.Lines.Count; ++i)
            {
                var l = obj.Lines.Lines[i];
                text += l.Slice.Text.Substring(l.Slice.Start, l.Slice.Length);
            }

            if (string.IsNullOrEmpty(text))
            {
                return;
            }

            TexFormula formula = null;

            try
            {
                formula = _formulaParser.Parse(text);
            }
            catch (Exception)
            {
                return;
            }

            var mathRenderer = new MathRendering.OpenXMLWpfMathRenderer();

            var mathObj = (DocumentFormat.OpenXml.OpenXmlCompositeElement)mathRenderer.Render(formula.RootAtom);

            var wordParagraph = renderer.PushNewParagraph(); // this is a Word paragraph

            renderer.Push(new Paragraph());                  // Attention this is a __Math__ paragraph!
            renderer.Push(mathObj);
            renderer.PopTo(wordParagraph);
        }
Exemplo n.º 22
0
        private void Mat_Text_KeyUp(object sender, KeyEventArgs e)
        {
            Res.Source = null;
            int N = 1;

            left_LaTeX = "";
            try
            {
                var lines = System.Text.RegularExpressions.Regex.Split(Mat_Text.Text.Trim(), @"\s+");
                numList.Clear();
                foreach (var it in lines)
                {
                    RationalNumber a;
                    if (it.Contains('/'))
                    {
                        var rat = it.Split('/');
                        a = new RationalNumber(Convert.ToInt32(rat[0]), Convert.ToInt32(rat[1]));
                    }
                    else
                    {
                        a = new RationalNumber(Convert.ToInt32(it));
                    }
                    numList.Add(a);
                }

                while (numList.Count >= (N + 1) * (N + 1))
                {
                    N += 1;
                }
                if (numList.Count == N * N)
                {
                    left_LaTeX += @"\pmatrix{";
                    int idx = 0;
                    foreach (var it in numList)
                    {
                        if (idx > 0)
                        {
                            if (idx % N == 0)
                            {
                                left_LaTeX += @"\\";
                            }
                            else
                            {
                                left_LaTeX += "&";
                            }
                        }
                        left_LaTeX += it.ToLaTeX();
                        idx++;
                    }
                    left_LaTeX += "}";

                    var          formula  = parser.Parse(left_LaTeX + "X=" + right_LaTeX);
                    var          pngBytes = formula.RenderToPng(20.0, 0.0, 0.0, "Arial");
                    MemoryStream ms       = new MemoryStream(pngBytes, true);

                    BitmapImage p1 = new BitmapImage();
                    p1.BeginInit();
                    p1.StreamSource = ms;
                    p1.EndInit();
                    imgSrc.Source = p1;
                }
            }
            catch
            {
                ;
            }
        }
        /// <inheritdoc/>
        public (Stream bitmapStream, string placement, int yoffset, int width96thInch, int height96thInch) Parse(string text, string fontFamily, double fontSize, double dpiResolution, bool isIntendedForHelp1File)
        {
            TexFormula formula = null;

            try
            {
                formula = _formulaParser.Parse(text);
            }
            catch (Exception)
            {
                return(null, null, 0, 0, 0);
            }

            double cyAscent;
            double cyDescent;
            double cyMiddle;
            {
                var gdiFont      = new System.Drawing.Font(fontFamily, (float)fontSize, System.Drawing.FontStyle.Regular);
                int iCellSpace   = gdiFont.FontFamily.GetLineSpacing(gdiFont.Style);
                int iEmHeight    = gdiFont.FontFamily.GetEmHeight(gdiFont.Style);
                int iCellAscent  = gdiFont.FontFamily.GetCellAscent(gdiFont.Style);
                int iCellDescent = gdiFont.FontFamily.GetCellDescent(gdiFont.Style);
                cyAscent  = fontSize * iCellAscent / iEmHeight;
                cyDescent = fontSize * iCellDescent / iEmHeight;
                cyMiddle  = cyAscent / 3; // is only a first guess, details coming from the Wpf font
                gdiFont.Dispose();
                var ff = new FontFamily(fontFamily);
                var tf = new Typeface(ff, System.Windows.FontStyles.Normal, System.Windows.FontWeights.Normal, System.Windows.FontStretches.Normal);
                if (tf.TryGetGlyphTypeface(out var gtf))
                {
                    cyMiddle = Math.Floor(fontSize * gtf.Height * gtf.StrikethroughPosition);
                }
            }

            var formulaRenderer = formula.GetRenderer(TexStyle.Display, fontSize, fontFamily);
            // the placement of the image depends on the depth value
            var absoluteDepth  = formulaRenderer.RenderSize.Height * formulaRenderer.RelativeDepth;
            var absoluteAscent = formulaRenderer.RenderSize.Height * (1 - formulaRenderer.RelativeDepth);

            double yoffset = 0;

            BitmapSource bmp;
            int          width96thInch, height96thInch;
            string       alignment;


            if (isIntendedForHelp1File)
            {
                // dictionary that holds the number of additional pixels neccessary to exactly align the formula, and the value is the alignment
                var sort = new SortedDictionary <double, (double, string)>();

                if (formulaRenderer.RelativeDepth < (1 / 16.0)) // if the formulas baseline is almost at the bottom of the image
                {
                    sort.Add(0, (0.0, "baseline"));             // then we can use baseline as vertical alight
                }
                if (absoluteAscent <= cyAscent)                 // if our formula is higher than the top of the text
                {
                    yoffset = cyAscent - absoluteAscent;
                    sort.Add(Math.Abs(yoffset), (yoffset, "texttop")); // then we can use texttop alignment, and we shift the formula downwards (positive offset)
                }
                if (absoluteDepth <= cyDescent)                        // then we can use bottom alignment, and we shift the formula upwards (negative offset)
                {
                    yoffset = absoluteDepth - cyDescent;
                    sort.Add(Math.Abs(yoffset), (yoffset, "bottom"));
                }

                {
                    // Alignment: middle
                    // Note that this is a moving target: we must change the vertical size of the image, but by that
                    // we change the middle of the image, which changes again the offset...
                    if (isIntendedForHelp1File)
                    {
                        yoffset = absoluteDepth - absoluteAscent; // in help1 file, the baseline of text is aligned with the middle of the image
                    }
                    else
                    {
                        yoffset = 2 * cyMiddle + absoluteDepth - absoluteAscent; // if yoffset is negative, then pad at the bottom, else pad at the top
                    }
                    sort.Add(Math.Abs(yoffset), (yoffset, "middle"));
                }

                var firstEntry = sort.First();
                (bmp, width96thInch, height96thInch) = RenderToBitmap(formulaRenderer, 0, firstEntry.Value.Item1, dpiResolution);
                alignment = firstEntry.Value.Item2;
                yoffset   = 0; // 0 as return value
            }
            else // MAML is intended for HTML help (so we can use HTML5 alignment with pixel accuracy        )
            {
                alignment = "baseline";
                var yshift = Math.Ceiling(absoluteAscent) - absoluteAscent; // we shift the formula downwards, so that the new absoluteAscent is Math.Ceiling(absoluteAscent)
                // by providing a positive offset in arg2, the image is lowered compared to the baseline
                (bmp, width96thInch, height96thInch) = RenderToBitmap(formulaRenderer, 0, yshift, dpiResolution);
                yoffset = Math.Ceiling(absoluteAscent) - height96thInch; // number of pixels from image bottom to baseline (negative sign)
            }

            var           fileStream = new MemoryStream();
            BitmapEncoder encoder    = new PngBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(bmp));
            encoder.Save(fileStream);
            fileStream.Seek(0, SeekOrigin.Begin);

            return(fileStream, alignment, (int)Math.Round(yoffset), width96thInch, height96thInch);
        }
Exemplo n.º 24
0
        protected IRichEditDocumentServer AddLatex(ArgumentCollection arguments)
        {
            if (arguments.Count <= 0)
            {
                throw new Exception("'DOCVARIABLE LATEX' requires LaTeX as first argument.");
            }

            var latex = arguments[0].Value;

            float?scale = null, scaleX = null, scaleY = null;
            float dpi = 300, fontSize = 20;

            if (arguments.Count > 1)
            {
                var properties = Utils.SplitNameValueString(arguments[1].Value, ';');

                foreach (var prop in properties)
                {
                    if (string.IsNullOrWhiteSpace(prop.Key))
                    {
                        continue;
                    }

                    switch (prop.Key.ToLower())
                    {
                    case "dpi":
                        dpi = float.Parse(prop.Value, CultureInfo.InvariantCulture);
                        break;

                    case "scale":
                        scale = float.Parse(prop.Value, CultureInfo.InvariantCulture);
                        break;

                    case "scalex":
                        scaleX = float.Parse(prop.Value, CultureInfo.InvariantCulture);
                        break;

                    case "scaley":
                        scaleY = float.Parse(prop.Value, CultureInfo.InvariantCulture);
                        break;

                    case "fontsize":
                        fontSize = float.Parse(prop.Value, CultureInfo.InvariantCulture);
                        break;
                    }
                }
            }

            var parser  = new TexFormulaParser();
            var formula = parser.Parse(latex);

            var renderer = formula.GetRenderer(TexStyle.Text, fontSize, "Tahoma");

            var geometry    = renderer.RenderToGeometry(0, 0);
            var converter   = new SVGConverter();
            var svgPathText = converter.ConvertGeometry(geometry);
            var svgText     = AddSVGHeader(svgPathText);

            var docSVG = new XmlDocument();

            docSVG.LoadXml(svgText);

            var image = PaintSVG(docSVG, Size.Empty, dpi);

            var server   = new RichEditDocumentServer();
            var document = server.Document;
            var docImage = document.Images.Append(image);

            if (scale.HasValue)
            {
                docImage.ScaleX = docImage.ScaleY = scale.Value;
            }
            else
            {
                if (scaleX.HasValue)
                {
                    docImage.ScaleX = scaleX.Value;
                }
                if (scaleY.HasValue)
                {
                    docImage.ScaleY = scaleY.Value;
                }
            }

            return(server);
Exemplo n.º 25
0
        protected override void Write([NotNull] WpfRenderer renderer, [NotNull] MathBlock obj)
        {
            string text = string.Empty; // obj.Content.Text.Substring(obj.Content.Start, obj.Content.Length);

            for (int i = 0; i < obj.Lines.Count; ++i)
            {
                var l = obj.Lines.Lines[i];
                text += l.Slice.Text.Substring(l.Slice.Start, l.Slice.Length);
            }

            if (string.IsNullOrEmpty(text))
            {
                return;
            }

            TexFormula formula = null;

            try
            {
                formula = formulaParser.Parse(text);
            }
            catch (Exception)
            {
                var paragraph = new Paragraph()
                {
                    Tag = obj
                };
                renderer.Push(paragraph);
                renderer.WriteInline(new Run("[!!FORMULA PARSE ERROR!!]")
                {
                    Tag = obj
                });
                renderer.Pop();
                return;
            }

            var fontSize = renderer.CurrentFontSize();

            if (fontSize <= 0)
            {
                throw new InvalidProgramException();
            }

            var formulaRenderer = formula.GetRenderer(TexStyle.Display, fontSize, "Arial");
            var geo             = formulaRenderer.RenderToGeometry(0, 0);
            var geoD            = new System.Windows.Media.GeometryDrawing(Brushes.Black, null, geo);
            var di      = new DrawingImage(geoD);
            var uiImage = new System.Windows.Controls.Image()
            {
                Source = di
            };

            uiImage.Height = formulaRenderer.RenderSize.Height; // size image to match rendersize -> get a zoom of 100%
            // uiImage.Margin = new System.Windows.Thickness(0, 0, 0, -formulaRenderer.RenderSize.Height * formulaRenderer.RelativeDepth); // Move image so that baseline matches that of text
            var uiBlock = new System.Windows.Documents.BlockUIContainer()
            {
                Child = uiImage,
                Tag   = obj,
            };

            renderer.WriteBlock(uiBlock);
        }
Exemplo n.º 26
0
        private static Table genFormulaeTable(List <Formula> formulae, MainDocumentPart mainPart)
        {
            Table tableOfInputs = new Table();
            var   tableGrid     = new TableGrid();

            tableGrid.AppendChild(new GridColumn());
            tableGrid.AppendChild(new GridColumn());
            tableGrid.AppendChild(new GridColumn());
            tableOfInputs.AppendChild(tableGrid);
            var tableProps = new TableProperties();

            tableProps.AppendChild(new TableLayout()
            {
                Type = TableLayoutValues.Fixed
            });
            tableProps.AppendChild(new TableWidth()
            {
                Width = "9000", Type = TableWidthUnitValues.Dxa
            });
            tableProps.AppendChild(new TableBorders()
            {
                InsideHorizontalBorder = new InsideHorizontalBorder()
                {
                    Color = "c0c0c0", Size = 4, Val = BorderValues.Single
                }
            });
            tableProps.AppendChild(new TableBorders()
            {
                BottomBorder = new BottomBorder()
                {
                    Color = "c0c0c0", Size = 4, Val = BorderValues.Single
                }
            });
            tableProps.AppendChild(new TableBorders()
            {
                TopBorder = new TopBorder()
                {
                    Color = "c0c0c0", Size = 4, Val = BorderValues.Single
                }
            });
            //tableProps.AppendChild(new TableBorders() { LeftBorder = new LeftBorder() { Color = "c0c0c0", Size = 4, Val = BorderValues.Single } });
            //tableProps.AppendChild(new TableBorders() { InsideVerticalBorder = new InsideVerticalBorder() { Color = "c0c0c0", Size = 4, Val = BorderValues.Single } });
            //tableProps.AppendChild(new TableBorders() { RightBorder = new RightBorder() { Color = "c0c0c0", Size = 4, Val = BorderValues.Single } });
            tableOfInputs.AppendChild(tableProps);

            foreach (var item in formulae)
            {
                TableRow row  = new TableRow();
                var      para = new Paragraph();
                para.AppendChild((new Run(new Text(item.Ref))));
                TableCell cell1 = new TableCell();
                cell1.Append(para);
                cell1.Append(new TableCellProperties(new TableCellWidth()
                {
                    Type = TableWidthUnitValues.Dxa, Width = "1200"
                }));
                TableCell cell2 = new TableCell();
                cell2.Append(new TableCellProperties(new TableCellWidth()
                {
                    Type = TableWidthUnitValues.Dxa, Width = "6100"
                }));
                cell2.AppendChild(new Paragraph(new Run(new Text(item.Narrative))));
                //foreach (var formula in item.Expression)
                //{
                //    var mathPara = new Paragraph();
                //    var myMath = new M.OfficeMath(new M.Run(new M.Text(formula + Environment.NewLine) { Space = SpaceProcessingModeValues.Preserve }));
                //    mathPara.AppendChild(myMath);
                //    mathPara.AppendChild(new Run(new Text(" ") { Space = SpaceProcessingModeValues.Preserve }));
                //    cell2.AppendChild(mathPara);
                //}
                foreach (var formula in item.Expression)
                {
                    if (formula != "")
                    {
                        TexFormula formulaToParse = new TexFormula();
                        try
                        {
                            var parser = new TexFormulaParser();
                            formulaToParse = parser.Parse(formula);
                        }
                        catch (Exception)
                        {
                            var parser = new TexFormulaParser();
                            formulaToParse = parser.Parse("Error in LaTeX string...");
                        }
                        var test = formulaToParse.GetRenderer(TexStyle.Script, 100, "Franklin Gothic Book");
                        if (test.RenderSize.Width > 0 && test.RenderSize.Height > 0)
                        {
                            var       formulaImage = formulaToParse.RenderToPng(100, 0, 0, "Franklin Gothic Book");
                            ImagePart imagePart    = mainPart.AddImagePart(ImagePartType.Png);
                            using (var stream = new MemoryStream(formulaImage))
                            {
                                imagePart.FeedData(stream);
                                var img = new BitmapImage();
                                img.BeginInit();
                                img.StreamSource = stream;
                                img.CacheOption  = BitmapCacheOption.OnLoad;
                                img.EndInit();
                                img.Freeze();
                                var paraImage = AddImageToBody(mainPart.GetIdOfPart(imagePart), img.Width * 2.54 / 600, img.Height * 2.54 / 600);
                                cell2.AppendChild(new Paragraph(new Run(paraImage)));
                            }
                        }

                        GC.WaitForPendingFinalizers();
                    }
                    //var myMath = new M.OfficeMath(new M.Run(new M.Text(formula + Environment.NewLine) { Space = SpaceProcessingModeValues.Preserve }));
                    //mathPara.AppendChild(myMath);
                    //mathPara.AppendChild(new Run(new Text(" ") { Space = SpaceProcessingModeValues.Preserve }));
                    //cell2.AppendChild(mathPara);
                }

                if (item.Image != null)
                {
                    ImagePart        imagePart = mainPart.AddImagePart(ImagePartType.Png);
                    var              tempFile  = Path.GetTempFileName();
                    PngBitmapEncoder png       = new PngBitmapEncoder();
                    //CHANGEBITMAP
                    //png.Frames.Add(BitmapFrame.Create(item.Image));
                    var width  = Math.Min(10d, item.Image.Width * 2.54 / 96);
                    var height = ((double)item.Image.Height / (double)item.Image.Width) * width;
                    using (SkiaSharp.SKWStream stm = new SkiaSharp.SKFileWStream(tempFile))
                    {
                        item.Image.Encode(stm, SkiaSharp.SKEncodedImageFormat.Png, 0);
                    }
                    using (FileStream stream = new FileStream(tempFile, FileMode.Open))
                    {
                        imagePart.FeedData(stream);
                    }
                    var paraImage = AddImageToBody(mainPart.GetIdOfPart(imagePart), width, height);
                    cell2.AppendChild(new Paragraph(new Run(paraImage)));
                }

                TableCell cell3 = new TableCell();
                cell3.Append(new Paragraph(new Run(new Text(item.Conclusion))));
                cell3.Append(new TableCellProperties(new TableCellWidth()
                {
                    Type = TableWidthUnitValues.Dxa, Width = "1700"
                }));

                row.Append(cell1, cell2, cell3);
                tableOfInputs.AppendChild(row);
            }
            return(tableOfInputs);
        }
Exemplo n.º 27
0
        private static Table genTable(List <CalcCore.CalcValueBase> calcVals, MainDocumentPart mainPart)
        {
            Table tableOfInputs = new Table();
            var   tableGrid     = new TableGrid();

            tableGrid.AppendChild(new GridColumn());
            tableGrid.AppendChild(new GridColumn());
            tableGrid.AppendChild(new GridColumn());
            tableOfInputs.AppendChild(tableGrid);
            var tableProps = new TableProperties();

            tableProps.AppendChild(new TableLayout()
            {
                Type = TableLayoutValues.Fixed
            });
            tableProps.AppendChild(new TableWidth()
            {
                Width = "9000", Type = TableWidthUnitValues.Dxa
            });
            tableProps.AppendChild(new TableBorders()
            {
                InsideHorizontalBorder = new InsideHorizontalBorder()
                {
                    Color = "c0c0c0", Size = 4, Val = BorderValues.Single
                }
            });
            tableProps.AppendChild(new TableBorders()
            {
                BottomBorder = new BottomBorder()
                {
                    Color = "c0c0c0", Size = 4, Val = BorderValues.Single
                }
            });
            tableProps.AppendChild(new TableBorders()
            {
                TopBorder = new TopBorder()
                {
                    Color = "c0c0c0", Size = 4, Val = BorderValues.Single
                }
            });
            //tableProps.AppendChild(new TableBorders() { LeftBorder = new LeftBorder() { Color = "c0c0c0", Size = 4, Val = BorderValues.Single } });
            //tableProps.AppendChild(new TableBorders() { InsideVerticalBorder = new InsideVerticalBorder() { Color = "c0c0c0", Size = 4, Val = BorderValues.Single } });
            //tableProps.AppendChild(new TableBorders() { RightBorder = new RightBorder() { Color = "c0c0c0", Size = 4, Val = BorderValues.Single } });

            tableOfInputs.AppendChild(tableProps);

            foreach (var item in calcVals)
            {
                TableRow  row   = new TableRow();
                var       para1 = new Paragraph();
                TableCell cell1 = new TableCell();

                // insert symbol as image
                var parser = new TexFormulaParser();
                if (item.Symbol != "")
                {
                    TexFormula formulaToParse = new TexFormula();
                    try
                    {
                        parser         = new TexFormulaParser();
                        formulaToParse = parser.Parse(item.Symbol);
                    }
                    catch (Exception)
                    {
                        parser         = new TexFormulaParser();
                        formulaToParse = parser.Parse("Error in LaTeX string...");
                    }
                    var       formulaImage = formulaToParse.RenderToPng(100, 0, 0, "Franklin Gothic Book");
                    ImagePart imagePart    = mainPart.AddImagePart(ImagePartType.Png);
                    using (var stream = new MemoryStream(formulaImage))
                    {
                        imagePart.FeedData(stream);
                        var img = new BitmapImage();
                        img.BeginInit();
                        img.StreamSource = stream;
                        img.CacheOption  = BitmapCacheOption.OnLoad;
                        img.EndInit();
                        img.Freeze();
                        var paraImage = AddImageToBody(mainPart.GetIdOfPart(imagePart), img.Width * 2.54 / 600, img.Height * 2.54 / 600);
                        para1.AppendChild(new Run(paraImage));
                    }
                }
                else
                {
                    para1.AppendChild(new Run(new Text(" ")));
                }


                //var myMath = new M.OfficeMath(new M.Run(new M.Text(item.Symbol) { Space = SpaceProcessingModeValues.Preserve }));
                //para1.AppendChild(myMath);
                //para1.AppendChild(new Run(new Text(" ") { Space = SpaceProcessingModeValues.Preserve }));

                cell1.Append(para1);
                cell1.Append(new TableCellProperties(new TableCellWidth()
                {
                    Type = TableWidthUnitValues.Dxa, Width = "1200"
                }));
                var       para2 = new Paragraph(new Run(new Text(item.Name)));
                TableCell cell2 = new TableCell();
                cell2.AppendChild(para2);
                cell2.Append(new TableCellProperties(new TableCellWidth()
                {
                    Type = TableWidthUnitValues.Dxa, Width = "6100"
                }));
                var para3 = new Paragraph();
                if (item.Type == CalcValueType.DOUBLE)
                {
                    // insert symbol as image
                    parser = new TexFormulaParser();
                    string toRender = item.ValueAsString + item.Unit;
                    if (toRender != "")
                    {
                        TexFormula formulaToParse = new TexFormula();
                        try
                        {
                            parser         = new TexFormulaParser();
                            formulaToParse = parser.Parse(toRender);
                        }
                        catch (Exception)
                        {
                            parser         = new TexFormulaParser();
                            formulaToParse = parser.Parse("Error in LaTeX string...");
                        }
                        var       formulaImage = formulaToParse.RenderToPng(100, 0, 0, "Franklin Gothic Book");
                        ImagePart imagePart    = mainPart.AddImagePart(ImagePartType.Png);
                        using (var stream = new MemoryStream(formulaImage))
                        {
                            imagePart.FeedData(stream);
                            var img = new BitmapImage();
                            img.BeginInit();
                            img.StreamSource = stream;
                            img.CacheOption  = BitmapCacheOption.OnLoad;
                            img.EndInit();
                            img.Freeze();
                            var paraImage = AddImageToBody(mainPart.GetIdOfPart(imagePart), img.Width * 2.54 / 600, img.Height * 2.54 / 600);
                            para3.AppendChild(new Run(paraImage));
                        }
                    }
                    else
                    {
                        para3.AppendChild(new Run(new Text(" ")));
                    }
                    //myMath = new DocumentFormat.OpenXml.Math.OfficeMath(new M.Run(new M.Text(item.ValueAsString + item.Unit) { Space = SpaceProcessingModeValues.Preserve }));
                    //para3.AppendChild(myMath);
                    //para3.AppendChild(new Run(new Text(" ") { Space = SpaceProcessingModeValues.Preserve }));
                }
                else if (item.Type == CalcValueType.SELECTIONLIST)
                {
                    para3.AppendChild(new Run(new Text(item.ValueAsString)));
                }
                else
                {
                    cell2.AppendChild(new Paragraph(new Run(new Text(item.ValueAsString))));
                }
                TableCell cell3 = new TableCell();
                cell3.Append(para3);
                cell3.Append(new TableCellProperties(new TableCellWidth()
                {
                    Type = TableWidthUnitValues.Dxa, Width = "1700"
                }));
                row.Append(cell1, cell2, cell3);
                tableOfInputs.AppendChild(row);
            }
            return(tableOfInputs);
        }
Exemplo n.º 28
0
        /// <summary>
        /// This is implemented to perform the component tasks.
        /// </summary>
        /// <param name="document">The XML document with which to work.</param>
        /// <param name="key">The key (member name) of the item being documented.</param>
        public override void Apply(XmlDocument document, string key)
        {
            var latexList = document.SelectNodes("//latex");

            if (latexList == null)
            {
                return;
            }

            foreach (XmlNode code in latexList)
            {
                var attr       = code.Attributes.GetNamedItem("expr");
                var expression = attr == null ? code.InnerText : attr.InnerText;

                if (String.IsNullOrWhiteSpace(expression))
                {
                    continue;
                }

                bool svgOut = true;

                var result      = GetImageName(expression, svgOut);
                var filename    = result.Item2;
                var filenamePng = Path.ChangeExtension(filename, ".png");

                var parser = new TexFormulaParser();

                if (!result.Item1)
                {
                    foreach (var path in _paths)
                    {
                        //TODO: copy instead of running for each path
                        //SafeNativeMethods.CreateGifFromEq(expression, path + filename, _fontSize);
                        //
                        //const string latex = @"\frac{2+2}{2}";
                        //const string fileName = @"T:\Temp\formula.png";
                        TexFormula formula;
                        try
                        {
                            formula = parser.Parse(expression);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("An error occurred while parsing the given input: " + ex.Message);
                            continue;
                        }

                        if (svgOut)
                        {
                            // Output png for fallback.
                            var    renderer = formula.GetRenderer(TexStyle.Display, 20, "Arial");
                            var    bitmap   = renderer.RenderToBitmap(0, 0);
                            double width    = bitmap.Width;
                            double height   = bitmap.Height;

                            renderer = formula.GetRenderer(TexStyle.Display, 20, "Arial");
                            var geometry    = renderer.RenderToGeometry(0, 0);
                            var converter   = new SVGConverter();
                            var svgPathText = converter.ConvertGeometry(geometry);
                            var svgText     = AddSVGHeader(svgPathText, width, height);
                            using (var stream = new FileStream(path + filename, FileMode.Create))
                            {
                                using (var writer = new StreamWriter(stream))
                                    writer.WriteLine(svgText);
                            }

                            // Output png for fallback.
                            var pngBytes = formula.RenderToPng(20.0, 0.0, 0.0, "Arial");
                            File.WriteAllBytes(path + filenamePng, pngBytes);
                        }
                        else
                        {
                            var pngBytes = formula.RenderToPng(20.0, 0.0, 0.0, "Arial");
                            File.WriteAllBytes(path + filename, pngBytes);
                        }
                    }
                }



                var src = document.CreateAttribute("src");
                src.Value = "../html/" + filename;
                var hspace = document.CreateAttribute("hspace");
                hspace.Value = "0";
                var vspace = document.CreateAttribute("vspace");
                vspace.Value = "0";
                var align = document.CreateAttribute("align");
                align.Value = "bottom";
                XmlNode img = document.CreateElement("img");
                img.Attributes.Append(src);
                img.Attributes.Append(hspace);
                img.Attributes.Append(vspace);
                img.Attributes.Append(align);
                if (svgOut)
                {
                    // Add a png fallback
                    var onError = document.CreateAttribute("onerror");
                    onError.Value = "this.src='../html/" + filenamePng + "'";
                    img.Attributes.Append(onError);
                }
                code.ParentNode.ReplaceChild(img, code);
            }
        }
Exemplo n.º 29
0
        protected void DoWriteLatex(string text, LatexOptions options)
        {
            options ??= new LatexOptions();

            var book = options.Book?.Document ?? Document;

            using (new UsingProcessor(() => book.BeginUpdate(), () => book.EndUpdate()))
            {
                DocumentPosition rangeStart = null, rangeEnd = null;

                var parser     = new TexFormulaParser();
                var formula    = parser.Parse(text);

                var renderer   = formula.GetRenderer(TexStyle.Text, options.FontSize, "Tahoma");

                var geometry   = renderer.RenderToGeometry(0, 0);
                var converter  = new SVGConverter();
                var svgPathText = converter.ConvertGeometry(geometry);
                var svgText    = AddSVGHeader(svgPathText);

                var imageLatex = PaintSVG(svgText, options.DPI);
                AddUserCommentsToImage(imageLatex, text);
                var image = book.Images.Append(imageLatex);

                image.ScaleX = options.Scale;
                image.ScaleY = options.Scale;

                var rangeImage = image.Range;
                if (rangeStart == null)
                {
                    rangeStart = rangeImage.Start;
                }

                if (!options.NoLineBreaks)
                {
                    rangeImage = book.AppendText(Environment.NewLine);
                }

                rangeEnd = rangeImage.End;

                if (rangeStart != null && rangeEnd != null)
                {
                    var range = book.CreateRange(rangeStart, rangeEnd.ToInt() - rangeStart.ToInt());

                    if (!string.IsNullOrWhiteSpace(options.ParagraphStyle))
                    {
                        var style = book.ParagraphStyles[options.ParagraphStyle] ?? throw new Exception($"Paragraph style '{options.ParagraphStyle}' does not exist.");
                        var pp    = book.BeginUpdateParagraphs(range);
                        try
                        {
                            pp.Style = style;
                        }
                        finally
                        {
                            book.EndUpdateParagraphs(pp);
                        }
                    }

                    Script.Book.SCBook.AddComments(book, range, options);

                    WriteRangeToConsole(book, range);
                }

                if (rangeEnd != null)
                {
                    book.CaretPosition = rangeEnd;
                    Script.Book.SCBook.ResetBookFormatting(book, rangeEnd);
                    ScrollToCaret();
                }
            }
Exemplo n.º 30
0
 public void AddAccent(string formula, string accentName) => AddAccent(FormulaParser.Parse(formula), accentName);