我有一个 ReportPdf
继承自 Prawn::Document
。
当我从 Rails 控制台测试它时,pdf 中嵌入的 png 图像正确呈现。
ReportPdf.new(param1,param2).render_file('/Users/ZZ/Desktop/test.pdf')
但是,当 Controller 请求它时:
def generate_pdf
pdf = ReportPdf.new(param1, param2)
send_data pdf.render, filename: 'report.pdf', type: 'application/pdf'
end
图片未渲染,其他内容渲染无问题。
我试过使用本地镜像和来自 Amazon S3 的图像。两者在控制台中都能正常工作,但在 Controller 中却不行。
Controller 中的generate_pdf
方法也给出了正确的pdf。如果我直接请求,PDF 会正确呈现。我用 Postman 测试了它。
但是,仅当 Angular 中的导出按钮请求时,PDF 中的图像才不会呈现。以下是实现:
后端:
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
前端:
$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.
});
};
我猜问题出在编码上,图像二进制数据在编码过程中被破坏了。 哪里错了?
最佳答案
当我们看不到试图将图像添加到 PDF 的代码时,很难判断错误出在哪里。 ReportPdf 如何访问图像?
也许这里有适合您情况的提示。在我的代码中,当为画廊生成 pdf 时,画廊会创建 pdf,并通过如下调用将其每张照片添加到 pdf 中:
photo = Photo.find(photo_id)
photo.add_to_pdf(pdf, h_pos, v_pos, h_size, v_size)
照片类方法使用(删除布局计算):
def add_to_pdf(pdf, h_pos, v_pos, h_size, v_size)
pdf.image self.image.path(:full),
:position => pos_sym,
:vposition => vpos_sym,
:fit => [size,vsize]
end
生成pdf的 Prawn ,图片附件的回形针(photo has_attached_file :image)
关于javascript - 图像未使用 AngularJs 在 prawn pdf 中呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32173914/