{"id":2203,"date":"2019-06-12T09:53:21","date_gmt":"2019-06-12T08:53:21","guid":{"rendered":"https:\/\/solidt.eu\/site\/?p=2203"},"modified":"2022-07-25T08:33:26","modified_gmt":"2022-07-25T07:33:26","slug":"c-runprocessasync","status":"publish","type":"post","link":"https:\/\/solidt.eu\/site\/c-runprocessasync\/","title":{"rendered":"C# RunProcessAsync"},"content":{"rendered":"\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"> public static class PdfHelper\n    {\n        private static async Task&lt;byte[]> GetPdfFromHtmlString(string content, string id)\n        {\n            var path = GetExecutingDirectory();\n            var exePath = Path.Join(path, \"wkhtmltopdf.exe\");\n            var inputPath = Path.Join(path, $\"{id}.html\");\n            var outputPath = Path.Join(path, $\"{id}.pdf\");\n\n            await File.WriteAllTextAsync(inputPath, content);\n\n            \/\/ https:\/\/stackoverflow.com\/questions\/6057781\/wkhtmltopdf-with-full-page-background\n            var arguments = $\" -T 0 -B 0 -L 0 -R 0 --dpi 300 --page-size A4 --disable-smart-shrinking --print-media-type \\\"{inputPath}\\\" \\\"{outputPath}\\\"\";\n            await RunProcessAsync(exePath, arguments);\n\n            var bytes = await File.ReadAllBytesAsync(outputPath);\n\n            File.Delete(inputPath);\n            File.Delete(outputPath);\n\n            return bytes;\n        }\n\n        private static string GetExecutingDirectory()\n        {\n            var location = new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase);\n            return new FileInfo(location.AbsolutePath)?.Directory?.FullName;\n        }\n\n        private static void RunProcess(string fileName, string arguments, string workingDirectory)\n        {\n            var process = new Process\n            {\n                StartInfo = { FileName = fileName, Arguments = arguments, WorkingDirectory = workingDirectory }\n            };\n            process.Start();\n        }\n\n        private static Task&lt;int> RunProcessAsync(string fileName, string arguments)\n        {\n            var tcs = new TaskCompletionSource&lt;int>();\n\n            var process = new Process\n            {\n                StartInfo = { FileName = fileName, Arguments = arguments, WorkingDirectory = GetExecutingDirectory() },\n                EnableRaisingEvents = true\n            };\n\n            process.Exited += (sender, args) =>\n            {\n                tcs.SetResult(process.ExitCode);\n                process.Dispose();\n            };\n\n            process.Start();\n\n            return tcs.Task;\n        }\n\n        public static async Task&lt;byte[]> GetOrderConfirmation(string template, string id)\n        {\n            var stream = await GetPdfFromHtmlString(template, id);\n            return stream;\n        }\n\n        public static async Task&lt;string> GetOrderConfirmationTemplate(CustomerOrder customerOrder)\n        {\n            var template = await DotLiquidHelper\n                .GetTemplate(\"orderConfirmation.html\");\n\n            return template.Render(Hash.FromAnonymousObject(new { data = new OrderConfirmationDrop(customerOrder) }));\n        }\n    }<\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public static class DotLiquidHelper\n    {\n        private static async Task&lt;string> GetTemplateAsString(string filename)\n        {\n            var path = Path.Join(ConfigurationHelper.GetExecutingDirectory(), $\"\\\\Templates\\\\{filename}\");\n\n            using (var streamReader = new StreamReader(path, Encoding.UTF8))\n            {\n                return await streamReader.ReadToEndAsync();\n            }\n        }\n\n        public static async Task&lt;Template> GetTemplate(string fileName)\n        {\n            Template.NamingConvention = new CSharpNamingConvention();\n\n            var templateString = await GetTemplateAsString(fileName);\n            var template = Template.Parse(templateString);\n\n            template.MakeThreadSafe();\n\n            return template;\n        }\n    }<\/pre>\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[6,4,1],"tags":[],"class_list":["post-2203","post","type-post","status-publish","format-standard","hentry","category-dotnet","category-programming","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/2203","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/comments?post=2203"}],"version-history":[{"count":2,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/2203\/revisions"}],"predecessor-version":[{"id":2205,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/2203\/revisions\/2205"}],"wp:attachment":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/media?parent=2203"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/categories?post=2203"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/tags?post=2203"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}