PDFToImageTest.vb 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. Imports ComPDFKit.PDFDocument
  2. Imports ComPDFKit.PDFPage
  3. Imports System
  4. Imports System.Drawing
  5. Imports System.Drawing.Imaging
  6. Imports System.IO
  7. Imports System.Windows
  8. Imports System.Windows.Media
  9. Imports System.Windows.Media.Imaging
  10. Imports ComPDFKit.Import
  11. Module PDFToImageTest
  12. Private parentPath As String =
  13. Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory())))
  14. Private outputPath As String = Path.Combine(parentPath, "Output", "VB")
  15. Sub Main(args As String())
  16. Console.WriteLine("Running PDFToImage test sample..." & vbCrLf)
  17. SDKLicenseHelper.LicenseVerify()
  18. Dim document As CPDFDocument = CPDFDocument.InitWithFilePath("CommonFivePage.pdf")
  19. If Not Directory.Exists(outputPath) Then
  20. Directory.CreateDirectory(outputPath)
  21. End If
  22. PDFPageToImage(document)
  23. Console.WriteLine("--------------------")
  24. Console.WriteLine("Done!")
  25. Console.WriteLine("--------------------")
  26. Console.ReadLine()
  27. End Sub
  28. Private Sub SaveWriteableBitmapAsPng(writeableBitmap As WriteableBitmap, fileName As String)
  29. Using stream As New FileStream(fileName, FileMode.Create)
  30. Dim encoder As New PngBitmapEncoder()
  31. encoder.Frames.Add(BitmapFrame.Create(writeableBitmap))
  32. encoder.Save(stream)
  33. End Using
  34. End Sub
  35. ' Convert PDF to image
  36. Private Function PDFPageToImage(document As CPDFDocument) As Boolean
  37. For i As Integer = 0 To document.PageCount - 1
  38. Dim pdfPage As CPDFPage = document.PageAtIndex(i, True)
  39. Dim pageSize As CSize = document.GetPageSize(0)
  40. Dim pageRect As New CRect(0, 0, CInt(pageSize.width / 72.0 * 96), CInt(pageSize.height / 72.0 * 96))
  41. ' TODO: Crash here. Wrong method of calculating pageSize.height.
  42. Dim bmpData As Byte() = New Byte(CInt(pageRect.width * pageRect.height * (96 / 72.0) * (96 / 72.0) * 4) - 1) {}
  43. pdfPage.RenderPageBitmapWithMatrix(CSng(96 / 72.0), pageRect, Convert.ToUInt32(&HFFFFFFF), bmpData, 0, True)
  44. Dim writeableBitmap As New WriteableBitmap(CInt(pageRect.Width), CInt(pageRect.Height), 96, 96, PixelFormats.Bgra32, Nothing)
  45. writeableBitmap.WritePixels(New Int32Rect(0, 0, CInt(pageRect.Width), CInt(pageRect.Height)), bmpData, writeableBitmap.BackBufferStride, 0)
  46. Dim filePath As String = Path.Combine(outputPath, "PDFToImageTest" & i & ".png")
  47. SaveWriteableBitmapAsPng(writeableBitmap, filePath)
  48. Console.WriteLine("Png image saved in " & filePath)
  49. Next
  50. Return False
  51. End Function
  52. End Module