如何在ROR中将Word文件转换为PDF

时间:2018-12-05 14:08:14

标签: ruby-on-rails amazon-s3 rails-activejob rails-activestorage ruby-on-rails-5.2

我正在使用Libreconv gem将word转换为doc,但是它不适用于S3

bucket = Aws::S3::Bucket.new('bucket-name')
object = bucket.object file.attachment.blob.key
path = object.presigned_url(:get)
Libreconv.convert(path, "public/test.pdf")

如果我尝试使用Libreconv将此路径转换为PDF,则会给我文件名过长的错误。我在ActiveJobs下编写了此代码。因此,请根据ActiveJobs为我提供解决方案。

有人可以建议我如何将Word文件转换为pdf。 路径为https://domain.s3.amazonaws.com/Bf5qPUP3znZGCHCcTWHcR5Nn?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIZ6RZ7J425ORVUYQ%2F20181206%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20181206T051240Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Signature=b89c47a324b2aa423bf64dfb343e3b3c90dce9b54fa9fe1bc4efa9c248e912f9

我得到的错误是

Error: source file could not be loaded *** Errno::ENAMETOOLONG Exception: File name too long @ rb_sysopen - /tmp/Bf5qPUP3znZGCHCcTWHcR5Nn?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIZ6RZ7J425ORVUYQ%2F20181206%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20181206T051240Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Signature=b89c47a324b2aa423bf64dfb343e3b3c90dce9b54fa9fe1bc4efa9c248e912f9.pd

2 个答案:

答案 0 :(得分:0)

似乎您已创建PDF,其中包含从S3提取docx所需的所有参数。

我想它发生在this line

target_tmp_file = "#{target_path}/#{File.basename(@source, ".*")}.#{File.basename(@convert_to, ":*")}"

@sourcehttps://domain.s3.amazonaws.com/Bf5qPUP3znZGCHCcTWHcR5Nn?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIZ6RZ7J425ORVUYQ%2F20181206%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20181206T051240Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Signature=b89c47a324b2aa423bf64dfb343e3b3c90dce9b54fa9fe1bc4efa9c248e912f9

> File.basename(@source, ".*")
=> "Bf5qPUP3znZGCHCcTWHcR5Nn?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIZ6RZ7J425ORVUYQ%2F20181206%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20181206T051240Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Signature=b89c47a324b2aa423bf64dfb343e3b3c90dce9b54fa9fe1bc4efa9c248e912f9"

结果,Libreconv gem尝试使用此长名称创建tmp文件,并且该文件太长-这就是引发错误的原因。

可能的解决方案:将过程分为获取文件和转换文件的单独步骤。像这样:

require "open-uri"

bucket = Aws::S3::Bucket.new('bucket-name')
object = bucket.object file.attachment.blob.key
path = object.presigned_url(:get)

doc_file = open(path)
begin
  Libreconv.convert(doc_file.path, "public/test.pdf")
ensure
  doc_file.delete
end

答案 1 :(得分:0)

  

以下是使用Combine pdf gem的答案

tape = Tape.new(file)
result = tape.preview
tempfile = Tempfile.new(['foo', '.pdf'])
File.open(tempfile, 'wb') do |f|
  f.write result
end
path = tempfile.path
combine_pdf(path)
  

对于我曾经使用过的S3加载文件

object = @bucket.object object_key
path = object.presigned_url(:get)
response = Net::HTTP.get_response(URI.parse(path)).body