-
Notifications
You must be signed in to change notification settings - Fork 249
/
Copy pathAltoXmlTextExporter.cs
411 lines (373 loc) · 17.5 KB
/
AltoXmlTextExporter.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
namespace UglyToad.PdfPig.DocumentLayoutAnalysis.Export
{
using Alto;
using Content;
using DocumentLayoutAnalysis;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;
using UglyToad.PdfPig.DocumentLayoutAnalysis.PageSegmenter;
using UglyToad.PdfPig.Graphics;
using Util;
/// <summary>
/// Alto 4.1 (XML) text exporter.
/// <para>See https://github.com/altoxml/schema </para>
/// </summary>
public sealed class AltoXmlTextExporter : ITextExporter
{
private readonly IPageSegmenter pageSegmenter;
private readonly IWordExtractor wordExtractor;
private readonly Func<string, string> invalidCharacterHandler;
private readonly double scale;
private readonly string indentChar;
private int pageCount;
private int pageSpaceCount;
private int graphicalElementCount;
private int illustrationCount;
private int textBlockCount;
private int textLineCount;
private int stringCount;
private int glyphCount;
/// <inheritdoc/>
public InvalidCharStrategy InvalidCharStrategy { get; }
/// <summary>
/// Alto 4.1 (XML).
/// <para>See https://github.com/altoxml/schema </para>
/// </summary>
/// <param name="wordExtractor">Extractor used to identify words in the document.</param>
/// <param name="pageSegmenter">Segmenter used to split page into blocks.</param>
/// <param name="scale">Scale multiplier to apply to output document, defaults to 1.</param>
/// <param name="indentChar">Character to use for indentation, defaults to tab.</param>
/// <param name="invalidCharacterHandler">How to handle invalid characters.</param>
public AltoXmlTextExporter(IWordExtractor wordExtractor, IPageSegmenter pageSegmenter,
double scale, string indentChar,
Func<string, string> invalidCharacterHandler)
: this(wordExtractor, pageSegmenter, scale, indentChar,
InvalidCharStrategy.Custom, invalidCharacterHandler)
{ }
/// <summary>
/// Alto 4.1 (XML).
/// <para>See https://github.com/altoxml/schema </para>
/// </summary>
/// <param name="wordExtractor">Extractor used to identify words in the document.</param>
/// <param name="pageSegmenter">Segmenter used to split page into blocks.</param>
/// <param name="scale">Scale multiplier to apply to output document, defaults to 1.</param>
/// <param name="indentChar">Character to use for indentation, defaults to tab.</param>
/// <param name="invalidCharacterStrategy">How to handle invalid characters.</param>
public AltoXmlTextExporter(IWordExtractor wordExtractor, IPageSegmenter pageSegmenter,
double scale = 1, string indentChar = "\t",
InvalidCharStrategy invalidCharacterStrategy = InvalidCharStrategy.DoNotCheck)
: this(wordExtractor, pageSegmenter, scale, indentChar,
invalidCharacterStrategy, null)
{ }
private AltoXmlTextExporter(IWordExtractor wordExtractor, IPageSegmenter pageSegmenter,
double scale, string indentChar,
InvalidCharStrategy invalidCharacterStrategy,
Func<string, string> invalidCharacterHandler)
{
this.wordExtractor = wordExtractor;
this.pageSegmenter = pageSegmenter;
this.scale = scale;
this.indentChar = indentChar ?? string.Empty;
InvalidCharStrategy = invalidCharacterStrategy;
if (invalidCharacterHandler is null)
{
this.invalidCharacterHandler = TextExporterHelper.GetXmlInvalidCharHandler(InvalidCharStrategy);
}
else
{
this.invalidCharacterHandler = invalidCharacterHandler;
}
}
/// <summary>
/// Get the Alto (XML) string of the pages layout.
/// </summary>
/// <param name="document">The document to extract page layouts from.</param>
/// <param name="includePaths">Draw PdfPaths present in the page.</param>
#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Members from AltoDocument may be trimmed if not referenced directly")]
#endif
public string Get(PdfDocument document, bool includePaths = false)
{
var altoDocument = CreateAltoDocument("unknown");
altoDocument.Layout.Pages = document.GetPages().Select(x => ToAltoPage(x, includePaths)).ToArray();
return Serialize(altoDocument);
}
/// <summary>
/// Get the Alto (XML) string of the page layout. Excludes <see cref="T:UglyToad.PdfPig.Geometry.PdfSubpath" />s.
/// </summary>
/// <param name="page">The page to export the XML layout for.</param>
#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Members from AltoDocument may be trimmed if not referenced directly")]
#endif
public string Get(Page page) => Get(page, false);
/// <summary>
/// Get the Alto (XML) string of the page layout.
/// </summary>
/// <param name="page">The page to export the XML layout for.</param>
/// <param name="includePaths">Whether the output should include the PdfPaths present in the page.</param>
#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Members from AltoDocument may be trimmed if not referenced directly")]
#endif
public string Get(Page page, bool includePaths)
{
var document = CreateAltoDocument("unknown");
document.Layout.Pages = new[] { ToAltoPage(page, includePaths) };
return Serialize(document);
}
/// <summary>
/// Create an empty <see cref="AltoDocument"/>.
/// </summary>
private AltoDocument CreateAltoDocument(string fileName)
{
return new AltoDocument
{
Layout = new AltoDocument.AltoLayout
{
StyleRefs = null
},
Description = GetAltoDescription(fileName),
SchemaVersion = "4",
};
}
private AltoDocument.AltoPage ToAltoPage(Page page, bool includePaths)
{
pageCount = page.Number;
pageSpaceCount++;
var altoPage = new AltoDocument.AltoPage
{
Height = (float)Math.Round(page.Height * scale),
Width = (float)Math.Round(page.Width * scale),
Accuracy = float.NaN,
Quality = AltoDocument.AltoQuality.OK,
QualityDetail = null,
BottomMargin = null,
LeftMargin = null,
RightMargin = null,
TopMargin = null,
Pc = float.NaN,
PhysicalImgNr = page.Number,
PrintedImgNr = null,
PageClass = null,
Position = AltoDocument.AltoPosition.Cover,
Processing = null,
ProcessingRefs = null,
StyleRefs = null,
PrintSpace = new AltoDocument.AltoPageSpace
{
Height = (float)Math.Round(page.Height * scale), // TBD
Width = (float)Math.Round(page.Width * scale), // TBD
VerticalPosition = 0f, // TBD
HorizontalPosition = 0f, // TBD
ComposedBlocks = null, // TBD
GraphicalElements = null, // TBD
Illustrations = null, // TBD
ProcessingRefs = null, // TBD
StyleRefs = null, // TBD
Id = "P" + pageCount + "_PS" + pageSpaceCount.ToString("#00000")
},
Id = "P" + pageCount
};
var words = page.GetWords(wordExtractor);
altoPage.PrintSpace.TextBlock = pageSegmenter.GetBlocks(words).Select(b => ToAltoTextBlock(b, page.Height)).ToArray();
altoPage.PrintSpace.Illustrations = page.GetImages().Select(i => ToAltoIllustration(i, page.Height)).ToArray();
if (includePaths)
{
altoPage.PrintSpace.GraphicalElements = page.Paths
.Select(p => ToAltoGraphicalElement(p, page.Height))
.ToArray();
}
return altoPage;
}
private AltoDocument.AltoGraphicalElement ToAltoGraphicalElement(PdfPath pdfPath, double height)
{
graphicalElementCount++;
var rectangle = pdfPath.GetBoundingRectangle();
if (rectangle.HasValue)
{
return new AltoDocument.AltoGraphicalElement
{
VerticalPosition = (float)Math.Round((height - rectangle.Value.Top) * scale),
HorizontalPosition = (float)Math.Round(rectangle.Value.Left * scale),
Height = (float)Math.Round(rectangle.Value.Height * scale),
Width = (float)Math.Round(rectangle.Value.Width * scale),
Rotation = 0,
StyleRefs = null,
TagRefs = null,
Title = null,
Type = null,
Id = "P" + pageCount + "_GE" + graphicalElementCount.ToString("#00000")
};
}
return null;
}
private AltoDocument.AltoIllustration ToAltoIllustration(IPdfImage pdfImage, double height)
{
illustrationCount++;
var rectangle = pdfImage.Bounds;
return new AltoDocument.AltoIllustration
{
VerticalPosition = (float)Math.Round((height - rectangle.Top) * scale),
HorizontalPosition = (float)Math.Round(rectangle.Left * scale),
Height = (float)Math.Round(rectangle.Height * scale),
Width = (float)Math.Round(rectangle.Width * scale),
FileId = "",
Rotation = 0,
Id = "P" + pageCount + "_I" + illustrationCount.ToString("#00000")
};
}
private AltoDocument.AltoTextBlock ToAltoTextBlock(TextBlock textBlock, double height)
{
textBlockCount++;
return new AltoDocument.AltoTextBlock
{
VerticalPosition = (float)Math.Round((height - textBlock.BoundingBox.Top) * scale),
HorizontalPosition = (float)Math.Round(textBlock.BoundingBox.Left * scale),
Height = (float)Math.Round(textBlock.BoundingBox.Height * scale),
Width = (float)Math.Round(textBlock.BoundingBox.Width * scale),
Rotation = 0,
TextLines = textBlock.TextLines.Select(l => ToAltoTextLine(l, height)).ToArray(),
StyleRefs = null,
TagRefs = null,
Title = null,
Type = null,
Id = "P" + pageCount + "_TB" + textBlockCount.ToString("#00000")
};
}
private AltoDocument.AltoTextBlockTextLine ToAltoTextLine(TextLine textLine, double height)
{
textLineCount++;
var strings = textLine.Words
.Select(w => ToAltoString(w, height)).ToArray();
return new AltoDocument.AltoTextBlockTextLine
{
VerticalPosition = (float)Math.Round((height - textLine.BoundingBox.Top) * scale),
HorizontalPosition = (float)Math.Round(textLine.BoundingBox.Left * scale),
Height = (float)Math.Round(textLine.BoundingBox.Height * scale),
Width = (float)Math.Round(textLine.BoundingBox.Width * scale),
BaseLine = float.NaN,
Strings = strings,
Language = null,
StyleRefs = null,
TagRefs = null,
Id = "P" + pageCount + "_TL" + textLineCount.ToString("#00000")
};
}
private AltoDocument.AltoString ToAltoString(Word word, double height)
{
stringCount++;
var glyphs = word.Letters.Select(l => ToAltoGlyph(l, height)).ToArray();
return new AltoDocument.AltoString
{
VerticalPosition = (float)Math.Round((height - word.BoundingBox.Top) * scale),
HorizontalPosition = (float)Math.Round(word.BoundingBox.Left * scale),
Height = (float)Math.Round(word.BoundingBox.Height * scale),
Width = (float)Math.Round(word.BoundingBox.Width * scale),
Glyph = glyphs,
Cc = string.Join("", glyphs.Select(g => 9f * (1f - g.Gc))), // from 0->1 to 9->0
Content = invalidCharacterHandler(word.Text),
Language = null,
StyleRefs = null,
SubsContent = null,
TagRefs = null,
Wc = float.NaN,
Id = "P" + pageCount + "_ST" + stringCount.ToString("#00000")
};
}
private AltoDocument.AltoGlyph ToAltoGlyph(Letter letter, double height)
{
glyphCount++;
return new AltoDocument.AltoGlyph
{
VerticalPosition = (float)Math.Round((height - letter.GlyphRectangle.Top) * scale),
HorizontalPosition = (float)Math.Round(letter.GlyphRectangle.Left * scale),
Height = (float)Math.Round(letter.GlyphRectangle.Height * scale),
Width = (float)Math.Round(letter.GlyphRectangle.Width * scale),
Gc = 1.0f,
Content = invalidCharacterHandler(letter.Value),
Id = "P" + pageCount + "_ST" + stringCount.ToString("#00000") + "_G" + glyphCount.ToString("#00")
};
}
private AltoDocument.AltoDescription GetAltoDescription(string fileName)
{
var processing = new AltoDocument.AltoDescriptionProcessing
{
ProcessingAgency = null,
ProcessingCategory = AltoDocument.AltoProcessingCategory.Other,
ProcessingDateTime = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture),
ProcessingSoftware = new AltoDocument.AltoProcessingSoftware
{
SoftwareName = "PdfPig",
SoftwareCreator = "https://github.com/UglyToad/PdfPig",
ApplicationDescription = "Read and extract text and other content from PDFs in C# (port of PdfBox)",
SoftwareVersion = "x.x.xx"
},
ProcessingStepDescription = null,
ProcessingStepSettings = pageSegmenter.GetType().Name + "|" + wordExtractor.GetType().Name,
Id = "P" + pageCount + "_D1"
};
var documentIdentifier = new AltoDocument.AltoDocumentIdentifier
{
DocumentIdentifierLocation = null,
Value = null
};
var fileIdentifier = new AltoDocument.AltoFileIdentifier
{
FileIdentifierLocation = null,
Value = null
};
return new AltoDocument.AltoDescription
{
MeasurementUnit = AltoDocument.AltoMeasurementUnit.Pixel,
Processings = new[] { processing },
SourceImageInformation = new AltoDocument.AltoSourceImageInformation
{
DocumentIdentifiers = new[] { documentIdentifier },
FileIdentifiers = new[] { fileIdentifier },
FileName = fileName
}
};
}
#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Members from AltoDocument may be trimmed if not referenced directly")]
#endif
private string Serialize(AltoDocument altoDocument)
{
var serializer = new XmlSerializer(typeof(AltoDocument));
var settings = new XmlWriterSettings
{
Encoding = System.Text.Encoding.UTF8,
Indent = true,
IndentChars = indentChar,
CheckCharacters = InvalidCharStrategy != InvalidCharStrategy.DoNotCheck,
};
using (var memoryStream = new System.IO.MemoryStream())
using (var xmlWriter = XmlWriter.Create(memoryStream, settings))
{
serializer.Serialize(xmlWriter, altoDocument);
return System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
}
}
/// <summary>
/// Deserialize an <see cref="AltoDocument"/> from a given Alto format XML document.
/// </summary>
#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Members from AltoDocument may be trimmed if not referenced directly")]
#endif
public static AltoDocument Deserialize(string xmlPath)
{
var serializer = new XmlSerializer(typeof(AltoDocument));
var settings = new XmlReaderSettings()
{
CheckCharacters = false
};
using (var reader = XmlReader.Create(xmlPath, settings))
{
return (AltoDocument)serializer.Deserialize(reader);
}
}
}
}