-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPrintHelper.Android.cs
105 lines (84 loc) · 2.88 KB
/
PrintHelper.Android.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
#if ANDROID
using Android.Content;
using Android.OS;
using Android.Print;
using Java.IO;
namespace DocumentPrinting.Helpers;
public class PrintHelper
{
// Credit goes to https://github.com/Cywizz for abstracting this into a more user-friendly manner.
public Task PrintAsync(Stream fileStream, string fileName)
{
if (fileStream.CanSeek)
fileStream.Position = 0;
string createdFilePath = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), fileName);
//Save the stream to the created file
using (var dest = System.IO.File.OpenWrite(createdFilePath))
{
fileStream.CopyTo(dest);
}
if (Platform.CurrentActivity == null)
return Task.FromException<long>(new Exception("The CurrentActivity is null."));
var printManager = (PrintManager)Platform.CurrentActivity.GetSystemService(Context.PrintService);
// Now we can use the preexisting print helper class
var utility = new PrintUtility(createdFilePath);
printManager?.Print(createdFilePath, utility, null);
return Task.CompletedTask;
}
}
public class PrintUtility : PrintDocumentAdapter
{
public string PrintFileName { get; set; }
public PrintUtility(string printFileName)
{
PrintFileName = printFileName;
}
public override void OnLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras)
{
if (cancellationSignal.IsCanceled)
{
callback.OnLayoutCancelled();
return;
}
var pdi = new PrintDocumentInfo.Builder(PrintFileName).SetContentType(PrintContentType.Document).Build();
callback.OnLayoutFinished(pdi, true);
}
public override void OnWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback)
{
InputStream input = null;
OutputStream output = null;
try
{
input = new FileInputStream(PrintFileName);
output = new FileOutputStream(destination.FileDescriptor);
var buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.Read(buf)) > 0)
{
output.Write(buf, 0, bytesRead);
}
callback.OnWriteFinished(new[] { PageRange.AllPages });
}
catch (Java.IO.FileNotFoundException ee)
{
//Catch
}
catch (Exception e)
{
//Catch
}
finally
{
try
{
input?.Close();
output?.Close();
}
catch (Java.IO.IOException e)
{
e.PrintStackTrace();
}
}
}
}
#endif