PDFToImage.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using ComPDFKit.PDFDocument;
  2. using ComPDFKit.PDFPage;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Drawing;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Windows;
  11. using ComPDFKit.Import;
  12. using ImageMagick;
  13. namespace PDFToImageTest
  14. {
  15. internal class PDFToImage
  16. {
  17. private static string parentPath =
  18. Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory())));
  19. private static string outputPath = parentPath + @"\Output\CS";
  20. static void Main(string[] args)
  21. {
  22. Console.WriteLine("Running PDFToImage test sample…" + Environment.NewLine);
  23. SDKLicenseHelper.LicenseVerify();
  24. CPDFDocument document = CPDFDocument.InitWithFilePath("CommonFivePage.pdf");
  25. if (!Directory.Exists(outputPath))
  26. {
  27. Directory.CreateDirectory(outputPath);
  28. }
  29. PDFPageToImage(document);
  30. PDFToImage2(document);
  31. Console.WriteLine("--------------------");
  32. Console.WriteLine("Done!");
  33. Console.WriteLine("--------------------");
  34. Console.ReadLine();
  35. }
  36. private static void PDFToImage2(CPDFDocument document)
  37. {
  38. document.PdfToImage("1", outputPath);
  39. }
  40. /// <summary>
  41. /// Convert PDF to image
  42. /// </summary>
  43. static private bool PDFPageToImage(CPDFDocument document)
  44. {
  45. for (int i = 0; i < document.PageCount; i++)
  46. {
  47. CPDFPage pdfPage = document.PageAtIndex(i, true);
  48. CSize cSize = document.GetPageSize(0);
  49. System.Drawing.Size pageSize = new System.Drawing.Size((int)cSize.width, (int)cSize.height);
  50. CRect pageRect = new CRect(0, (int)(pageSize.Height / 72.0 * 96), (int)(pageSize.Width / 72.0 * 96), 0);
  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. var path = Path.Combine(outputPath, "PDFToImageTest" + i + ".png");
  54. var settings = new MagickReadSettings()
  55. {
  56. Format = MagickFormat.Bgra,
  57. Width = (int)pageRect.width(),
  58. Height = (int)pageRect.height()
  59. };
  60. using (var image = new MagickImage(bmpData,settings))
  61. {
  62. image.Format = MagickFormat.Png;
  63. image.Write(path);
  64. }
  65. Console.WriteLine("Png image saved in {0}", path);
  66. }
  67. return false;
  68. }
  69. }
  70. }