2

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.

Brendan
  • 57
  • 6

1 Answers1

2

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) }
Summer
  • 141
  • 3
  • wow!!! This is terrific and works the way I want it to. If you don't mind please explaining this part: { |f| CombinePDF.load(f.path) }. Is the variable f for file? I get the CombinePDF.load function loading per the gem docs and now even get the script.document.open for rails opening that file in memory. – Brendan Jul 11 '21 at 02:24