You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.7 KiB

5 months ago
5 months ago
5 months ago
  1. using PdfiumViewer;
  2. using System.Drawing.Imaging;
  3. using System.Drawing;
  4. using System;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7. using System.IO;
  8. using System.Collections.Generic;
  9. namespace Shentun.Utilities
  10. {
  11. public class PdfiumConverter
  12. {
  13. public static List<string> ConvertPdfToImages(string pdfBase64)
  14. {
  15. List<string> base64Images = new List<string>();
  16. //try
  17. //{
  18. if (pdfBase64.Contains("base64,"))
  19. {
  20. pdfBase64 = pdfBase64.Substring(pdfBase64.IndexOf(",") + 1);
  21. }
  22. // 将Base64字符串转换为字节数组
  23. byte[] pdfBytes = Convert.FromBase64String(pdfBase64);
  24. Stream pdfStream = new MemoryStream(pdfBytes);
  25. using var document = PdfDocument.Load(pdfStream);
  26. for (int i = 0; i < document.PageCount; i++)
  27. {
  28. // 将页面转换为图片
  29. using (Image image = document.Render(i, 600, 600, true))
  30. {
  31. // 将图片转换为Base64字符串
  32. string base64 = ImageToBase64(image, ImageFormat.Jpeg);
  33. base64Images.Add(base64);
  34. }
  35. }
  36. //}
  37. //catch (Exception ex)
  38. //{
  39. //}
  40. return base64Images;
  41. }
  42. private static string ImageToBase64(Image image, ImageFormat format)
  43. {
  44. using (MemoryStream ms = new MemoryStream())
  45. {
  46. image.Save(ms, format);
  47. byte[] imageBytes = ms.ToArray();
  48. return Convert.ToBase64String(imageBytes);
  49. }
  50. }
  51. }
  52. }