[poppler] Modifying existing pdfs with popplar and cairo

Kouhei Sutou kou at cozmixng.org
Tue Apr 22 04:34:48 PDT 2008


Hi,

In <480D49ED.6000506 at plmw.com>
  "[poppler] Modifying existing pdfs with popplar and cairo" on Mon, 21 Apr 2008 20:14:05 -0600,
  Mark Thompson <markthompson at plmw.com> wrote:

> I have a project using Rails where I'm trying to read and modify pdf 
> files. it has been a very frustrating search to find the right libraries 
> to use for the project.
> Specifically, my client want the site to allow a user to enter text on a 
> form, and then have that text inserted into an existing pdf file. I was 
> wondering if I could use poppler to read the pdf file and then use cairo 
> to modify it and write it back out. I am wondering if anyone has any 
> examples of ruby code using poppler.

input:
  http://pub.cozmixng.org/~kou/archives/rabbit/rabbit-theme-bench.pdf

output:
  http://pub.cozmixng.org/~kou/archives/rabbit/rabbit-theme-bench-numbered.pdf

#!/usr/bin/env ruby

require 'poppler'

input = ARGV.first
output = input.sub(/\.pdf$/, "-numbered.pdf")

doc = Poppler::Document.new(input)
first_page = doc[0]

Cairo::PDFSurface.new(output, *first_page.size) do |surface|
  context = Cairo::Context.new(surface)

  doc.each_with_index do |page, i|
    width, height = page.size
    surface.set_size(width, height)
    context.save do
      context.render_poppler_page(page)
    end
    context.save do
      layout = context.create_pango_layout
      layout.text = i.to_s
      layout.width = width * Pango::SCALE
      layout.alignment = Pango::Layout::ALIGN_CENTER
      layout.font_description = Pango::FontDescription.new("Sans 288")
      context.move_to(0, (height - layout.pixel_size[1]) / 2.0)
      context.set_source_rgba(0.1, 0.1, 0.1, 0.5)
      context.show_pango_layout(layout)
    end
    context.show_page
  end
end


Thanks,
--
kou


More information about the poppler mailing list