0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Hexapdfを使って、rubyでpdf をゼロから生成する (Windows)

Last updated at Posted at 2025-04-24

有名な Prawn PDFだと、日本語およびWindowsの扱いが悪いので…

はじめの一歩

まずはIPAフォントを使って日本語を表示されるように

hello.rb
require 'hexapdf'

doc = HexaPDF::Document.new
doc.config['font.map'] = {
  'IPA' => { none: 'ipagp.ttf' }
}

page = doc.pages.add		# A4ページが生成 (A4 は 595 x 842 ポイント)。

canvas = page.canvas
canvas.font('IPA', size: 30)
canvas.text("Hello 日本語", at: [20, 400])	# 左下が原点

doc.write("hello-world.pdf")

フォントの色を変える

RGBで指定する。

canvas.font('IPA', size: 22).fill_color(0, 128, 255) #RGB

長方形を配置する

テキストとグラフィックは、同じレイヤーに配置できません。レイヤーを分けましょう

  • rectangle()の最後が.fill だと塗りつぶし、.strokeだと境界線を描写します。
box.rb

# メインレイヤーに、グレーの塗りつぶし長方形
canvas = page.canvas
canvas.fill_color(222, 222, 222).rectangle( 0,660, 300, 680 ).fill	#[開始x, 開始y, x太さ ,y太さ] 

# 上側レイヤーに文字を書く
canvas_up = page.canvas(type: :overlay)	
canvas_up.font('IPA', size: 13)
canvas_up.text("Hello 日本語", at: [20, 400])

複数ページPDFを、個別のPDFファイルに分割

split.rb
doc = HexaPDF::Document.open("input.pdf")
len = doc.pages.length

len.times do |i|
	p i
	newdoc = doc.duplicate()
	i.times do newdoc.pages.delete_at(0) end		# 自分より前ページを削除
	(len - i).times do newdoc.pages.delete_at(1) end	# 自分より後ページを削除
	
	newdoc.write("splitted_#{i}.pdf")
end

ページサイズやフォントをいろいろ変えてみる

Composerメソッドが楽だと思う。これはタイプライタ方式で、上から下にスクロールしながら印字していく。

# ページサイズはポイント指定
# 余白は[上下,左右]
HexaPDF::Composer.create('out.pdf', page_size: [0,0,327,560], margin:  [4,36] ) do |pdf|
	pdf.document.config['font.map'] = {
		'IPA' => { none: 'C:\Windows\Fonts\ipagp.ttf' }, 
		'Noto' => { none: 'C:\Windows\Fonts\NotoSerifJP-VF.ttf'}
		}

	pdf.style(:base, font_size: 20, text_align: :center, font:"IPA")	# デフォルトフォント
	pdf.text("Hello 日本語")

	pdf.new_page  
	pdf.text("ここは 二ページ目だよ", text_align: :right, font: "Noto", font_size: 13 )	# フォントを変えて
	pdf.text("\n")
	pdf.text("行を置いて 文字を入れたりも", text_align: :center)
    pdf.text("このページは #{pdf.document.pages.length} ページ目だよ")
end

任意の場所に、任意のアイテムを配置する

Composerメソッドを使っている途中で、任意の場所に配置したくなった時はCanvasを呼び出す

HexaPDF::Composer.create('out.pdf') do |pdf|
	pdf.image("background.png") 
	pdf.canvas.image("human.png" , at:[30,10] ,width: 270) 	# 左下が原点
end
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?