# Write images in PDF format

**URL:** <https://www.ruby-forum.com/t/write-images-in-pdf-format/138353>\
**Category:** Ruby\
**Created:** [May 22, 2008, 7:49am UTC](https://www.ruby-forum.com/t/write-images-in-pdf-format/138353 "2008-05-22T07:49:53Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jazzezravi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/71e660/32.png) [@jazzezravi](https://www.ruby-forum.com/u/jazzezravi)\
**Post date:** [May 22, 2008, 7:49am UTC](https://www.ruby-forum.com/t/write-images-in-pdf-format/138353/1 "2008-05-22T07:49:53Z")

</div>

Hi All,

My Environment:

OS: Windows, Ruby1.8.6, pdfwriter-1.1.8

My need:

I have 10 jpeg images in my local system(C:\jazzezravi\1.jpg).  
I want to write all the 10 images into one PDF format. Just now i  
installed pdf-writer gem.

Thank you.

Regards,  
P.Raveendran  
RailsFactory

> **[Raveendran](https://raveendran.wordpress.com)**
>
> Nothing is impossible...

---

<div class="post-metadata">

**Author:** ![jazzezravi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/71e660/32.png) [@jazzezravi](https://www.ruby-forum.com/u/jazzezravi)\
**Post date:** [May 22, 2008, 11:10am UTC](https://www.ruby-forum.com/t/write-images-in-pdf-format/138353/2 "2008-05-22T11:10:39Z")

</div>

On Thu, May 22, 2008 at 7:49 AM, Raveendran J.  
[removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> installed pdf-writer gem.
> 
> Thank you.

Hi,

it’s easy, I think you’ll find some examples either in pdfwriter docs  
([http://ruby-pdf.rubyforge.org/pdf-writer/index.html](http://ruby-pdf.rubyforge.org/pdf-writer/index.html)),  
or somewhere else on the web. Just google a bit.

If you get stuck, post the code here and somebody will try to help you.

This is my code for something similar - I do some resizing too. You  
should be able to produce similar  
code in a short time - everything you need is in the docs (for me the  
initial version took 1-2 hours max).

J.

require ‘pdf/writer’  
pdf = PDF::Writer.new(:paper =\> “A4”, :orientation =\> :portrait)

[‘1.jpg’, ‘2.jpg’, ‘3.jpg’].each do |jpg|  
pdf.start\_new\_page  
image\_data = File.open(jpg, ‘rb’) {|f| f.read }  
image\_info = PDF::Writer::Graphics::ImageInfo.new(image\_data)  
p image\_info.width, pdf.page\_width  
p image\_info.height, pdf.page\_height  
ratio = [pdf.page\_width/image\_info.width,  
pdf.page\_height/image\_info.height].min  
p ratio  
width = image\_info.width \* ratio  
height = image\_info.height \* ratio  
p width, height  
offset\_x = (pdf.page\_width - width) / 2  
offset\_y = (pdf.page\_height - height)

```
    pdf.add_image(image_data, offset_x, offset_y, width, height)

```

end

pdf.save\_as(“out.pdf”)
