LaTeX에서 PNG까지 배치 렌더링은 웹 문서, 지식 기반 및 수학 무거운 응용 프로그램에 대한 일반적인 요구 사항입니다. ** .NET을 위한 Aspose.TEX는 간단한 API를 제공합니다. .tex 출력 디렉토리 및 해상도를 제어하는 라스터 이미지에 출처.이 기사는 최소한의 단일 파일 변환기와 강력한 배치 파이프라인을 보여줍니다. .NET 앱에 내려갈 수 있습니다.

원칙

  • .NET 6 또는 이후
  • 포장 패키지 : Aspose.TeX
  • Aspose.TeX에 의해 사용되는 Object LaTEX 엔진 아래에서 컴파일하는 라텍스 출처

ASPOSE.TEX 소개 TeXOptions.ConsoleAppOptions(TeXConfig.ObjectLaTeX), ImageDevice그리고, 그리고 PngSaveOptions PNG 생산을 위해.

최소 변환: 하나의 LaTeX 파일에서 PNG

이 예제가 변환된다. hello-world.ltx (또는 .tex) 출력 폴더에 PNG. 장치는 이미지 파일을 직접 작성합니다.

// File: Program.cs
// NuGet: Aspose.TeX

using System;
using System.IO;
using Aspose.TeX;

class Program
{
    static void Main()
    {
        var inputFile  = Path.GetFullPath("hello-world.tex"); // or .ltx
        var outputDir  = Path.GetFullPath("out-png");
        Directory.CreateDirectory(outputDir);

        // 1) Create conversion options for Object LaTeX
        TeXOptions options = TeXOptions.ConsoleAppOptions(TeXConfig.ObjectLaTeX);

        // 2) Choose where to write output files
        options.OutputWorkingDirectory = new OutputFileSystemDirectory(outputDir);

        // 3) Save as PNG (you can set resolution if required)
        var png = new PngSaveOptions
        {
            // Resolution = 300 // uncomment to render at 300 DPI
        };
        options.SaveOptions = png;

        // 4) Run the job. ImageDevice writes PNG files into the output directory.
        var device = new ImageDevice();
        new TeXJob(inputFile, device, options).Run();

        Console.WriteLine("PNG written to: " + outputDir);
    }
}

이것은 문서화 된 패턴을 따릅니다 : 창조 TeXOptions세트 OutputWorkingDirectory세트 PngSaveOptions그런 다음 A를 실행합니다. TeXJob A와 함께 ImageDevice.

배치 변환 : 모든 .tex 폴더에 있는 파일

배치 버전은 입력 디렉토리를 스캔하고 각각 변환합니다. .tex 그것은 또한 의존성과 포함 된 그래픽이 읽어지는 곳을 제어하는 방법을 보여줍니다.

// File: BatchLatexToPng.cs
// NuGet: Aspose.TeX

using System;
using System.IO;
using Aspose.TeX;

public static class BatchLatexToPng
{
    public static int Run(string inputDir, string outputDir, int? dpi = null)
    {
        if (!Directory.Exists(inputDir))
        {
            Console.Error.WriteLine("Input directory not found: " + inputDir);
            return 1;
        }
        Directory.CreateDirectory(outputDir);

        // Configure conversion options once and reuse
        var options = TeXOptions.ConsoleAppOptions(TeXConfig.ObjectLaTeX);

        // Where to read auxiliary inputs (e.g., included images)
        options.InputWorkingDirectory = new InputFileSystemDirectory(inputDir);

        // Where to read extra required packages (if you supply them)
        // options.RequiredInputDirectory = new InputFileSystemDirectory(Path.Combine(inputDir, "texmf"));

        // Where to write PNG, log, aux, etc.
        options.OutputWorkingDirectory = new OutputFileSystemDirectory(outputDir);

        // PNG save options (set DPI if needed)
        var png = new PngSaveOptions();
        if (dpi.HasValue) png.Resolution = dpi.Value;
        options.SaveOptions = png;

        int ok = 0, err = 0;
        var device = new ImageDevice(); // will write images to OutputWorkingDirectory

        foreach (var texPath in Directory.GetFiles(inputDir, "*.tex", SearchOption.AllDirectories))
        {
            try
            {
                // Optional: set a job name so output files have predictable names
                options.JobName = Path.GetFileNameWithoutExtension(texPath);

                new TeXJob(texPath, device, options).Run();
                Console.WriteLine("OK  " + Path.GetRelativePath(inputDir, texPath));
                ok++;
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERR " + Path.GetRelativePath(inputDir, texPath) + " | " + ex.Message);
                err++;
            }
        }

        Console.WriteLine($"Done. Success: {ok}, Failed: {err}");
        return err == 0 ? 0 : 2;
    }
}

배치 직업에 대한 핵심 포인트:

  • 사용하기 InputWorkingDirectory 포함된 자산과 같은 \includegraphics{img.png}.
  • 사용하기 RequiredInputDirectory 내장된 세트 밖에서 추가 LaTeX 패키지를 제공해야 하는 경우.
  • 세트 JobName 출력 파일 이름을 문서에 따라 영향을 미칩니다.

파일을 작성하는 대신 메모리에서 이미지를 캡처

PNG 바이트를 스스로 스트리밍하는 것을 선호하는 경우, 장치가 직접 파일 글을 끄고 그들을 버퍼하도록하십시오.

using System;
using System.IO;
using Aspose.TeX;

static void ConvertToStreams(string inputFile, string outputDir)
{
    Directory.CreateDirectory(outputDir);

    var options = TeXOptions.ConsoleAppOptions(TeXConfig.ObjectLaTeX);
    var png     = new PngSaveOptions { DeviceWritesImages = false };
    options.SaveOptions = png;

    var device = new ImageDevice();
    new TeXJob(inputFile, device, options).Run();

    for (int i = 0; i < device.Result.Length; i++)
    {
        var pageBytes = device.Result[i];
        var outPath   = Path.Combine(outputDir, $"page-{i + 1}.png");
        File.WriteAllBytes(outPath, pageBytes);
    }
}

이것은 주요 출력 PNG 파일을 작성하는 문서화 된 “대체 방법"을 반영합니다.

문제 해결 및 팁

  • 결정 : 증가 PngSaveOptions.Resolution retina 스크린 촬영 또는 인쇄 자산에서 더 날카로운 수식을 위해.
  • Dependencies : 사용자 지정 패키지 및 입력 목록에 배치 RequiredInputDirectory 그리고 InputWorkingDirectory.
    • 이름* : 세트 options.JobName 예측 가능한 출력 파일 이름에 대 한 배치 실행.
  • Logging : 엔진은 트랜스크립트를 작성합니다. .log 실종된 패키지와 LaTeX 오류를 분해하는 데 유용한 출력 디렉토리.

다른 형식을 선택할 때

PNG는 웹 출판 및 UI 삽입을위한 이상적입니다. 무한한 zoom 또는 스케일에 작은 텍스트를 위해 벡터 출력을 필요로하는 경우 SVG로 전환하여 사용 SvgSaveOptions 그리고 하나 SvgDevice, 또는 파이그드 문서에 대한 PDF. 변환 흐름은 동일합니다.

이러한 패턴을 사용하면 .NET에서 LaTeX에서 PNG를 자동화하여 해상도, 디렉토리 및 파일 관리에 대한 완전한 통제를 유지할 수 있습니다.

More in this category