How to check that a PDF file has some link with Ruby/Rspec?

Viewed 1706

I am using prawnpdf/pdf-inspector to test that content of a PDF generated in my Rails app is correct.

I would want to check that the PDF file contains a link with certain URL. I looked at yob/pdf-reader but haven't found any useful information related to this topic

Is it possible to test URLs within PDF with Ruby/RSpec?

I would want the following:

expect(urls_in_pdf(pdf)).to include 'https://example.com/users/1'
2 Answers

The https://github.com/yob/pdf-reader contains a method for each page called text. Do something like

    pdf = PDF::Reader.new("tmp/pdf.pdf")
    assert pdf.pages[0].text.include? 'https://example.com/users/1'

assuming what you are looking for is at the first page

Since pdf-inspector seems only to return text, you could try to use the pdf-reader directly (pdf-inspector uses it anyways).

reader = PDF::Reader.new("somefile.pdf")

reader.pages.each do |page|
  puts page.raw_content # This should also give you the link
end

Anyway I only did a quick look at the github page. I am not sure what raw_content exactly returns. But there is also a low-level method to directly access the objects of the pdf:

reader  = PDF::Reader.new("somefile.pdf")
puts reader.objects.inspect

With that it surely is possible to get the url.

Related