Techioz Blog

Ruby on Rails を使用して、サイズ変更した画像を既存の PDF に追加する方法

概要

私は Ruby on Rails プロジェクトに取り組んでおり、私の目標は、サイズ変更された画像、特に署名を既存の PDF に追加することです。高度な機能を備えた複雑な署名ではなく、単純な画像を追加しようとしているということを強調したいと思います。

私が実装したコードは次のとおりです。

def add_image_to_pdf
  # Get the original PDF and the image
  original_pdf_path = Rails.root.join("public", "uploads", "document", "pdf", "original.pdf").to_s
  image_path = Rails.root.join("public", "uploads", "images", "signature_image.jpeg").to_s

  # Output path for the new PDF
  output_pdf_path = Rails.root.join("public", "uploads", "document", "pdf", "document_with_image.pdf").to_s

  # Temporary path for the image converted to PDF
  temp_pdf_path = Rails.root.join("public", "uploads", "temp_image.pdf").to_s

  # Resize the image using MiniMagick and convert it to PDF
  image = MiniMagick::Image.open(image_path)
  image.resize "1000x1000"
  image.format "pdf"
  image.write temp_pdf_path

  # Load the original PDF and the resized image
  original_pdf = CombinePDF.load(original_pdf_path)
  image_page = CombinePDF.load(temp_pdf_path).pages[0]

  # Combine the original PDF with the resized image
  pdf = CombinePDF.new
  pdf << original_pdf
  pdf.pages.each { |page| page << image_page }
  pdf.save output_pdf_path

  # Delete the temporary file
  File.delete(temp_pdf_path) if File.exist?(temp_pdf_path)

  render json: { status: "Success", message: "Image added to PDF successfully", output_pdf_path: output_pdf_path }
end

私の努力にもかかわらず、サイズ変更された画像が既存の PDF 内に正確に配置されません。 PDF 内の指定された位置に画像を正確に配置する方法についてアドバイスを求めています。

具体的な質問:

PDF への画像追加の精度を高めるためのガイダンスや提案をいただければ幸いです。ありがとう!

解決策

[注意]私は HexaPDF の作者です。商用利用するにはライセンスを購入する必要があります。]

HexaPDF または Prawn を prawn-templates gem と一緒に使用することをお勧めします。

コードから、ソース PDF の各ページの上に既存の画像を追加したいと思います。 HexaPDF の場合、コードは次のようになります。

doc = HexaPDF::Document.open(original_pdf_path)
image = doc.images.add(image_path)
doc.pages.each do |page|
  page.canvas(type: :overlay).image(image, at: [0, 0])
end
doc.write(output_pdf_path, optimize: true)

画像の配置に関するご質問ですが、各ページの左下隅を (0, 0) として at 部分を変更します。 #image メソッドで width および/または height キーワード引数を指定することで、画像のサイズを変更することもできます。

#image メソッドの詳細については、https://hexapdf.gettalong.org/documentation/api/HexaPDF/Content/Canvas.html#method-i-image を参照してください。