1. PDF转JPG

在下面的示例中,我们将该gographics/imagick包用作ImageMagick的C库的包装,以将我们的PDF转换为JPG。处理过程如下:我们使用软件包将测试文件加载到测试文件中,然后通过设置分辨率,压缩级别和alpha通道设置进行处理,然后保存最终的输出文件。由于该库基于C构建,因此重要的是我们必须适当调用Terminate和Destroy函数以检查内存使用情况。

在Ubuntu 18.04下运行的前提条件:

  1. sudo apt install libmagic-dev libmagickwand-dev

代码:

  1. package main
  2. import (
  3. "log"
  4. "gopkg.in/gographics/imagick.v2/imagick"
  5. )
  6. func main() {
  7. pdfName := "ref.pdf"
  8. imageName := "test.jpg"
  9. if err := ConvertPdfToJpg(pdfName, imageName); err != nil {
  10. log.Fatal(err)
  11. }
  12. }
  13. // ConvertPdfToJpg will take a filename of a pdf file and convert the file into an
  14. // image which will be saved back to the same location. It will save the image as a
  15. // high resolution jpg file with minimal compression.
  16. func ConvertPdfToJpg(pdfName string, imageName string) error {
  17. // Setup
  18. imagick.Initialize()
  19. defer imagick.Terminate()
  20. mw := imagick.NewMagickWand()
  21. defer mw.Destroy()
  22. // Must be *before* ReadImageFile
  23. // Make sure our image is high quality
  24. if err := mw.SetResolution(300, 300); err != nil {
  25. return err
  26. }
  27. // Load the image file into imagick
  28. if err := mw.ReadImage(pdfName); err != nil {
  29. return err
  30. }
  31. // Must be *after* ReadImageFile
  32. // Flatten image and remove alpha channel, to prevent alpha turning black in jpg
  33. if err := mw.SetImageAlphaChannel(imagick.ALPHA_CHANNEL_FLATTEN); err != nil {
  34. return err
  35. }
  36. // Set any compression (100 = max quality)
  37. if err := mw.SetCompressionQuality(95); err != nil {
  38. return err
  39. }
  40. // Select only first page of pdf
  41. mw.SetIteratorIndex(0)
  42. // Convert into JPG
  43. if err := mw.SetFormat("jpg"); err != nil {
  44. return err
  45. }
  46. // Save File
  47. return mw.WriteImage(imageName)
  48. }

如果您看到类似以下的错误,请参阅指南

  1. ERROR_POLICY: not authorized `TestPdf.pdf' @ error/constitute.c/ReadImage/412