I have a ReportPdf
inherited from Prawn::Document
.
When I test it from Rails console, The embedded png image in pdf rendered correctly.
ReportPdf.new(param1,param2).render_file('/Users/ZZ/Desktop/test.pdf')
However, when it is requested from controller:
def generate_pdf
pdf = ReportPdf.new(param1, param2)
send_data pdf.render, filename: 'report.pdf', type: 'application/pdf'
end
the image was not rendered, other contents rendered without any problems.
I've tried using local image and image from Amazon S3. Both works fine in console but not from controller.
The generate_pdf
method in controller also gives a correct pdf. The PDF was correctly rendered if I request it directly. I tested it with Postman.
However, the image in PDF was not rendered only when it is requested from an export button in Angular. The following are implementations:
Backend:
class ReportPdf < Prawn::Document
def initialize(param1, param2)
super()
@param1 = param1
@date = Time.zone.parse(param2) || Time.zone.now
header
end
def header
img = open('https://s3-ap-southeast2.amazonaws.com/bucket/folder/logo.png')
# use local image
# img = "#{Rails.root}/app/assets/images/logo.png"
data = [[{ image: img, image_width: 150, vposition: :center },
"#{@param1.name} - #{@param2.suburb}"]]
table(data, cell_style: { borders: {},
valign: :center, align: :right, size: 25, width:
270 })
end
end
Frontend:
$scope.exportToPdf = function() {
var tmpDate = moment(new Date($scope.date)).format('DD-MM-YYYY');
$http({
method: 'GET',
url: '/resourceA/' + $stateParams.resourceAId + '/resourceB/daily_pdf?day=' + tmpDate
}).
success(function(data, status, headers, config) {
var anchor = angular.element('<a/>');
anchor.attr({
href: 'data:application/pdf;charset=utf-8,' + encodeURI(data),
target: '_blank',
download: 'daily_report.pdf'
})[0].click();
}).
error(function(data, status, headers, config) {
// something here.
});
};
I guess the problem is encoding, image binary data was corrupted during encoding. Where is the mistake?
report.pdf.erb
– Unmeetimg
object's data or class to review the returned value fromopen(img_url)
... I'm wondering if that line isn't where something goes sideways... – Uncork