Skip to content

Commit 5e4c213

Browse files
committed
finalize !
1 parent 3de00ed commit 5e4c213

File tree

4 files changed

+76
-168
lines changed

4 files changed

+76
-168
lines changed

src/Balbarak.WeasyPrint.Test/WeasyPrintClientTest.cs

+37
Original file line numberDiff line numberDiff line change
@@ -51,5 +51,42 @@ public void Should_Create_Pdf_From_Input_File()
5151

5252
}
5353
}
54+
55+
[Fact]
56+
public async Task Should_Create_Pdf_From_Input_File_Async()
57+
{
58+
var trace = new DebugTraceWriter();
59+
60+
var input = $"{_inputFolder}\\complex.html";
61+
var output = $"{_outputFolder}\\output.pdf";
62+
63+
using (WeasyPrintClient client = new WeasyPrintClient(trace))
64+
{
65+
await client.GeneratePdfAsync(input, output);
66+
67+
}
68+
}
69+
70+
[Fact]
71+
public async Task Should_Create_Pdf_From_Url_Async()
72+
{
73+
var trace = new DebugTraceWriter();
74+
75+
var url = "https://www.google.com";
76+
77+
using (WeasyPrintClient client = new WeasyPrintClient(trace))
78+
{
79+
var result = await client.GeneratePdfFromUrlAsync(url);
80+
81+
File.WriteAllBytes($"{_outputFolder}\\url.pdf", result);
82+
83+
}
84+
}
85+
86+
[Fact]
87+
public void Should_Create_Pdf_From_Url_Output_File()
88+
{
89+
90+
}
5491
}
5592
}
0 Bytes
Binary file not shown.
58.3 KB
Binary file not shown.

src/Balbarak.WeasyPrint/WeasyPrintClient.cs

+39-168
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,6 @@ namespace Balbarak.WeasyPrint
1515
{
1616
public class WeasyPrintClient : IDisposable
1717
{
18-
private readonly string _libDir = Path.Combine(Directory.GetCurrentDirectory(), "weasyprint-v48");
19-
private Process _nativeProccess;
2018
private readonly FilesManager _fileManager;
2119
private readonly ProcessInvoker _invoker;
2220
private readonly ITraceWriter _trace;
@@ -110,77 +108,40 @@ public async Task GeneratePdfAsync(string inputPathFile, string outputPathFile)
110108
}
111109
}
112110

113-
private async Task GeneratePdfInternal(string inputPathFile, string outputPathFile)
114-
{
115-
if (!File.Exists(inputPathFile))
116-
throw new FileNotFoundException();
117-
118-
await EnsureFilesExisted()
119-
.ConfigureAwait(false);
120-
121-
var cmd = $"/c python.exe scripts/weasyprint.exe {inputPathFile} {outputPathFile} -e utf8";
122-
123-
var workingDir = _fileManager.FolderPath;
124-
125-
await _invoker.ExcuteAsync(workingDir, "cmd.exe", cmd)
126-
.ConfigureAwait(false);
127-
}
128-
129111
public byte[] GeneratePdfFromUrl(string url)
130112
{
131-
if (!CheckFiles())
132-
InitFiles();
133-
134-
byte[] result = null;
113+
byte[] result;
135114

136115
try
137116
{
138-
LogOutput($"Generating pdf from url {url} ...");
139-
140-
var fileName = $"{Guid.NewGuid().ToString().ToLower()}";
141-
var dirSeparator = Path.DirectorySeparatorChar;
142-
143-
var outputFileName = $"{fileName}.pdf";
144-
145-
var outputFullName = Path.Combine(_libDir, outputFileName);
117+
result = GeneratePdfFromUrlInternal(url).GetAwaiter().GetResult();
146118

147-
ExcuteCommand($"python.exe weasyprint.exe {url} {outputFileName} ");
148-
149-
result = File.ReadAllBytes(outputFullName);
150-
151-
if (File.Exists(outputFullName))
152-
File.Delete(outputFullName);
153-
154-
LogOutput("Pdf generated successfully");
119+
return result;
155120

156121
}
157122
catch (Exception ex)
158123
{
159-
OnDataError?.Invoke(new OutputEventArgs(ex.ToString()));
124+
LogError(ex.ToString());
125+
throw new WeasyPrintException(ex.Message, ex);
160126
}
161-
162-
return result;
163127
}
164128

165-
public void GeneratePdfFromUrl(string url, string outputFilePath)
129+
public async Task<byte[]> GeneratePdfFromUrlAsync(string url)
166130
{
167-
if (!CheckFiles())
168-
InitFiles();
131+
byte[] result;
169132

170133
try
171134
{
172-
LogOutput($"Generating pdf from url {url} ...");
173-
174-
ExcuteCommand($"python.exe weasyprint.exe {url} {outputFilePath} ");
175-
176-
LogOutput("Pdf generated successfully");
135+
result = await GeneratePdfFromUrlInternal(url);
177136

137+
return result;
178138
}
179139
catch (Exception ex)
180140
{
181-
OnDataError?.Invoke(new OutputEventArgs(ex.ToString()));
182-
}
141+
LogError(ex.ToString());
183142

143+
throw new WeasyPrintException(ex.Message, ex);
144+
}
184145
}
185146

186147
private async Task<byte[]> GeneratePdfInternal(string htmlText)
@@ -218,125 +179,54 @@ await _fileManager.Delete(outputFileName)
218179
return result;
219180
}
220181

221-
private async Task EnsureFilesExisted()
222-
{
223-
if (!_fileManager.IsFilesExsited())
224-
await _fileManager.InitFilesAsync();
225-
}
226-
227-
private void ExcuteCommand(string cmd)
228-
{
229-
InitProccess();
230-
231-
_nativeProccess.StartInfo.Arguments = $@"/c {cmd}";
232-
233-
_nativeProccess.Start();
234-
235-
_nativeProccess.BeginOutputReadLine();
236-
_nativeProccess.BeginErrorReadLine();
237-
238-
_nativeProccess.WaitForExit();
239-
240-
}
241-
242-
private bool CheckFiles()
243-
{
244-
LogOutput("Checking files ...");
245-
246-
if (!Directory.Exists(_libDir))
247-
return false;
248-
249-
var files = Directory.GetFiles(_libDir);
250-
251-
if (files.Count() < 22)
252-
return false;
253-
254-
var containPython = files.Where(a => a.Contains("python.exe")).FirstOrDefault() != null;
255-
256-
if (!containPython)
257-
return false;
258-
259-
return true;
260-
}
261-
262-
private void InitFiles()
182+
private async Task GeneratePdfInternal(string inputPathFile, string outputPathFile)
263183
{
264-
LogOutput($"Checking {_libDir} direcoty");
265-
266-
if (!Directory.Exists(_libDir))
267-
{
268-
LogOutput("Creating direcotry");
269-
270-
Directory.CreateDirectory(_libDir);
271-
}
272-
else
273-
{
274-
LogOutput("Deleting corrupted files ...");
275-
276-
Directory.Delete(_libDir, true);
277-
278-
Directory.CreateDirectory(_libDir);
279-
}
280-
281-
var filesData = FileResx.libCompress;
282-
283-
var zipFileName = Path.Combine(_libDir, "weasyFile.zip");
284-
285-
File.WriteAllBytes(zipFileName, filesData);
184+
if (!File.Exists(inputPathFile))
185+
throw new FileNotFoundException();
286186

287-
LogOutput("Extracting files ...");
187+
await EnsureFilesExisted()
188+
.ConfigureAwait(false);
288189

289-
ZipFile.ExtractToDirectory(zipFileName, _libDir);
190+
var cmd = $"/c python.exe scripts/weasyprint.exe {inputPathFile} {outputPathFile} -e utf8";
290191

291-
LogOutput($"Deleting {zipFileName}");
192+
var workingDir = _fileManager.FolderPath;
292193

293-
File.Delete(zipFileName);
194+
await _invoker.ExcuteAsync(workingDir, "cmd.exe", cmd)
195+
.ConfigureAwait(false);
294196
}
295197

296-
private void InitProccess()
198+
private async Task<byte[]> GeneratePdfFromUrlInternal(string url)
297199
{
298-
KillProc();
200+
byte[] result;
299201

300-
var workingDir = _libDir;
202+
await EnsureFilesExisted()
203+
.ConfigureAwait(false);
301204

302-
_nativeProccess = new Process();
205+
var fileName = $"{Guid.NewGuid().ToString().ToLower()}.pdf";
303206

304-
_nativeProccess.StartInfo.FileName = @"cmd.exe";
207+
var outputFileName = Path.Combine(_fileManager.FolderPath, $"{fileName}");
305208

306-
_nativeProccess.StartInfo.EnvironmentVariables["PATH"] = "gtk3;%PATH%";
209+
var cmd = $"/c python.exe scripts/weasyprint.exe {url} {outputFileName} -e utf8";
307210

308-
_nativeProccess.StartInfo.EnvironmentVariables["FONTCONFIG_FILE"] = $"{workingDir}\\gtk3\\fonts.config";
211+
var workingDir = _fileManager.FolderPath;
309212

310-
_nativeProccess.StartInfo.WorkingDirectory = workingDir;
311-
_nativeProccess.StartInfo.UseShellExecute = false;
312-
_nativeProccess.StartInfo.RedirectStandardInput = true;
313-
_nativeProccess.StartInfo.RedirectStandardOutput = true;
314-
_nativeProccess.StartInfo.RedirectStandardError = true;
315-
_nativeProccess.StartInfo.CreateNoWindow = true;
213+
await _invoker.ExcuteAsync(workingDir, "cmd.exe", cmd)
214+
.ConfigureAwait(false);
316215

317-
_nativeProccess.OutputDataReceived += OnOutputDataReceived;
318-
_nativeProccess.ErrorDataReceived += OnErrorDataReceived;
319-
_nativeProccess.Exited += OnExited;
320216

321-
}
322-
323-
private void OnExited(object sender, EventArgs e)
324-
{
325-
Debug.WriteLine("Proccess exited");
326-
}
217+
result = await _fileManager.ReadFile(fileName)
218+
.ConfigureAwait(false);
327219

328-
private void OnErrorDataReceived(object sender, DataReceivedEventArgs e)
329-
{
330-
LogError(e.Data);
220+
await _fileManager.Delete(fileName)
221+
.ConfigureAwait(false);
331222

332-
Debug.WriteLine($"Error: {e.Data}");
223+
return result;
333224
}
334225

335-
private void OnOutputDataReceived(object sender, DataReceivedEventArgs e)
226+
private async Task EnsureFilesExisted()
336227
{
337-
LogOutput(e.Data);
338-
339-
Debug.WriteLine(e.Data);
228+
if (!_fileManager.IsFilesExsited())
229+
await _fileManager.InitFilesAsync();
340230
}
341231

342232
private void LogOutput(string data)
@@ -361,28 +251,9 @@ private void LogError(string data)
361251

362252
public void Dispose()
363253
{
364-
KillProc();
365-
366254
_invoker.Dispose();
367255
}
368256

369-
private void KillProc()
370-
{
371-
if (_nativeProccess != null)
372-
{
373-
try
374-
{
375-
_nativeProccess.Kill();
376-
}
377-
catch
378-
{
379-
380-
}
381-
382-
_nativeProccess.Dispose();
383-
}
384-
}
385-
386257
private void SetEnviromentVariables()
387258
{
388259
var variables = new Dictionary<string, string>()

0 commit comments

Comments
 (0)