# License # # Copyright (c) 2004 Koen Vervloesem. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, and/or sell copies of the Software, and to permit persons # to whom the Software is furnished to do so, provided that the above # copyright notice(s) and this permission notice appear in all copies of # the Software and that both the above copyright notice(s) and this # permission notice appear in supporting documentation. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT # OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY # SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER # RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF # CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # # Except as contained in this notice, the name of a copyright holder # shall not be used in advertising or otherwise to promote the sale, use # or other dealings in this Software without prior written authorization # of the copyright holder. require 'rpdf' require 'image_size' class JPEG2PDF include RPDF def initialize(pdf) @doc = Document.new(pdf) @imagenumber = 0 end def add_jpeg(filename) jpegfile = File.open(filename) imagedata = jpegfile.read jpegfile.close size = ImageSize.new(imagedata) if(size.get_type == 'JPEG') width = size.get_width height = size.get_height bpc = size.get_bpc components = size.get_components if components == 1 colorspace = :DeviceGray elsif components == 3 colorspace = :DeviceRGB elsif components == 4 colorspace = :DeviceCMYK else raise Exception.new("Unsupported colorspace in image #{filename}") end imagestream = PDFStream.new(imagedata, @doc) imagestream.dict[:Filter] = [:DCTDecode] imagestream.dict[:Name] = "Image#{@imagenumber}".intern imagedictionary = ImageDictionary.new(width, height, colorspace, bpc) imagestream.dict.update(imagedictionary) imagestream.invalidate # write jpeg as soon as possible page = Page.new(@doc, @doc.pagetree) page[:MediaBox] = [0, 0, width, height] page[:Resources] = { :XObject => { "Image#{@imagenumber}".intern => imagestream } } contentstream = PDFStream.new("q\n#{width} 0 0 #{height} 0 0 cm\n/Image#{@imagenumber} Do\nQ", @doc) page[:Contents] = contentstream @imagenumber = @imagenumber + 1 end end def close @doc.close_pdf end end