challenge Hello, world! PDF版

Hello, world!シリーズの続編です。 「Hello, world!」となるべく大きく書かれた1ページのPDFを出力してください。

Posted feedbacks - Ruby

うわぁ、一番乗りそこねたぁ
1
2
3
4
5
6
require 'rubygems'
require 'pdf/writer'
PDF::Writer.new do |pdf|
  pdf.text "Hello, world!", :font_size => 150, :justification => true
  pdf.save_as "50.pdf"
end

#2489 の rcairo 版。

ページいっぱいにテキストを出力するために text extents から font size を計算していたが、
http://mmon.sourceforge.jp/memo/memo.html
を見ると width より x_advance を使ったほうがよさそうなのでそうしました。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
require 'cairo'

width, height = 291, 210
text = "Hello, world!"

Cairo::PDFSurface.new("hello.pdf", width, height) do |surface|
  cr = Cairo::Context.new(surface)
  font_size = cr.save {
    cr.set_font_size(100.0)
    width / cr.text_extents(text).x_advance * 100.0
  }

  cr.set_font_size(font_size)
  cr.move_to(0, height / 2)
  cr.show_text(text)
  cr.show_page
end

OpenOffice の COM インターフェイスを使って PDF にしてみました。

フォントサイズは決めうちです。
マクロで記録した Oo Basic をそのまま直訳した感じです。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
require "win32ole"

class Hash
  def to_prop(manager)
    inject([]){|acc,pair|
      opt = manager.Bridge_GetStruct("com.sun.star.beans.PropertyValue")
      opt["Name"], opt["Value"] = *pair
      acc << opt
    }
  end
end

manager = WIN32OLE.new("com.sun.star.ServiceManager")
desktop = manager.createInstance("com.sun.star.frame.Desktop")
document = desktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, [])

frame = document.getCurrentController().getFrame()
dispatcher = manager.createInstance("com.sun.star.frame.DispatchHelper")

dispatcher.executeDispatch(frame, ".uno:FontHeight", "", 0, {
  "FontHeight.Height" => 80,
  "FontHeight.Prop" => 100,
  "FontHeight.Diff" => 0,
}.to_prop(manager))

text = document.GetText
cursor = text.createTextCursor
text.insertString(cursor, "Hello, world!", 0)

dispatcher.executeDispatch(frame, ".uno:ExportDirectToPDF", "", 0, {
  "URL" => "file:///#{File.expand_path("hello.pdf")}" ,
  "FilterName" => "writer_pdf_Export",
  "SelectionOnly" => "true",
}.to_prop(manager))

document.close(false)

Index

Feed

Other

Link

Pathtraq

loading...