ScreenshotNeo

BlogHow-to

How to Save a PDF Online and Return a URL in Ruby

Generate a PDF in Ruby, upload it securely, and return the right temporary or permanent URL with Rails Active Storage or Amazon S3.

By the ScreenshotNeo team30 September 20269 min read

How to Save a PDF Online and Return a URL in Ruby

Short answer: saving a PDF online and returning a URL involves three separate operations: create the PDF, upload its bytes to storage, and generate a URL with the access behavior you want. A presigned PUT URL uploads a file; a presigned GET URL retrieves one. They are different URLs with different permissions.

In Ruby, you can use Rails Active Storage when your application already uses Rails and Active Record, or the AWS SDK for Ruby when you need explicit Amazon S3 operations. The examples below cover both approaches, including private files, public or CDN delivery, browser uploads, expiration, error handling, and complete runnable code.

Choose the URL you actually need

“Return a URL” can mean several things:

A PDF generator, storage object, and delivery URL are separate parts of the workflow.
A PDF generator, storage object, and delivery URL are separate parts of the workflow.
URL type Purpose Typical lifetime Who should receive it?
Presigned upload URL Accepts a PUT or form upload containing the PDF Short and temporary Your browser or upload client
Presigned download URL Lets a client download an existing private object with GET Temporary The intended recipient
Application URL Your Rails endpoint authenticates the request, then redirects or streams the file Stable application route Users of your application
Public or CDN URL Serves an object that is deliberately public Usually durable Anyone with the link

A presigned URL is a temporary bearer credential. Anyone who obtains it can normally use it until it expires, so do not log it unnecessarily or place it in an untrusted page. Amazon’s Ruby SDK supports presigned requests for operations such as GET and PUT; the HTTP method must match the operation you intended. See the AWS SDK for Ruby examples and the S3 object API.

Option 1: Generate a PDF and upload it with the AWS SDK for Ruby

This approach gives you direct control over the S3 bucket, object key, permissions, expiration, and response format. Keep the bucket name, region, and credentials in deployment configuration rather than source code.

PUT uploads a PDF; GET retrieves one.
PUT uploads a PDF; GET retrieves one.

1. Install the gems

gem install aws-sdk-s3 prawn

The Prawn 2.5.0 manual documents creating a document with Prawn::Document and Prawn::Document.generate. Prawn creates the PDF; it does not host the result online. Hosting starts when you upload the generated bytes to storage. See the Prawn 2.5.0 manual.

2. Configure environment variables

export AWS_REGION=us-east-1
export PDF_BUCKET=my-private-pdf-bucket

The AWS SDK reads credentials from its standard provider chain, such as an IAM role, environment variables, or a local profile. Give the runtime only the S3 permissions it needs, normally permission to put objects and create the specific presigned requests required by your service.

3. Complete Ruby example

require "aws-sdk-s3"
require "prawn"
require "securerandom"

region = ENV.fetch("AWS_REGION")
bucket = ENV.fetch("PDF_BUCKET")
key = "documents/#{SecureRandom.uuid}.pdf"

pdf_bytes = Prawn::Document.new do |pdf|
  pdf.text "Invoice 1007", size: 24, style: :bold
  pdf.move_down 18
  pdf.text "Generated by a Ruby application."
  pdf.text "Created at: #{Time.now.utc.iso8601}"
end.render

s3 = Aws::S3::Client.new(region: region)
s3.put_object(
  bucket: bucket,
  key: key,
  body: StringIO.new(pdf_bytes),
  content_type: "application/pdf",
  content_disposition: "inline; filename=invoice-1007.pdf"
)

object = Aws::S3::Object.new(bucket: bucket, key: key, client: s3)
presigner = Aws::S3::Presigner.new(client: s3)
download_url = presigner.presigned_url(
  :get_object,
  bucket: bucket,
  key: key,
  expires_in: 900,
  response_content_type: "application/pdf",
  response_content_disposition: "inline; filename=invoice-1007.pdf"
)

puts download_url

The output is a temporary retrieval URL. It is not a permanent public address. If you need a stable link, return your own route such as /documents/:id, look up the object after authenticating the caller, and either redirect to a newly generated presigned URL or stream the file through your application.

Upload with a presigned PUT URL

If the PDF is produced in a browser or another service, your Ruby server can create an upload URL without receiving the file bytes itself.

require "aws-sdk-s3"

s3 = Aws::S3::Client.new(region: ENV.fetch("AWS_REGION"))
presigner = Aws::S3::Presigner.new(client: s3)

key = "incoming/#{SecureRandom.uuid}.pdf"
upload_url = presigner.presigned_url(
  :put_object,
  bucket: ENV.fetch("PDF_BUCKET"),
  key: key,
  expires_in: 600,
  content_type: "application/pdf"
)

puts upload_url
puts key

The client must send a PUT request and, when you signed content_type, use the same Content-Type: application/pdf header. A successful upload does not automatically mean your application has recorded the object. Persist the key and metadata after the client reports success, or verify the object with a server-side HEAD request.

Equivalent clients for a presigned PUT

# cURL
curl -X PUT -H "Content-Type: application/pdf" --upload-file invoice.pdf "PRESIGNED_PUT_URL"
# Python
import requests

with open("invoice.pdf", "rb") as f:
    response = requests.put(
        "PRESIGNED_PUT_URL",
        data=f,
        headers={"Content-Type": "application/pdf"},
        timeout=90,
    )
response.raise_for_status()
// Node.js
import { readFile } from "node:fs/promises";

const bytes = await readFile("invoice.pdf");
const response = await fetch("PRESIGNED_PUT_URL", {
  method: "PUT",
  headers: { "Content-Type": "application/pdf" },
  body: bytes,
});
if (!response.ok) throw new Error(`Upload failed: ${response.status}`);

Option 2: Rails Active Storage

Active Storage is usually the simplest choice when the PDF belongs to a Rails model. Rails supports local disk storage for development and testing and cloud services for production. The default delivery model is private and uses signed URLs. The Active Storage guide also documents direct browser uploads, redirect delivery, and proxy delivery.

Attach a generated PDF

# Gemfile
gem "prawn"

# app/models/report.rb
class Report < ApplicationRecord
  has_one_attached :pdf
end

# app/services/report_pdf.rb
class ReportPdf
  def self.attach_to(report)
    bytes = Prawn::Document.new do |pdf|
      pdf.text "Report #{report.id}", size: 22
      pdf.move_down 12
      pdf.text report.title.to_s
    end.render

    report.pdf.attach(
      io: StringIO.new(bytes),
      filename: "report-#{report.id}.pdf",
      content_type: "application/pdf"
    )
    report.save!
  end
end
# app/controllers/reports_controller.rb
class ReportsController < ApplicationController
  def pdf
    report = current_user.reports.find(params[:id])
    redirect_to rails_blob_path(report.pdf, disposition: "inline")
  end
end

A Rails blob URL is application-level indirection. In redirect mode, Rails sends the client to the storage service; the guide describes a five-minute HTTP expiration for that redirect. That does not mean every underlying storage URL has the same lifetime. Proxy mode sends file data through your application and can fit a CDN design, but increases application traffic. Choose the mode based on your access-control and delivery requirements.

Direct browser uploads

Active Storage can upload directly from a browser to the configured cloud service. Configure the exact origins, bucket permissions, and storage CORS rules for your deployment. Do not copy a permissive CORS policy without checking which origins and headers your application actually needs. After the upload, attach the signed blob identifier to the intended record and authorize access when serving it.

Public, private, redirect, or proxy?

Requirement Recommended design Trade-off
Only a logged-in user may read the PDF Private storage plus an authenticated application endpoint Every request passes authorization logic
Share for 15 minutes Presigned GET URL with a short expiration The link stops working after expiry
Embed on a public website Public or CDN URL, or a signed CDN URL Anyone with access can retrieve it
Keep storage hidden from clients Rails proxy delivery or an application download action Your servers handle file traffic
Let browsers upload large files Presigned PUT or multipart upload Requires careful client error handling and CORS

Rails warns that Active Storage controllers are publicly accessible by default and that anyone who knows a URL may access the file. Applications with stricter requirements should implement authenticated controllers. Public Active Storage also requires explicit configuration and correctly configured bucket permissions.

Common errors and fixes

  • 403 SignatureDoesNotMatch: the HTTP method, region, key, headers, or query string changed after signing. Use the exact method and signed headers, and generate the URL for the bucket’s real region.
  • AccessDenied: the IAM policy, bucket policy, object ownership, or key is wrong. Check the effective role and the precise bucket/key ARN.
  • Upload succeeds but download fails: you may be treating a PUT URL as a GET URL, or you may have stored the wrong object key. Persist the key separately from the temporary upload URL.
  • The browser reports CORS failure: configure the storage service for the actual origin, method, and headers. A server-side cURL test can distinguish CORS from an S3 authorization error.
  • PDF opens as a download instead of in the browser: set Content-Type: application/pdf and choose Content-Disposition: inline when generating the object or response.
  • Rails link expires unexpectedly: Rails blob delivery can redirect to a short-lived service URL. Generate a fresh application link when needed, or use proxy delivery.
  • Blank or corrupt PDF: ensure the upload body contains binary bytes, not a UTF-8 encoded string transformation. In Ruby, use an IO such as StringIO or the file opened in binary mode.
  • Success redirect is trusted as proof: a presigned POST success redirect is optional behavior, not a substitute for checking the upload result. Record completion only after a confirmed response or server-side verification.

Performance, reliability, and cost

  • Generate the PDF in memory for small documents; use a temporary file or streaming strategy when documents are large.
  • Use deterministic object keys when you need idempotency, or UUID keys when retries must never overwrite an earlier document.
  • Store the object key, checksum if available, content type, byte size, creator, and creation time in your database. The key is the durable identifier; a presigned URL is not.
  • Retry transient network failures with bounded backoff, but do not blindly retry a request that may have completed. A follow-up HEAD check can make retries safe.
  • Set lifecycle rules for abandoned uploads and old versions if your retention policy permits it.
  • There is no evidence in the supplied sources for a universal performance or price ranking between Active Storage and direct S3 integration. Choose based on your existing Rails model lifecycle, access pattern, and operational controls.

Or skip the browser setup

If what you need is a clean PDF or image capture of a rendered web page, ScreenshotNeo provides a single API endpoint. It is a screenshot and PDF capture service, not a general-purpose object store, so use S3 or Active Storage when you need durable PDF hosting. ScreenshotNeo is useful when the PDF itself must be rendered from a URL and you want to avoid maintaining browser automation.

Cookie banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result. Its MCP server lets AI agents such as Claude or Cursor call take_screenshot, get_page_info, and capture_pdf. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots.

See the ScreenshotNeo API documentation for all options.

# cURL
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
# Python
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
// Node.js
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Create a free ScreenshotNeo account with 1,000 screenshots each month and no card.

Implementation checklist

  1. Decide whether you need an upload URL, a download URL, or a stable application route.
  2. Generate the PDF with Prawn or another library.
  3. Choose Active Storage or direct S3 operations.
  4. Keep bucket names, regions, and credentials in deployment configuration.
  5. Set the correct content type and disposition.
  6. Store the object key and metadata in your database.
  7. Use short-lived presigned URLs for private sharing.
  8. Authorize application endpoints before issuing a download link.
  9. Verify uploads server-side and handle retries safely.
  10. Apply retention and lifecycle rules to temporary or obsolete files.

FAQ

Can a PDF library return a URL by itself?

No. Prawn creates PDF bytes. You still need storage and a delivery URL.

No. PUT authorizes upload. Generate a separate GET URL for retrieval.

Should I make the S3 bucket public?

Only when the document is intentionally public. Private storage with authenticated application links is safer for user-specific files.

How long should a presigned URL last?

Use the shortest period that fits the workflow: minutes for an upload or one-time share, longer only when the recipient genuinely needs it.

When is Active Storage the better choice?

Use it when the PDF belongs to Rails records and you want attachment lifecycle, validations, and Rails URL helpers. Use the SDK directly when you need explicit S3 operations or a non-Rails service.