iT邦幫忙

2021 iThome 鐵人賽

DAY 14
0
自我挑戰組

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

Day14 - PDF 加浮水印

前言

工作上在處理 API 取得的 PDF 後,要在上面增加浮水印,進而研究與紀錄的處理方式

實作

會需要用到 combine_pdfprawn 這兩個 Gem 處理

# Gemfile

gem 'combine_pdf', '~> 1.0', '>= 1.0.21'
gem 'prawn', '~> 2.4'

將增加浮水寫成一個方法,範例的 PDF ,和實作的 pr

# app/features/pdf/add_watermark_pdf.rb

module Pdf
  class AddWatermarkPdf

    # input_file = Rails.root.join('data/river_demo_watermark.pdf')
    # output_file = input_file.dirname.join('done.pdf')
    # watermark_texts = %w[river_1 river_2 river_3]
    def execute(input_file, output_file, watermark_texts = [])
      tmp_watermark_file(input_file)              # 暫存的浮水印 PDF path
      generate_watermark_content(watermark_texts) # 產浮水印的 PDF
      combine_pdf(input_file, output_file)        # 將 input_file 與浮水印 PDF 合併
      FileUtils.rm_rf(@tmp_watermark_file)        # 移除暫存的浮水印 PDF
    end

    private

    def tmp_watermark_file(input_file)
      @tmp_watermark_file ||= input_file.dirname.join('tmp_watermark.pdf')
    end

    # 可自行設定字型大小、顏色等
    # Prawn Documentation: https://prawnpdf.org/api-docs
    # Prawn example: https://prawnpdf.org/manual.pdf
    def generate_watermark_content(watermark_texts)
      position, amount_per_page = watermark_args
      Prawn::Document.generate(@tmp_watermark_file) do
        watermark_texts.each_with_index do |watermark_text, index|
          page = index / amount_per_page + 1
          coordinate = position[index % amount_per_page]
          start_new_page if page != 1 && (index % amount_per_page).zero?
          go_to_page(page)
          float do
            bounding_box(coordinate, height: 14, width: 48) do
              fill_color '000000'
              fill_rectangle [0, bounds.height], bounds.width, bounds.height
              stroke_bounds
              fill_color 'FFFFFF'
              text watermark_text.to_s, align: :center, valign: :center, size: 12
            end
          end
        end
      end
    end

    # 浮水印在頁面上的位置、每頁的數量
    def watermark_args
      position = [[0, 769], [0, 392]] # xy 軸座標 (需自行計算適合的位置)
      amount_per_page = 2             # 每頁的浮水印數量

      [position, amount_per_page]
    end

    def combine_pdf(input_file, output_file)
      pdf_pages = CombinePDF.load(@tmp_watermark_file).pages
      pdf = CombinePDF.load(input_file)
      pdf.pages.each_with_index { |page, index| page << pdf_pages[index] }
      pdf.save(output_file)
    end
  end
end

完成上述步驟後,接著在 rails console 輸入以下,便大功告成

# rails console

input_file = Rails.root.join('data/river_demo_watermark.pdf')
output_file = input_file.dirname.join('done.pdf')
watermark_texts = %w[river_1 river_2 river_3]
Pdf::AddWatermarkPdf.new.execute(input_file, output_file, watermark_texts)

示範的 PDF

加上浮水印後

小結

上面的範例為一頁有多處需要加浮水印,且每個位置的浮水印內容皆不一樣,因此在處理上會略為複雜些,若每頁只需加一處且浮水印內容一樣,處理上會簡單一點

目前想到在 PDF 上加浮水印的做法是,將來源的 PDF、浮水印的 PDF 合併,合併後再把暫存浮水印 PDF 刪除,若有更好的做法,歡迎留言和我說

至於如何知道浮水印的位置,「trial and error」會是一個好方法 xD

參考資料

  1. combine_pdf GitHub
  2. Prawn GitHub
  3. Prawn example

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

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


上一篇
Day13 - PDF 加密、解密的處理
下一篇
Day15 - 匯出(下載) PDF
系列文
Ruby on Rails 與它們相關的東西 II30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言