PDFToImage.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using ComPDFKit.PDFDocument;
  2. using ComPDFKit.PDFPage;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows;
  10. using System.Windows.Media;
  11. using System.Windows.Media.Imaging;
  12. namespace PDFToImageTest
  13. {
  14. internal class PDFToImage
  15. {
  16. static private string outputPath = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()))) + "\\Output\\PDFToImage";
  17. static void Main(string[] args)
  18. {
  19. Console.WriteLine("Running PDFToImage test sample…\r\n");
  20. SDKLicenseHelper.LicenseVerify();
  21. CPDFDocument document = CPDFDocument.InitWithFilePath("CommonFivePage.pdf");
  22. if (!Directory.Exists(outputPath))
  23. {
  24. Directory.CreateDirectory(outputPath);
  25. }
  26. PDFPageToImage(document);
  27. Console.WriteLine("--------------------");
  28. Console.WriteLine("Done!");
  29. Console.WriteLine("--------------------");
  30. Console.ReadLine();
  31. }
  32. static private void SaveWriteableBitmapAsPng(WriteableBitmap writeableBitmap, string fileName)
  33. {
  34. using (FileStream stream = new FileStream(fileName, FileMode.Create))
  35. {
  36. PngBitmapEncoder encoder = new PngBitmapEncoder();
  37. encoder.Frames.Add(BitmapFrame.Create(writeableBitmap));
  38. encoder.Save(stream);
  39. }
  40. }
  41. /// <summary>
  42. /// Convert PDF to image
  43. /// </summary>
  44. static private bool PDFPageToImage(CPDFDocument document)
  45. {
  46. for (int i = 0; i < document.PageCount; i++)
  47. {
  48. CPDFPage pdfPage = document.PageAtIndex(i, true);
  49. Size pageSize = document.GetPageSize(0);
  50. Rect pageRect = new Rect(0, 0, (int)(pageSize.Width / 72.0 * 96), (int)(pageSize.Height / 72.0 * 96));
  51. byte[] bmpData = new byte[(int)(pageRect.Width * pageRect.Height * (96 / 72.0) * (96 / 72.0) * 4)];
  52. pdfPage.RenderPageBitmapWithMatrix((float)(96/72.0), pageRect, 0xFFFFFFFF, bmpData, 0, true);
  53. WriteableBitmap writeableBitmap = new WriteableBitmap((int)pageRect.Width, (int)pageRect.Height, 96, 96, PixelFormats.Bgra32, null);
  54. writeableBitmap.WritePixels(new Int32Rect(0, 0, (int)pageRect.Width, (int)pageRect.Height), bmpData, writeableBitmap.BackBufferStride, 0);
  55. var path = outputPath + "//PDFToImageTest" + i + ".png";
  56. SaveWriteableBitmapAsPng(writeableBitmap, path);
  57. Console.WriteLine("Png image saved in {0}", path);
  58. }
  59. return false;
  60. }
  61. }
  62. }