此指南显示如何添加 ** 实时 LaTeX 数学传输** 到 ASP.NET 应用程序使用 ** Aspose. TeX for .NET**. 您将建立一个小型 Web API 接收 LaTex 输入,将其转换为 ** PNG**,以正确的内容类型返回图像比特,并在磁盘上存储结果。

你要建造的

  • 使用 ASP.NET Core 应用程序:

  • Endpoint POST /api/latex/png 接受 LaTeX 并返回 PNG 图像

  • 简单的HTML页面,用户输入方程式并查看直播预览

  • 磁盘缓存由内容Hash和DPI密钥

  • 基本输入验证和 Sandboxed 工作目录

你可以复制代码并按照它进行操作。

原則

  • Windows、Linux 或 macOS 與 .NET 6 及更高版本

  • Visual Studio 2022 或 ** VS 代码** C# 扩展

  • NuGet 包 Aspose.TeX

dotnet add package Aspose.TeX

ASPOSE.TEX 曝光 TeXOptions, TeXConfig.ObjectLaTeX, PngSaveOptions, ImageDevice, TeXJob, InputFileSystemDirectory, 和 OutputFileSystemDirectory您将使用这些来将 LaTeX 转换为 PNG。

项目Layout

创建一个 ASP.NET Core Web API 项目,然后添加轻量级服务以及最小的 HTML 页面。

AsposeTexDemo/
  Program.cs
  Services/
    LatexRenderer.cs
  wwwroot/
    index.html

服务: LaTeX to PNG Render

此服务将 LaTeX 发送到临时 .tex 文件运行 Aspose.TeX 工作,并返回 PNG 字节。

// File: Services/LatexRenderer.cs
using System.Security.Cryptography;
using System.Text;
using Aspose.TeX;

namespace AsposeTexDemo.Services;

public sealed class LatexRenderer
{
    private readonly string _cacheRoot;
    private readonly ILogger<LatexRenderer> _log;

    public LatexRenderer(IWebHostEnvironment env, ILogger<LatexRenderer> log)
    {
        _cacheRoot = Path.Combine(env.ContentRootPath, "tex-cache");
        Directory.CreateDirectory(_cacheRoot);
        _log = log;
    }

    // Public entry point. Renders LaTeX to PNG and returns bytes.
    public async Task<byte[]> RenderPngAsync(string latexBody, int dpi = 200, CancellationToken ct = default)
    {
        // Validate and normalize input
        var normalized = NormalizeLatex(latexBody);
        ValidateLatex(normalized);

        // Cache key depends on content and dpi
        var key = Hash($"{normalized}\n{dpi}");
        var cacheDir = Path.Combine(_cacheRoot, key);
        var cachePng = Path.Combine(cacheDir, "out.png");

        if (File.Exists(cachePng))
        {
            _log.LogDebug("Cache hit: {Key}", key);
            return await File.ReadAllBytesAsync(cachePng, ct);
        }

        Directory.CreateDirectory(cacheDir);

        // Prepare a minimal document that wraps the math
        var texDoc = BuildStandaloneDocument(normalized);

        // Write the .tex source into an isolated working folder
        var workDir = Path.Combine(cacheDir, "work");
        Directory.CreateDirectory(workDir);
        var texPath = Path.Combine(workDir, "doc.tex");
        await File.WriteAllTextAsync(texPath, texDoc, Encoding.UTF8, ct);

        // Configure Aspose.TeX conversion options
        var options = TeXOptions.ConsoleAppOptions(TeXConfig.ObjectLaTeX);
        options.InputWorkingDirectory  = new InputFileSystemDirectory(workDir);
        options.OutputWorkingDirectory = new OutputFileSystemDirectory(workDir);

        var png = new PngSaveOptions
        {
            // If you want higher fidelity on HiDPI displays, raise this number
            Resolution = dpi,

            // When false, the ImageDevice buffers PNG bytes in memory so you can capture them without file I/O
            // You can also leave the default (true) and read the file from disk. Both modes are shown below.
            DeviceWritesImages = false
        };
        options.SaveOptions = png;

        // Run the job; capture PNG bytes from the device
        var device = new ImageDevice();
        new TeXJob(texPath, device, options).Run();

        if (device.Result == null || device.Result.Length == 0)
            throw new InvalidOperationException("No PNG output generated by TeX engine.");

        var pngBytes = device.Result[0];

        // Persist into cache for the next request
        await File.WriteAllBytesAsync(cachePng, pngBytes, ct);

        // Clean up working files except cachePng if you want to keep cache slim
        TryDeleteDirectory(workDir);

        return pngBytes;
    }

    private static void TryDeleteDirectory(string dir)
    {
        try { if (Directory.Exists(dir)) Directory.Delete(dir, true); }
        catch { /* swallow to avoid noisy logs in high traffic */ }
    }

    // Minimal, safe preamble for math using Object LaTeX
    private static string BuildStandaloneDocument(string latexBody)
    {
        // With standalone class, the output image is tightly cropped around content
        return
$@"\documentclass{{standalone}}
\usepackage{{amsmath}}
\usepackage{{amssymb}}
\begin{{document}}
{latexBody}
\end{{document}}";
    }

    // Allow plain math snippets like x^2 + y^2 = z^2 and also wrapped forms like \[ ... \]
    private static string NormalizeLatex(string input)
    {
        input = input.Trim();

        // If user did not wrap math, wrap in display math to get proper spacing
        if (!(input.StartsWith(@"\[") && input.EndsWith(@"\]"))
            && !(input.StartsWith(@"$$") && input.EndsWith(@"$$")))
        {
            return $"\\[{input}\\]";
        }
        return input;
    }

    // Very conservative validation to avoid file inclusion or shell escapes
    private static void ValidateLatex(string input)
    {
        // Disallow commands that can touch the filesystem or process environment
        string[] blocked = {
            @"\write18", @"\input", @"\include", @"\openout", @"\write", @"\read",
            @"\usepackage", // preamble is fixed in BuildStandaloneDocument; avoid arbitrary packages
            @"\loop", @"\csname", @"\newread", @"\newwrite"
        };

        foreach (var b in blocked)
        {
            if (input.Contains(b, StringComparison.OrdinalIgnoreCase))
                throw new ArgumentException($"The LaTeX contains a forbidden command: {b}");
        }

        if (input.Length > 4000)
            throw new ArgumentException("Equation too long. Please keep input under 4000 characters.");
    }

    private static string Hash(string s)
    {
        using var sha = SHA256.Create();
        var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(s));
        return Convert.ToHexString(bytes).ToLowerInvariant();
    }
}

网页API:最小 ASP.NET 核心终点

这定义了JSON合同,记录了发行人,并展示了 POST 返回PNG的终点。

// File: Program.cs
using System.Text.Json.Serialization;
using AsposeTexDemo.Services;

var builder = WebApplication.CreateBuilder(args);

// Optional: serve a simple static page for testing
builder.Services.AddDirectoryBrowser();

// Add the renderer
builder.Services.AddSingleton<LatexRenderer>();

// Configure Kestrel limits for small payloads
builder.WebHost.ConfigureKestrel(opt =>
{
    opt.Limits.MaxRequestBodySize = 256 * 1024; // 256 KB per request is plenty for math
});

var app = builder.Build();

// Serve wwwroot for quick manual testing
app.UseDefaultFiles();
app.UseStaticFiles();

// DTOs
public record LatexRequest(
    [property: JsonPropertyName("latex")] string Latex,
    [property: JsonPropertyName("dpi")]   int? Dpi
);

app.MapPost("/api/latex/png", async (LatexRequest req, LatexRenderer renderer, HttpContext ctx, CancellationToken ct) =>
{
    if (string.IsNullOrWhiteSpace(req.Latex))
        return Results.BadRequest(new { error = "Missing 'latex'." });

    int dpi = req.Dpi is > 0 and <= 600 ? req.Dpi.Value : 200;

    try
    {
        var bytes = await renderer.RenderPngAsync(req.Latex, dpi, ct);
        ctx.Response.Headers.CacheControl = "public, max-age=31536000, immutable";
        return Results.File(bytes, "image/png");
    }
    catch (ArgumentException ex)
    {
        return Results.BadRequest(new { error = ex.Message });
    }
    catch (Exception ex)
    {
        // Hide engine details from clients; log the exception server-side if needed
        return Results.StatusCode(500);
    }
});

// Health check
app.MapGet("/health", () => Results.Ok(new { ok = true }));

app.Run();

简单的测试页面

把它推进 wwwroot/index.html 在没有前端框架的浏览器中尝试 API。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>Aspose.TeX LaTeX Demo</title>
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <style>
    body{font-family:system-ui,Segoe UI,Roboto,Arial,sans-serif;margin:2rem;line-height:1.4}
    textarea{width:100%;height:8rem}
    .row{display:flex;gap:1rem;align-items:flex-start;margin-top:1rem;flex-wrap:wrap}
    .card{border:1px solid #ddd;border-radius:8px;padding:1rem;flex:1 1 320px}
    img{max-width:100%;height:auto;border:1px solid #eee;border-radius:4px;background:#fff}
    label{font-weight:600}
    input[type=number]{width:6rem}
    .muted{color:#666;font-size:.9rem}
    .error{color:#b00020}
  </style>
</head>
<body>
  <h1>Real-time LaTeX to PNG with Aspose.TeX</h1>
  <p class="muted">Type LaTeX math and click Render. The server returns a PNG image rendered by Aspose.TeX.</p>

  <div class="card">
    <label for="latex">LaTeX</label><br />
    <textarea id="latex">x^2 + y^2 = z^2</textarea><br />
    <label for="dpi">DPI</label>
    <input id="dpi" type="number" min="72" max="600" value="200" />
    <button id="btn">Render</button>
    <div id="msg" class="error"></div>
  </div>

  <div class="row">
    <div class="card">
      <h3>Preview</h3>
      <img id="preview" alt="Rendered equation will appear here" />
    </div>
    <div class="card">
      <h3>cURL</h3>
      <pre id="curl" class="muted"></pre>
    </div>
  </div>

  <script>
    const btn = document.getElementById('btn');
    const latex = document.getElementById('latex');
    const dpi = document.getElementById('dpi');
    const img = document.getElementById('preview');
    const msg = document.getElementById('msg');
    const curl = document.getElementById('curl');

    function updateCurl() {
      const payload = JSON.stringify({ latex: latex.value, dpi: Number(dpi.value) }, null, 0);
      curl.textContent =
`curl -s -X POST http://localhost:5000/api/latex/png \
  -H "Content-Type: application/json" \
  -d '${payload}' --output out.png`;
    }

    updateCurl();

    [latex, dpi].forEach(el => el.addEventListener('input', updateCurl));

    btn.addEventListener('click', async () => {
      msg.textContent = '';
      img.src = '';
      try {
        const payload = { latex: latex.value, dpi: Number(dpi.value) };
        const res = await fetch('/api/latex/png', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload)
        });
        if (!res.ok) {
          const err = await res.json().catch(() => ({}));
          msg.textContent = err.error || `Error ${res.status}`;
          return;
        }
        const blob = await res.blob();
        img.src = URL.createObjectURL(blob);
      } catch (e) {
        msg.textContent = 'Request failed.';
      }
    });
  </script>
</body>
</html>

运行项目

dotnet run

Open http://localhost:5000http://localhost:5173 取决于您的启动个人资料. 输入方程式并单击 Render. Preview 更新与服务器侧 PNG 的输出。

配置和部署笔记

  • Aspose.TeX 许可证如果您有许可文件,请在启动期间设置该文件以删除评估限制。
// in Program.cs, before first use
// new Aspose.TeX.License().SetLicense("Aspose.Total.lic");
    • 存储位置*播放器在下方编写缓存文件 tex-cache/ 在内容根中. 在Linux或容器部署中,您可以将此路径安装在持久的容量上. 如果需要的话,按日程清理。
  • 请求尺寸限制示例容器要求大小为 256 KB. 如果您支持更大的输入,则增加。

  • ** 跨源访问**如果您服务于与网站不同起源的API,则可根据此启用CORS。

安全检查列表

  • 该服务拒绝潜在危险的命令,如 \input, \include, 和 \write18. 保持允许列表紧,并保持前置固定在 BuildStandaloneDocument.
  • 限制输入长度,阻止病理负载。
  • 按请求输入一个独特的工作目录,并在成功后删除目錄. 样品只保留隐藏的 PNG。
  • 考虑在公共网站的反向代理或API门口级别的利率限制。

性能提示

  • 使用 ** 磁盘存储库** 以避免重新计算相同的方程式. 样品对 LaTeX 和 DPI 进行复制。
  • 保持 DPI 150 至 300 为大多数 UI 需求。
  • 通过在初创时提供一个常见的公式来加热应用程序,如果您希望用户的第一个请求即时。
  • 如果您需要引导输出可转换的内容,则转到 SvgSaveOptionsSvgDevice,然后插入 SVG. 其余的管道是相同的。

Troubleshooting

  • ** 白色输出或错误**查看服务器日志. 如果 LaTeX 使用固定前列外的包,请删除它们。 \usepackage 根据设计的用户输入。
  • ** 粘贴或大边缘**是的 standalone 文档类通常会密切发送边缘,如果您仍然看到额外的空间,请 \[\] 为显示数学或删除它们为内线大小。
    • 保存文本*增加 PngSaveOptions.Resolution在 200 至 300 DPI 中,大多数 UI 案例看起来很糟糕。

API 使用代码的快速参考

  • TeXOptions.ConsoleAppOptions(TeXConfig.ObjectLaTeX): 为 Object LaTeX 发动机创建选项
  • PngSaveOptions: 控制 PNG 输出 ResolutionDeviceWritesImages
  • ImageDevice: 泡沫 PNG 结果在记忆中当 DeviceWritesImages = false
  • TeXJob(texPath, device, options).Run()• 编辑 The .tex 文件进入设备
  • InputFileSystemDirectoryOutputFileSystemDirectory: 定义输入和输出工作目录

使用这些构建区块,您的 ASP.NET 应用程序可以可靠地提供 LaTeX 的需求、存储结果和服务于 crisp PNG 方程式。

More in this category