balbarak / WeasyPrint-netcore

WeasyPrint Wrapper for .Net on Windows
BSD 3-Clause "New" or "Revised" License
71 stars 19 forks source link

dos windows flash out when use in WinForm #16

Open qq57941500 opened 3 years ago

qq57941500 commented 3 years ago

first of all, thanks a lot for this .net wrapper, very handy to use. I tried to test it from a winform application, it shows up a black command line window quickly and closes automatically. is there a solution to this issue?

private async void button1_Click(object sender, EventArgs e) { using (WeasyPrintClient client = new WeasyPrintClient(trace)) { var html = "<!DOCTYPE html><html><body><h1>Hello World</h1></body></html>"; var fileContent = await client.GeneratePdfAsync(html); File.WriteAllBytes(@"D:\TT\temp\test.pdf", fileContent); } }

NerLOR commented 1 year ago

Hi! For anyone still looking for a workaround for this issue, this may help. I use the python and WeasyPrint exe's directly and so I may pass CreateNoWindow = true to the process.

private static readonly FilesManager WeasyPrintManager = new();
private static string? WeasyPrintPython = null;
private static string? WeasyPrintDir => WeasyPrintManager.FolderPath;

public static async Task Init() {
    if (!WeasyPrintManager.IsFilesExsited()) {
        await WeasyPrintManager.InitFilesAsync();
    }
    WeasyPrintPython = Path.Combine(WeasyPrintManager.FolderPath, "python.exe");
}

public static async Task Convert(string htmlPath, string pdfPath) {
    var p = new Process() { StartInfo = new() {
        FileName = WeasyPrintPython,
        CreateNoWindow = true,
        WorkingDirectory = WeasyPrintDir,
        RedirectStandardError = true,
    } };
    p.StartInfo.EnvironmentVariables["PATH"] = "Scripts;gtk3;" + Environment.GetEnvironmentVariable("PATH");
    p.StartInfo.ArgumentList.Add("scripts/weasyprint.exe");
    p.StartInfo.ArgumentList.Add("-e");
    p.StartInfo.ArgumentList.Add("utf8");
    p.StartInfo.ArgumentList.Add(htmlPath);
    p.StartInfo.ArgumentList.Add(pdfPath);
    p.Start();
    await p.WaitForExitAsync();
    var stderr = await p.StandardError.ReadToEndAsync();
    if (p.ExitCode != 0) throw new Exception(stderr);
}