-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPdfService.cs
More file actions
82 lines (67 loc) · 2.71 KB
/
PdfService.cs
File metadata and controls
82 lines (67 loc) · 2.71 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
using PdfiumViewer;
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace ShowWrite;
public static class PdfService
{
private const int HighDpi = 300;
private const int UltraHighDpi = 600;
public static List<string> ConvertPdfToImages(string pdfPath, string? outputDirectory = null, bool ultraHighQuality = false)
{
var imagePaths = new List<string>();
if (!File.Exists(pdfPath))
{
return imagePaths;
}
outputDirectory ??= Path.Combine(Path.GetTempPath(), "ShowWrite_PdfImages", Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(outputDirectory);
try
{
using var doc = PdfDocument.Load(pdfPath);
int pageCount = doc.PageCount;
var results = new string[pageCount];
int maxDegree = Math.Max(1, Environment.ProcessorCount - 1);
var semaphore = new SemaphoreSlim(maxDegree, maxDegree);
var tasks = new List<Task>();
int dpi = ultraHighQuality ? UltraHighDpi : HighDpi;
for (int pageIndex = 0; pageIndex < pageCount; pageIndex++)
{
int idx = pageIndex;
tasks.Add(Task.Run(async () =>
{
await semaphore.WaitAsync().ConfigureAwait(false);
try
{
var fileName = $"Page_{idx + 1:D04}.png";
var outputPath = Path.Combine(outputDirectory, fileName);
using var image = doc.Render(idx, dpi, dpi, PdfRenderFlags.CorrectFromDpi | PdfRenderFlags.Annotations | PdfRenderFlags.ForPrinting);
var encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = new EncoderParameter(Encoder.Compression, (long)EncoderValue.CompressionNone);
image.Save(outputPath, ImageFormat.Png);
results[idx] = outputPath;
}
finally
{
semaphore.Release();
}
}));
}
Task.WaitAll(tasks.ToArray());
imagePaths.AddRange(results.Where(p => !string.IsNullOrEmpty(p)));
}
catch (Exception ex)
{
Console.WriteLine($"PDF 转换错误: {ex.Message}");
}
return imagePaths;
}
public static List<string> ConvertPdfToImagesHighQuality(string pdfPath, string? outputDirectory = null)
{
return ConvertPdfToImages(pdfPath, outputDirectory, ultraHighQuality: true);
}
}