forked from microsoft/markitdown
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathPdfConverter.cs
More file actions
349 lines (285 loc) · 10.7 KB
/
PdfConverter.cs
File metadata and controls
349 lines (285 loc) · 10.7 KB
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ManagedCode.MimeTypes;
using MarkItDown;
using PDFtoImage;
using SkiaSharp;
using UglyToad.PdfPig;
namespace MarkItDown.Converters;
/// <summary>
/// Converter for PDF files to Markdown using PdfPig for text extraction and optional page image rendering.
/// </summary>
public sealed class PdfConverter : IDocumentConverter
{
private static readonly HashSet<string> AcceptedExtensions = new(StringComparer.OrdinalIgnoreCase)
{
".pdf"
};
private static readonly HashSet<string> AcceptedMimeTypes = new(StringComparer.OrdinalIgnoreCase)
{
MimeHelper.PDF
};
private readonly IPdfTextExtractor textExtractor;
private readonly IPdfImageRenderer imageRenderer;
public PdfConverter()
: this(new PdfPigTextExtractor(), new PdfToImageRenderer())
{
}
internal PdfConverter(IPdfTextExtractor textExtractor, IPdfImageRenderer imageRenderer)
{
this.textExtractor = textExtractor ?? throw new ArgumentNullException(nameof(textExtractor));
this.imageRenderer = imageRenderer ?? throw new ArgumentNullException(nameof(imageRenderer));
}
public int Priority => 200; // Between HTML and plain text
public bool AcceptsInput(StreamInfo streamInfo)
{
var normalizedMime = MimeTypeUtilities.NormalizeMime(streamInfo);
var extension = streamInfo.Extension?.ToLowerInvariant();
if (extension is not null && AcceptedExtensions.Contains(extension))
{
return true;
}
if (normalizedMime is not null && AcceptedMimeTypes.Contains(normalizedMime))
{
return true;
}
return streamInfo.MimeType is not null && AcceptedMimeTypes.Contains(streamInfo.MimeType);
}
public bool Accepts(Stream stream, StreamInfo streamInfo, CancellationToken cancellationToken = default)
{
if (!AcceptsInput(streamInfo))
return false;
if (stream.CanSeek && stream.Length > 4)
{
var originalPosition = stream.Position;
try
{
stream.Position = 0;
Span<byte> buffer = stackalloc byte[4];
var bytesRead = stream.Read(buffer);
stream.Position = originalPosition;
if (bytesRead == 4)
{
return buffer[0] == '%' && buffer[1] == 'P' && buffer[2] == 'D' && buffer[3] == 'F';
}
}
catch
{
stream.Position = originalPosition;
}
}
return true;
}
public async Task<DocumentConverterResult> ConvertAsync(Stream stream, StreamInfo streamInfo, CancellationToken cancellationToken = default)
{
try
{
var pdfBytes = await ReadAllBytesAsync(stream, cancellationToken).ConfigureAwait(false);
var extractedText = await textExtractor.ExtractTextAsync(pdfBytes, cancellationToken).ConfigureAwait(false);
var pageImages = await imageRenderer.RenderImagesAsync(pdfBytes, cancellationToken).ConfigureAwait(false);
var markdown = AppendImages(ConvertTextToMarkdown(extractedText), pageImages);
var title = ExtractTitle(extractedText);
return new DocumentConverterResult(markdown, title);
}
catch (Exception ex) when (!(ex is MarkItDownException))
{
throw new FileConversionException($"Failed to convert PDF file: {ex.Message}", ex);
}
}
private static async Task<byte[]> ReadAllBytesAsync(Stream stream, CancellationToken cancellationToken)
{
if (stream is MemoryStream existingMemory && stream.CanSeek)
{
stream.Position = 0;
return existingMemory.ToArray();
}
await using var memory = new MemoryStream();
if (stream.CanSeek)
{
stream.Position = 0;
}
await stream.CopyToAsync(memory, cancellationToken).ConfigureAwait(false);
return memory.ToArray();
}
private static string ConvertTextToMarkdown(string text)
{
if (string.IsNullOrWhiteSpace(text))
return string.Empty;
var lines = text.Split('\n', StringSplitOptions.None);
var result = new StringBuilder();
foreach (var line in lines)
{
var trimmedLine = line.Trim();
if (string.IsNullOrWhiteSpace(trimmedLine))
{
result.AppendLine();
continue;
}
if (trimmedLine == "---")
{
result.AppendLine("\n---\n");
continue;
}
if (IsLikelyHeader(trimmedLine))
{
result.AppendLine($"## {trimmedLine}");
result.AppendLine();
continue;
}
if (IsListItem(trimmedLine))
{
result.AppendLine(ConvertListItem(trimmedLine));
continue;
}
result.AppendLine(trimmedLine);
}
return result.ToString().Trim();
}
private static bool IsLikelyHeader(string line)
{
if (line.Length > 80 || line.EndsWith('.') || line.EndsWith(','))
return false;
var upperCount = line.Count(char.IsUpper);
var lowerCount = line.Count(char.IsLower);
return upperCount > lowerCount && upperCount > 2;
}
private static bool IsListItem(string line)
{
if (line.StartsWith("•") || line.StartsWith("-") || line.StartsWith("*"))
return true;
var match = System.Text.RegularExpressions.Regex.Match(line, @"^\d+\.?\s+");
return match.Success;
}
private static string ConvertListItem(string line)
{
if (line.StartsWith("•"))
return line.Replace("•", "-");
var match = System.Text.RegularExpressions.Regex.Match(line, @"^(\d+)\.?\s+(.*)");
return match.Success ? $"{match.Groups[1].Value}. {match.Groups[2].Value}" : line;
}
private static string? ExtractTitle(string text)
{
if (string.IsNullOrWhiteSpace(text))
return null;
var lines = text.Split('\n', StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines.Take(10))
{
var trimmedLine = line.Trim();
if (trimmedLine.Length > 5 && trimmedLine.Length < 100 &&
!trimmedLine.Contains("Page ") &&
!trimmedLine.All(char.IsDigit))
{
return trimmedLine;
}
}
return null;
}
private static string AppendImages(string markdown, IReadOnlyList<string> images)
{
if (images.Count == 0)
{
return markdown;
}
var builder = new StringBuilder(markdown.Length + images.Count * 64);
if (!string.IsNullOrWhiteSpace(markdown))
{
builder.Append(markdown.TrimEnd());
builder.AppendLine();
builder.AppendLine();
}
builder.AppendLine("## Page Images");
builder.AppendLine();
for (var i = 0; i < images.Count; i++)
{
builder.Append(";
builder.Append(images[i]);
builder.Append(")");
builder.AppendLine();
builder.AppendLine();
}
return builder.ToString().TrimEnd();
}
internal interface IPdfTextExtractor
{
Task<string> ExtractTextAsync(byte[] pdfBytes, CancellationToken cancellationToken);
}
internal interface IPdfImageRenderer
{
Task<IReadOnlyList<string>> RenderImagesAsync(byte[] pdfBytes, CancellationToken cancellationToken);
}
private sealed class PdfPigTextExtractor : IPdfTextExtractor
{
public Task<string> ExtractTextAsync(byte[] pdfBytes, CancellationToken cancellationToken)
{
var builder = new StringBuilder();
using var pdfDocument = PdfDocument.Open(pdfBytes);
for (var pageNumber = 1; pageNumber <= pdfDocument.NumberOfPages; pageNumber++)
{
cancellationToken.ThrowIfCancellationRequested();
var page = pdfDocument.GetPage(pageNumber);
var pageText = page.Text;
if (string.IsNullOrWhiteSpace(pageText))
{
continue;
}
if (builder.Length > 0)
{
builder.AppendLine("\n---\n");
}
builder.AppendLine(pageText.Trim());
}
return Task.FromResult(builder.ToString());
}
}
private sealed class PdfToImageRenderer : IPdfImageRenderer
{
public Task<IReadOnlyList<string>> RenderImagesAsync(byte[] pdfBytes, CancellationToken cancellationToken)
{
if (!(OperatingSystem.IsWindows() || OperatingSystem.IsLinux() || OperatingSystem.IsMacOS() ||
OperatingSystem.IsMacCatalyst() || OperatingSystem.IsAndroid() || OperatingSystem.IsIOS()))
{
return Task.FromResult<IReadOnlyList<string>>(Array.Empty<string>());
}
return RenderOnSupportedPlatformsAsync(pdfBytes, cancellationToken);
}
[SupportedOSPlatform("windows")]
[SupportedOSPlatform("linux")]
[SupportedOSPlatform("macos")]
[SupportedOSPlatform("maccatalyst")]
[SupportedOSPlatform("android")]
[SupportedOSPlatform("ios")]
private static Task<IReadOnlyList<string>> RenderOnSupportedPlatformsAsync(byte[] pdfBytes, CancellationToken cancellationToken)
{
var images = new List<string>();
var options = new RenderOptions
{
Dpi = 144,
WithAnnotations = true,
WithAspectRatio = true,
AntiAliasing = PdfAntiAliasing.All,
};
#pragma warning disable CA1416
foreach (var bitmap in Conversion.ToImages(pdfBytes, password: null, options))
{
cancellationToken.ThrowIfCancellationRequested();
using var bmp = bitmap;
using var data = bmp.Encode(SKEncodedImageFormat.Png, quality: 90);
if (data is null)
{
continue;
}
images.Add(Convert.ToBase64String(data.Span));
}
#pragma warning restore CA1416
return Task.FromResult<IReadOnlyList<string>>(images);
}
}
}