public static class PdfHelper
{
private static async Task<byte[]> GetPdfFromHtmlString(string content, string id)
{
var path = GetExecutingDirectory();
var exePath = Path.Join(path, "wkhtmltopdf.exe");
var inputPath = Path.Join(path, $"{id}.html");
var outputPath = Path.Join(path, $"{id}.pdf");
await File.WriteAllTextAsync(inputPath, content);
// https://stackoverflow.com/questions/6057781/wkhtmltopdf-with-full-page-background
var arguments = $" -T 0 -B 0 -L 0 -R 0 --dpi 300 --page-size A4 --disable-smart-shrinking --print-media-type \"{inputPath}\" \"{outputPath}\"";
await RunProcessAsync(exePath, arguments);
var bytes = await File.ReadAllBytesAsync(outputPath);
File.Delete(inputPath);
File.Delete(outputPath);
return bytes;
}
private static string GetExecutingDirectory()
{
var location = new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase);
return new FileInfo(location.AbsolutePath)?.Directory?.FullName;
}
private static void RunProcess(string fileName, string arguments, string workingDirectory)
{
var process = new Process
{
StartInfo = { FileName = fileName, Arguments = arguments, WorkingDirectory = workingDirectory }
};
process.Start();
}
private static Task<int> RunProcessAsync(string fileName, string arguments)
{
var tcs = new TaskCompletionSource<int>();
var process = new Process
{
StartInfo = { FileName = fileName, Arguments = arguments, WorkingDirectory = GetExecutingDirectory() },
EnableRaisingEvents = true
};
process.Exited += (sender, args) =>
{
tcs.SetResult(process.ExitCode);
process.Dispose();
};
process.Start();
return tcs.Task;
}
public static async Task<byte[]> GetOrderConfirmation(string template, string id)
{
var stream = await GetPdfFromHtmlString(template, id);
return stream;
}
public static async Task<string> GetOrderConfirmationTemplate(CustomerOrder customerOrder)
{
var template = await DotLiquidHelper
.GetTemplate("orderConfirmation.html");
return template.Render(Hash.FromAnonymousObject(new { data = new OrderConfirmationDrop(customerOrder) }));
}
}
public static class DotLiquidHelper
{
private static async Task<string> GetTemplateAsString(string filename)
{
var path = Path.Join(ConfigurationHelper.GetExecutingDirectory(), $"\\Templates\\{filename}");
using (var streamReader = new StreamReader(path, Encoding.UTF8))
{
return await streamReader.ReadToEndAsync();
}
}
public static async Task<Template> GetTemplate(string fileName)
{
Template.NamingConvention = new CSharpNamingConvention();
var templateString = await GetTemplateAsString(fileName);
var template = Template.Parse(templateString);
template.MakeThreadSafe();
return template;
}
}
220300cookie-checkC# RunProcessAsync