iT邦幫忙

2021 iThome 鐵人賽

DAY 13
0
自我挑戰組

Ruby on Rails 與它們相關的東西 II系列 第 13

Day13 - PDF 加密、解密的處理

前言

在處理 PDF 增加密碼 (加密) 、移除解密 (解密) 時,可以使用 Ghostscript 處理,若不熟悉,可以先看下 wiki官方文件的介紹

實作

首先需要先安裝 ghostscript

# for macOS
brew install ghostscript

這邊提供範例 PDF ,和實作的 pr,參數細節設定,可以參考官方文件

# app/services/processing_pdf.rb

class ProcessingPdf
  # ghostscript Documentation: https://www.ghostscript.com/doc/current/Use.htm

  def self.encryption(pwd, input_file, output_file)
    _stdout_str, _stderr_str, _status = Open3.capture3("gs -sDEVICE=pdfwrite -dBATCH -dNOPAUSE -dNOPROMPT -dQUIET \
                                                        -sOwnerPassword=#{pwd} -sUserPassword=manan \
                                                        -sOutputFile=#{output_file} #{input_file}")

    { success: true, msg: 'PDF加密完成' }
  end

  def self.decrypt(pwd, input_file, output_file)
    _stdout_str, stderr_str, _status = Open3.capture3("gs -q -sDEVICE=pdfwrite -dBATCH -dNOPAUSE \
                                                       -SPDFPassword=#{pwd} -sOutputFile=#{output_file} \
                                                       -c 30000000 setvmthreshold -f #{input_file}")

    return { error_msgs: stderr_str.remove("\n") } if stderr_str.present?

    { success: true, msg: 'PDF解密完成' }
  end
end

將加密、解密寫在 services,方便之後使用,以下為實際測試加解密 PDF

# rails console

source_pdf = Rails.root.join("data/river_demo_pdf.pdf")
encryption_pdf = Rails.root.join("data/set_password_river_demo_pdf.pdf")
password = "river_test"

# 加密 PDF
encryption_result = ProcessingPdf.encryption(password, source_pdf, encryption_pdf)

# 解密 PDF
input_pdf = encryption_pdf
output_pdf = Rails.root.join("data/decrypt_river_demo_pdf.pdf")
decrypt_result = ProcessingPdf.decrypt(password, input_pdf, output_pdf)

# 處理解密時,若遇到輸入密碼錯誤,要在自行處理

示範的 PDF

加密後的 PDF (開啟時,會要求輸入密碼)

小結

之前不知道 Ghostscript 前,會找各種 Gems 看是否有好用的解決方案,後來得知這套知名的老牌軟體後,支援的平台挺廣泛的,直接用這套就能搞定了~

參考資料

  1. Ghostscript 官網

鐵人賽文章連結:https://ithelp.ithome.com.tw/articles/10271819
medium 文章連結:https://link.medium.com/JoYN5HDVPjb
本文同步發布於 小菜的 Blog https://riverye.com/

備註:之後文章修改更新,以個人部落格為主


上一篇
Day12 - 解析圖片中的 QR Code 資料
下一篇
Day14 - PDF 加浮水印
系列文
Ruby on Rails 與它們相關的東西 II30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言