-
Notifications
You must be signed in to change notification settings - Fork 1
/
FlowDocumentConverter.cs
264 lines (190 loc) · 7.23 KB
/
FlowDocumentConverter.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Documents;
using System.IO;
using System.IO.Packaging;
using System.Windows.Xps.Packaging;
using System.Windows.Xps.Serialization;
using System.Xml.Linq;
using System.Xaml;
using System.Threading.Tasks;
using System.Net;
using System.Diagnostics;
using System.Windows.Media;
using System.Windows;
namespace NeuroSpeech.XamlToPDF.Xaml
{
public class FlowDocumentPackage : IDisposable
{
private static string _TempPath = null;
public static string TempPath {
get {
return _TempPath ?? Path.GetTempPath();
}
set {
_TempPath = value;
}
}
private FlowDocument flowDoc;
//private XpsSerializationManager XSrm;
//private XpsPackagingPolicy XPolicy;
private XpsDocument XpsDoc;
//private Package Package;
//private Stream Stream;
private DirectoryInfo TempFolder;
//private string pack;
public List<IDisposable> toDispose;
public FlowDocumentPackage(string xamlFlowDocument)
{
toDispose = new List<IDisposable>();
TempFolder = new DirectoryInfo(TempPath + "\\XamlToPDF\\" + DateTime.Now.Ticks.ToString());
if (!TempFolder.Exists)
TempFolder.Create();
/*Stream = File.Create(TempFolder.FullName + "\\a.xps");
toDispose.Add(Stream);
Package = Package.Open(Stream, FileMode.Create, FileAccess.ReadWrite);
toDispose.Add(Package);
pack = "pack://" + DateTime.Now.Ticks + ".xps";
PackageStore.AddPackage(new Uri(pack), Package);
XpsDoc = new XpsDocument(Package, CompressionOption.NotCompressed, pack);*/
XpsDoc = new XpsDocument(TempFolder.FullName + "\\a.xps", FileAccess.ReadWrite, CompressionOption.NotCompressed);
toDispose.Add(new InlineDisposable(()=> XpsDoc.Close()));
System.Windows.Xps.XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(XpsDoc);
xamlFlowDocument = ReplaceImages(writer, xamlFlowDocument);
flowDoc = XamlServices.Parse(xamlFlowDocument) as FlowDocument;
IDocumentPaginatorSource src = flowDoc as IDocumentPaginatorSource;
if (double.IsNaN(flowDoc.PageHeight))
{
flowDoc.PageHeight = 792;
}
if (double.IsNaN(flowDoc.PageWidth))
{
flowDoc.PageWidth = 612;
}
/*XPolicy = new XpsPackagingPolicy(XpsDoc);
toDispose.Add(XPolicy);
XSrm = new XpsSerializationManager(XPolicy, false);
toDispose.Add(XSrm);*/
DocumentPaginator pgn = src.DocumentPaginator;
//XSrm.SaveAsXaml(pgn);
writer.Write(pgn);
var seq = XpsDoc.GetFixedDocumentSequence();
DocumentReference reff = seq.References.First();
Document = reff.GetDocument(true);
}
private Dictionary<string, DownloadItem> Cache = new Dictionary<string, DownloadItem>();
#region private string ReplaceImages(string xamlFlowDocument)
private string ReplaceImages(System.Windows.Xps.XpsDocumentWriter writer, string xamlFlowDocument)
{
XDocument doc = XDocument.Parse(xamlFlowDocument);
foreach (XElement img in doc.Descendants().Where(x => x.Name.LocalName == "Image" && x.Attributes().Any(a=>a.Name.LocalName == "Source") )) {
var at = img.Attributes().FirstOrDefault(x => x.Name.LocalName == "Source");
if (at == null)
continue;
string url = at.Value;
//if (url.StartsWith("http://") || url.StartsWith("https://"))
{
string urlKey = at.Value.ToLower();
DownloadItem file = null;
if (!Cache.TryGetValue(urlKey, out file))
{
file = new DownloadItem {
FilePath = TempFolder + "\\" + Cache.Count + ".dat",
Url = url
};
Cache[urlKey] = file;
}
file.Nodes.Add(img);
}
}
Parallel.ForEach(Cache.Values, DownloadFile);
foreach (var item in Cache.Values)
{
//var pp = Package.CreatePart(new Uri(item.PackgeUri, UriKind.Relative), "image/jpeg", CompressionOption.NotCompressed);
//using (Stream ss = pp.GetStream(FileMode.OpenOrCreate, FileAccess.ReadWrite)) {
// using (FileStream fs = File.OpenRead(item.FilePath)) {
// fs.CopyTo(ss);
// }
//}
//Trace.WriteLine(pack + item.PackgeUri);
////Package.CreateRelationship(new Uri(pack + item.PackgeUri), TargetMode.External, "http://schemas.microsoft.com/xps/2005/06/required-resource");
//foreach (var node in item.Nodes)
//{
// node.Value = pack + ",,," + item.PackgeUri;
//}
foreach (var node in item.Nodes)
{
node.Name = XName.Get("InlineImage",node.Name.NamespaceName);
XCData d = new XCData(Convert.ToBase64String(File.ReadAllBytes(item.FilePath)));
node.Add(d);
XAttribute a = node.Attributes().FirstOrDefault(x => x.Name.LocalName == "Source");
a.Remove();
}
}
using(StringWriter sw = new StringWriter()){
doc.Save(sw, SaveOptions.OmitDuplicateNamespaces);
xamlFlowDocument = sw.ToString();
};
return xamlFlowDocument;
}
#endregion
#region private void DownloadFile(string p,string p_2)
private void DownloadFile(DownloadItem item)
{
try {
string url = item.Url;
if (url.StartsWith("//"))
{
url = "http:" + url;
}
if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
using (WebClient client = new WebClient())
{
client.DownloadFile(item.Url, item.FilePath);
}
}
}
catch {
}
// check if zero sized file...
FileInfo info = new FileInfo(item.FilePath);
if (!info.Exists || info.Length == 0) {
// write empty file....
File.WriteAllBytes(item.FilePath, XResources.EmptyImageData);
}
}
#endregion
public FixedDocument Document { get; private set; }
#region public void Dispose()
public void Dispose()
{
if (toDispose.Count > 0)
{
//PackageStore.RemovePackage(new Uri(pack));
foreach (var item in toDispose.ToArray().Reverse())
{
item.Dispose();
}
try
{
TempFolder.Delete(true);
}
catch { }
}
}
#endregion
}
public class DownloadItem {
public DownloadItem()
{
Nodes = new List<XElement>();
}
public string PackgeUri { get; set; }
public List<XElement> Nodes { get; private set; }
public string Url { get; set; }
public string FilePath { get; set; }
}
}