-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWeb2PdfWebBrowser.cs
More file actions
78 lines (69 loc) · 2.5 KB
/
Web2PdfWebBrowser.cs
File metadata and controls
78 lines (69 loc) · 2.5 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
66
67
68
69
70
71
72
73
74
75
76
77
78
using CefSharp;
using CefSharp.OffScreen;
using System;
using System.IO;
using System.Threading;
namespace Web2Pdf
{
public class Web2PdfWebBrowser
{
private Web2PdfConfig _config;
private bool _success = false;
private ManualResetEvent _evtCompleted = null;
private ChromiumWebBrowser _browser = null;
public Web2PdfWebBrowser(Web2PdfConfig config)
{
_config = config;
_evtCompleted = new ManualResetEvent(false);
var settings = new CefSettings()
{
//CachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CefSharp\\Cache"),
//LogSeverity = LogSeverity.Disable
};
Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);
_browser = new ChromiumWebBrowser(_config.UrlString);
_browser.LoadingStateChanged += Browser_LoadingStateChanged;
}
private async void Browser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
{
if (!e.IsLoading)
{
_browser.LoadingStateChanged -= Browser_LoadingStateChanged;
Thread.Sleep(500);
var filePath = GetEffectiveOutputFilePath();
_success = await _browser.PrintToPdfAsync(filePath);
if (_success)
{
Console.WriteLine($"File '{filePath}' successfully created.");
}
else
{
Console.WriteLine($"File '{filePath}' could not be created.");
}
_evtCompleted.Set();
}
}
private string GetEffectiveOutputFilePath()
{
var fullFilePath = Path.GetFullPath(_config.OutputFilePath);
if (_config.UseTimestampPrefix)
{
var folderName = Path.GetDirectoryName(fullFilePath);
var fileName = Path.GetFileName(fullFilePath);
var newFileName = $"{System.DateTime.Now.ToString("yyyyMMdd_HHmmss")}_{fileName}";
var newPath = Path.Combine(folderName, newFileName);
return newPath;
}
else
{
return fullFilePath;
}
}
public bool WaitForCompletion()
{
_evtCompleted.WaitOne();
Cef.Shutdown();
return _success;
}
}
}