你必須很努力

Day13 - PDF 加密、解密的處理

2021/09/26
字數統計: 423閱讀時間: 1 min

前言

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

實作

首先需要先安裝 ghostscript

1
2
# for macOS
brew install ghostscript

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 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/

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

原文連結:https://riverye.com/2021/09/26/Day13-PDF-加密、解密的處理/

發表日期:2021-09-26

更新日期:2022-12-21

CATALOG
  1. 1. 前言
  2. 2. 實作
    1. 2.1. 示範的 PDF
    2. 2.2. 加密後的 PDF (開啟時,會要求輸入密碼)
  3. 3. 小結
  4. 4. 參考資料