-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPhantomJS.cs
105 lines (84 loc) · 3.2 KB
/
PhantomJS.cs
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
namespace PhantomUI
{
public class PhantomJs
{
#region Init
public enum FileType
{
Pdf,
Jpeg,
Png
}
public string ApplicationDirectory { get; set; }
public PhantomJs() {
string basePath = Assembly.GetExecutingAssembly().Location;
string baseDir = Path.GetDirectoryName(basePath);
ApplicationDirectory = baseDir;
}
#endregion
#region NewCode
/// <summary>
/// Not implemented
/// Changing code to be able to pass in options more easily
/// </summary>
public async Task<string> RunPhantomJs(List<string> options, List<string> arguments)
{
return await Task.Run(() => Start(options, arguments));
}
private string Start(List<string> options, List<string> arguments)
{
return "";
}
#endregion
#region OldCode
public async Task<string> GetPdfTask(string url, FileType returnType)
{
return await Task.Run(() => UrlToPdf(url, returnType));
}
private string UrlToPdf(string url, FileType returnType)
{
var path = string.Format(@"{0}\lib\phantomjs-custom.exe", ApplicationDirectory);
if (string.IsNullOrEmpty(path) || !File.Exists(path))
{
throw new FileNotFoundException("Could not find PhantomJS executable.");
}
var dir = Path.GetDirectoryName(path);
if (string.IsNullOrEmpty(dir) || !Directory.Exists(dir))
{
throw new FileNotFoundException("Could not determin PhantomJS base directory.");
}
var fileName = Path.GetFileName(path);
var savePath = string.Format(@"{0}{1}.{2}", Path.GetTempPath(), Guid.NewGuid(), returnType.ToString().ToLower());
// If is a local file, we need to adapt the path a bit
if (File.Exists(url))
{
url = string.Format("file:///{0}", Uri.EscapeDataString(url).Replace("%3A", ":").Replace("%5C", "/"));
}
var arguments = string.Format(@"--config=config.json scripts/run.js {0} {1}", url, savePath);
using (var process = new Process())
{
process.EnableRaisingEvents = true;
process.ErrorDataReceived += (sender, e) =>
{
throw new Exception("process.ErrorDataReceived");
};
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.ErrorDialog = true;
process.StartInfo.FileName = fileName;
process.StartInfo.Arguments = arguments;
process.StartInfo.WorkingDirectory = dir;
process.Start();
process.WaitForExit(10000);
}
return savePath;
}
#endregion
}
}