-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunction1.cs
More file actions
65 lines (59 loc) · 2.37 KB
/
Function1.cs
File metadata and controls
65 lines (59 loc) · 2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using CefSharp.OffScreen;
using CefSharp;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
using System.IO;
namespace AzureCEF_HTMLtoPDFConversion
{
public class Function1
{
private readonly ILogger<Function1> _logger;
public Function1(ILogger<Function1> logger)
{
_logger = logger;
}
[Function("Function1")]
public async Task<IActionResult> RunAsync([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequest req)
{
_logger.LogInformation("C# HTTP trigger function processed a request.");
MemoryStream memoryStream = null;
// Initialize CefSharp
var settings = new CefSettings()
{
LogSeverity = LogSeverity.Disable,
CachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CefSharp\\Cache")
};
_logger.LogInformation("Initializing CefSharp settings.");
if (!Cef.IsInitialized)
{
var success = Cef.Initialize(settings, performDependencyCheck: false, browserProcessHandler: null);
}
try
{
// Create a browser instance
var browser = new ChromiumWebBrowser("https://www.google.com/");
_logger.LogInformation("Waiting for initial loading.");
await browser.WaitForInitialLoadAsync();
string fileName = Guid.NewGuid().ToString();
string tempFilePath = Path.Combine(Path.GetTempPath(), fileName + ".pdf");
_logger.LogInformation($"Generating the pdf file.");
await browser.PrintToPdfAsync(tempFilePath);
memoryStream = new MemoryStream();
byte[] bytes = File.ReadAllBytes(tempFilePath);
memoryStream.Write(bytes, 0, bytes.Length);
memoryStream.Position = 0;
}
catch (Exception ex)
{
_logger.LogError(ex.Message.ToString());
}
var fileStreamResult = new FileStreamResult(memoryStream, "application/pdf")
{
FileDownloadName = "Html-to-PDF-Output.pdf"
};
return fileStreamResult;
}
}
}