I have been tinkering with Combine_PDF to add a watermark to uploaded documents. I have managed to get it to work combining files locally hosted or through using net/http requests. I would like for it to watermark the file stored in active storage when it is downloaded by a user. I keep getting this error in the terminal:
Warning: parser advancing for unknown reason. Potential data-loss.
And this on the webpage:
Unknown PDF parsing error - malformed PDF file?
Checking documentation this is a very generic error for this gem. The PDF file uploaded to Active Storage is the same one downloaded from the website I used in the net/http parse function. Here is my code:
require 'combine_pdf'
require 'net/http'
def show
user = User.last
respond_to do |format|
format.html
format.pdf do
pdf = CombinePDF.new
url = url_for(@script.document)
pdf = CombinePDF.parse Net::HTTP.get_response(URI.parse(url)).body
pdf.pages.each {|page| page.textbox "#{user.first_name} #{user.last_name}", height: 70, width: 400, y: 200, x: 25}
send_data pdf.to_pdf, filename: "combined.pdf",
type: "application/pdf",
disposition: "inline"
end
end
end
As I stated before this setup works fine when pulling from external hosted pdfs:
require 'combine_pdf'
require 'net/http'
def show
user = User.last
respond_to do |format|
format.html
format.pdf do
pdf = CombinePDF.new
url = "https://www.americanexpress.com/content/dam/amex/us/staticassets/pdf/GCO/Test_PDF.pdf"
pdf = CombinePDF.parse Net::HTTP.get_response(URI.parse(url)).body
pdf.pages.each {|page| page.textbox "#{user.first_name} #{user.last_name}", height: 70, width: 400, y: 200, x: 25}
send_data pdf.to_pdf, filename: "combined.pdf",
type: "application/pdf",
disposition: "inline"
end
end
end
As you can see I used a test PDF from American Express and it works just fine. Its just an issue with Active Storage I can assume. I would prefer not to mess with temp files if at all possible.
Any help is greatly appreciated! Thanks to all in advance.
Try replacing:
pdf = CombinePDF.new
url = url_for(@script.document)
pdf = CombinePDF.parse Net::HTTP.get_response(URI.parse(url)).body
…with:
pdf = @script.document.open { |f| CombinePDF.load(f.path) }