Ruby简单粗暴把图片合成PDF文档

有些工具还收费,没有苛刻的要求可以用交易一气呵成。

ruby 复制代码
# frozen_string_literal: true
# encoding: utf-8

require 'prawn'

class Img2Pdf
  A4_WIDTH = 595.28
  A4_HEIGHT = 841.89

  def initialize(output_path = 'output.pdf')
    @output_path = output_path
  end

  def convert(image_paths)
    raise ArgumentError, '请提供至少一张图片路径' if image_paths.empty?

    image_paths = sort_image_paths(image_paths)

    valid_images = []

    image_paths.each do |image_path|
      if File.exist?(image_path)
        valid_images << image_path
      else
        warn "警告:图片不存在 - #{image_path}"
      end
    end

    return unless valid_images.any?

    doc = Prawn::Document.new(page_size: 'A4', page_layout: :portrait)

    valid_images.each_with_index do |image_path, index|
      begin
        add_image_to_page(doc, image_path)
        puts "已添加图片 #{index + 1}/#{valid_images.length}: #{File.basename(image_path)}"
      rescue => e
        warn "错误:无法处理图片 #{image_path} - #{e.message}"
      end
    end

    doc.render_file(@output_path)
    puts "PDF 文件已生成:#{@output_path}"
    @output_path
  end

  private

  def sort_image_paths(paths)
    paths.sort_by do |path|
      numbers = File.basename(path).scan(/\d+/).map(&:to_i)
      numbers.empty? ? [0, path] : [numbers.first, path]
    end
  end

  def add_image_to_page(doc, image_path)
    page_width = A4_WIDTH
    page_height = A4_HEIGHT
    margin = 50

    doc.image(image_path,
              width: page_width - margin * 2,
              position: :center,
              vposition: :top)
  end
end

if __FILE__ == $PROGRAM_NAME
  if ARGV.empty?
    puts "用法:ruby main.rb [图片路径 1] [图片路径 2] ... [-o 输出文件名]"
    puts "示例:ruby main.rb img1.jpg img2.jpg img3.jpg"
    puts "      ruby main.rb *.png -o mypdf.pdf"
    exit 1
  end

  output_file = 'output.pdf'
  if (output_index = ARGV.index('-o'))
    if output_index + 1 < ARGV.length
      output_file = ARGV[output_index + 1]
      ARGV.delete_at(output_index)
      ARGV.delete_at(output_index)
    end
  end

  image_paths = ARGV.select { |arg| !arg.start_with?('-') }

  converter = Img2Pdf.new(output_file)
  converter.convert(image_paths)
end
相关推荐
码云社区1 小时前
Java在线租房系统源码:VR看房素材、房源图片与内容维护方案
java·vue.js·vr·租房小程序·在线租房·看房租房
码云社区1 小时前
Spring Boot智慧物业系统源码:合同到期提醒、续签资料与资产协作
java·spring boot·后端·物业管理·物业系统·智慧物业
AI开源软件2 小时前
Vue3+SpringBoot3 业务配置统一管理:接管、保存与回退怎样保留有效值
java·前端·vue.js·spring boot·vue·ruoyi office
陈如水2 小时前
Spring AI Alibaba 在多 Agent 场景下的实践
java·人工智能·spring
吃我一窝jio2 小时前
Docker+Jenkins+K8s全流程部署
java·开发语言·笔记·python
Resean02235 小时前
Spring 源码分析(六)循环依赖与三级缓存
java·spring·缓存
在爪洼山玩泥巴6 小时前
fastjson2 JSONPath 取不存在路径,为什么会抛 “not support”?
java·开发语言·jsonpath·fastjson
星落梦生15 小时前
SpringAOP基础笔记(7)
java·开发语言
金銀銅鐵16 小时前
带您看懂字节码指令(四):一条指令里有什么
java·jvm
最强小杰17 小时前
某 OpenAI 兼容网关上的 `kimi-k3.1-pro`:Cline、Zed 接入与 SSE 排错示例
java·服务器·网络·ai