PDFToImageTest.vb 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. Module PDFToImageTest
  11. Private parentPath As String =
  12. Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory())))
  13. Private outputPath As String = Path.Combine(parentPath, "Output", "VB")
  14. Sub Main(args As String())
  15. Console.WriteLine("Running PDFToImage test sample..." & vbCrLf)
  16. SDKLicenseHelper.LicenseVerify()
  17. Dim document As CPDFDocument = CPDFDocument.InitWithFilePath("CommonFivePage.pdf")
  18. If Not Directory.Exists(outputPath) Then
  19. Directory.CreateDirectory(outputPath)
  20. End If
  21. PDFPageToImage(document)
  22. Console.WriteLine("--------------------")
  23. Console.WriteLine("Done!")
  24. Console.WriteLine("--------------------")
  25. Console.ReadLine()
  26. End Sub
  27. Private Sub SaveWriteableBitmapAsPng(writeableBitmap As WriteableBitmap, fileName As String)
  28. Using stream As New FileStream(fileName, FileMode.Create)
  29. Dim encoder As New PngBitmapEncoder()
  30. encoder.Frames.Add(BitmapFrame.Create(writeableBitmap))
  31. encoder.Save(stream)
  32. End Using
  33. End Sub
  34. ' Convert PDF to image
  35. Private Function PDFPageToImage(document As CPDFDocument) As Boolean
  36. For i As Integer = 0 To document.PageCount - 1
  37. Dim pdfPage As CPDFPage = document.PageAtIndex(i, True)
  38. Dim pageSize As Windows.Size = document.GetPageSize(0)
  39. Dim pageRect As New Rect(0, 0, CInt(pageSize.Width / 72.0 * 96), CInt(pageSize.Height / 72.0 * 96))
  40. Dim bmpData As Byte() = New Byte(CInt(pageRect.Width * pageRect.Height * (96 / 72.0) * (96 / 72.0) * 4) - 1) {}
  41. pdfPage.RenderPageBitmapWithMatrix(CSng(96 / 72.0), pageRect, Convert.ToUInt32(&HFFFFFFF), bmpData, 0, True)
  42. Dim writeableBitmap As New WriteableBitmap(CInt(pageRect.Width), CInt(pageRect.Height), 96, 96, PixelFormats.Bgra32, Nothing)
  43. writeableBitmap.WritePixels(New Int32Rect(0, 0, CInt(pageRect.Width), CInt(pageRect.Height)), bmpData, writeableBitmap.BackBufferStride, 0)
  44. Dim filePath As String = Path.Combine(outputPath, "PDFToImageTest" & i & ".png")
  45. SaveWriteableBitmapAsPng(writeableBitmap, filePath)
  46. Console.WriteLine("Png image saved in " & filePath)
  47. Next
  48. Return False
  49. End Function
  50. End Module