Method: CombinePDF::PDFOperations.inject_to_page

Defined in:
lib/combine_pdf.rb

.inject_to_page(page = {Type: :Page, MediaBox: [0,0,612.0,792.0], Resources: {}, Contents: []}, stream = nil, top = true) ⇒ Object



109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/combine_pdf.rb', line 109

def inject_to_page page = {Type: :Page, MediaBox: [0,0,612.0,792.0], Resources: {}, Contents: []}, stream = nil, top = true
	# make sure both the page reciving the new data and the injected page are of the correct data type.
	return false unless page.is_a?(Hash) && stream.is_a?(Hash)

	# following the reference chain and assigning a pointer to the correct Resouces object.
	# (assignments of Strings, Arrays and Hashes are pointers in Ruby, unless the .dup method is called)
	original_resources = page[:Resources]
	if original_resources[:is_reference_only]
		original_resources = original_resources[:referenced_object]
		raise "Couldn't tap into resources dictionary, as it is a reference and isn't linked." unless original_resources
	end
	original_contents = page[:Contents]
	original_contents = [original_contents] unless original_contents.is_a? Array

	stream_resources = stream[:Resources]
	if stream_resources[:is_reference_only]
		stream_resources = stream_resources[:referenced_object]
		raise "Couldn't tap into resources dictionary, as it is a reference and isn't linked." unless stream_resources
	end
	stream_contents = stream[:Contents]
	stream_contents = [stream_contents] unless stream_contents.is_a? Array

	# collect keys as objects - this is to make sure that
	# we are working on the actual resource data, rather then references
	flatten_resources_dictionaries stream_resources
	flatten_resources_dictionaries original_resources

	# injecting each of the values in the injected Page
	stream_resources.each do |key, new_val|
		unless PRIVATE_HASH_KEYS.include? key # keep CombinePDF structual data intact.
			if original_resources[key].nil?
				original_resources[key] = new_val
			elsif original_resources[key].is_a?(Hash) && new_val.is_a?(Hash)
				new_val.update original_resources[key] # make sure the old values are respected
				original_resources[key].update new_val # transfer old and new values to the injected page
			end #Do nothing if array - ot is the PROC array, which is an issue
		end
	end
	original_resources[:ProcSet] = [:PDF, :Text, :ImageB, :ImageC, :ImageI] # this was recommended by the ISO. 32000-1:2008

	if top # if this is a stamp (overlay)
		page[:Contents] = original_contents
		page[:Contents].push *stream_contents
	else #if this was a watermark (underlay? would be lost if the page was scanned, as white might not be transparent)
		page[:Contents] = stream_contents
		page[:Contents].push *original_contents
	end

	page
end