ScreenshotNeo

BlogHow-to

How to Save PDFs to Amazon S3 in Ruby

Upload PDF files to Amazon S3 from Ruby with the AWS SDK or Rails Active Storage, set metadata correctly, handle large files, and troubleshoot failures.

By the ScreenshotNeo team30 September 20268 min read

How to Save PDFs to Amazon S3 in Ruby

To save a PDF to Amazon S3 in Ruby, use the AWS SDK for Ruby v3 and upload the local file through an S3 object. Set content_type: "application/pdf", choose a unique object key, and keep the object private unless you have a deliberate sharing design.

For Rails applications that already use model attachments, Active Storage is usually the better fit because Rails manages attachment records and the storage abstraction for you.

Choose the upload approach

Situation Recommended approach Why
Standalone script, worker, or service AWS SDK for Ruby v3 You control the bucket, key, metadata, retries, and access policy directly.
Rails model with attachments Active Storage with an S3 service Rails integrates the attachment association and storage layer.
PDF already available as an IO or string An S3 object upload operation that accepts a body No temporary file is required.

Prerequisites

  1. Create or select an S3 bucket and identify its AWS Region.
  2. Give the application credentials permission to upload to the intended bucket and prefix.
  3. Install the AWS SDK for Ruby v3 in the application. The official AWS SDK for Ruby repository identifies the SDK and its RubyGems distribution.
  4. Configure credentials through the AWS SDK credential chain or your deployment’s secret manager. Do not hard-code access keys in source code.
A Ruby service uploads a PDF object to an S3 bucket.
A Ruby service uploads a PDF object to an S3 bucket.

Upload a PDF from disk with AWS SDK for Ruby v3

The v3 S3 object API documents upload_file for files on disk. The following is the minimal pattern; confirm option support against the version installed in your application using the v3 object API reference.

require "aws-sdk-s3"

s3 = Aws::S3::Resource.new(region: ENV.fetch("AWS_REGION"))
bucket = ENV.fetch("S3_BUCKET")
key = "documents/report.pdf"

object = s3.bucket(bucket).object(key)
object.upload_file(
  "/path/to/report.pdf",
  content_type: "application/pdf"
)

puts "Uploaded s3://#{bucket}/#{key}"

Use a unique key

Keys identify objects within a bucket. Avoid using the same fixed key when uploads represent separate documents. A UUID, database ID, or date-based prefix prevents accidental overwrites.

require "securerandom"

key = "documents/#{Time.now.utc.strftime("%Y/%m/%d")}/#{SecureRandom.uuid}.pdf"

Upload an IO or in-memory PDF

When the PDF comes from a generator, HTTP response, or another stream, use an object operation that accepts a file-like body. The bucket API documents put_object options such as body and content_type.

require "aws-sdk-s3"

s3 = Aws::S3::Resource.new(region: ENV.fetch("AWS_REGION"))
object = s3.bucket(ENV.fetch("S3_BUCKET")).object("documents/generated-report.pdf")

File.open("/path/to/report.pdf", "rb") do |file|
  object.put(body: file, content_type: "application/pdf")
end

Rails: save PDFs with Active Storage

Use Active Storage when a Rails model needs an attachment association and Rails-managed storage. Follow the Rails Active Storage guide to configure an S3 service and credentials.

Configure the S3 service

In config/storage.yml, define an S3 service using the AWS SDK integration supplied by Active Storage. Keep bucket names, regions, and credentials in environment-backed configuration.

amazon:
  service: S3
  access_key_id: <%="#{ENV.fetch("AWS_ACCESS_KEY_ID")}"%>
  secret_access_key: <%="#{ENV.fetch("AWS_SECRET_ACCESS_KEY")}"%>
  region: <%="#{ENV.fetch("AWS_REGION")}"%>
  bucket: <%="#{ENV.fetch("S3_BUCKET")}"%>

Select the service in the environment configuration:

# config/environments/production.rb
config.active_storage.service = :amazon

Attach a generated or uploaded PDF

class Report < ApplicationRecord
  has_one_attached :pdf
end

report = Report.create!
report.pdf.attach(
  io: File.open("/path/to/report.pdf", "rb"),
  filename: "report.pdf",
  content_type: "application/pdf"
)

Supply the content type when it matters to downstream delivery. Active Storage can fall back to application/octet-stream when it cannot determine a type and none is supplied.

Metadata, access, and naming decisions

  • MIME type: Set application/pdf so clients and browsers receive the intended type.
  • Disposition: Decide whether downloads should use an attachment filename or display inline; configure this at delivery time rather than assuming upload success controls browser behavior.
  • Privacy: S3 objects are private by default according to the AWS SDK v3 reference. Keep them private unless public access is an intentional requirement.
  • Keys: Use unique, predictable prefixes such as reports/2026/09/uuid.pdf. Avoid putting sensitive information in keys.
  • Overwrite policy: Reusing a key replaces the existing object. Use versioned keys when documents must be retained.

Complete Ruby example with validation and error handling

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

path = ARGV.fetch(0)
raise "PDF does not exist" unless File.file?(path)

bucket = ENV.fetch("S3_BUCKET")
region = ENV.fetch("AWS_REGION")
key = "documents/#{Time.now.utc.strftime("%Y/%m/%d")}/#{SecureRandom.uuid}.pdf"

s3 = Aws::S3::Resource.new(region: region)
object = s3.bucket(bucket).object(key)

begin
  object.upload_file(path, content_type: "application/pdf")
  puts({ bucket: bucket, key: key, content_type: "application/pdf" }.inspect)
rescue Aws::S3::Errors::ServiceError => e
  warn "S3 upload failed: #{e.class}: #{e.message}"
  exit 1
end

Equivalent upload commands

Ruby is the primary implementation for this guide. These equivalents show the same S3 concepts in other environments.

cURL

curl --fail --upload-file report.pdf \
  -H "Content-Type: application/pdf" \
  "https://s3.REGION.amazonaws.com/BUCKET/documents/report.pdf"

Raw S3 requests require correctly signed AWS authentication. In production, use the AWS CLI, an SDK, or a presigned URL rather than an unsigned request.

Python

import boto3

s3 = boto3.client("s3", region_name="us-east-1")
s3.upload_file(
    "report.pdf",
    "your-bucket",
    "documents/report.pdf",
    ExtraArgs={"ContentType": "application/pdf"},
)

Node.js

import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import { readFile } from "node:fs/promises";

const client = new S3Client({ region: process.env.AWS_REGION });
const body = await readFile("report.pdf");

await client.send(new PutObjectCommand({
  Bucket: process.env.S3_BUCKET,
  Key: "documents/report.pdf",
  Body: body,
  ContentType: "application/pdf"
}));

Large PDFs and multipart behavior

The v3 object documentation describes multipart upload behavior for upload_file when files meet the configured multipart threshold. Thresholds and options depend on the installed SDK version, so check the v3 reference instead of copying a v2 example. The v2 client documentation describes a separate put_object streaming example and its own 5 GB method limit; do not apply that v2 statement broadly to v3 uploads.

  • Prefer upload_file for a local file when the SDK’s multipart handling is appropriate.
  • Use streaming or multipart-capable APIs for generated PDFs that are too large to hold in memory.
  • Do not convert a large PDF to a Base64 string; that increases memory use.
  • Record the bucket, key, byte size, checksum strategy, and application document ID so a retry can be identified.

Reliability and performance checklist

  • Keep the application and bucket in a suitable AWS Region to reduce latency.
  • Use bounded retries supplied by the SDK for transient failures, and make retries safe by using a deterministic key when duplicate objects are unacceptable.
  • Set an application timeout appropriate for the PDF size and network path.
  • Log request failures without logging credentials or sensitive PDF contents.
  • Verify the resulting object metadata when downstream systems depend on the MIME type.
  • For asynchronous jobs, persist an upload state and retry failed jobs rather than blocking a web request indefinitely.

Cost and security notes

S3 charges depend on storage, requests, transfer, and related AWS services. The research for this guide does not establish current prices, so check AWS pricing for your Region and workload. Keep IAM permissions scoped to the required bucket and prefix, and keep objects private by default. Upload permission does not grant a caller permission to read or share the object.

Troubleshooting

Symptom Likely cause Fix
MissingCredentialsError The SDK credential chain cannot find credentials. Configure the deployment role, environment, or standard AWS credential provider and verify the process can access it.
AccessDenied The identity lacks permission for the bucket, prefix, or encryption settings. Review the IAM policy, bucket policy, Region, and key prefix.
NoSuchBucket Bucket name is wrong or the request targets the wrong Region/account. Check S3_BUCKET, AWS account, and AWS_REGION.
PDF downloads as binary data Content type was omitted or inferred as application/octet-stream. Set content_type: "application/pdf" in the upload.
Existing file was replaced The same object key was reused. Generate a unique key or implement an intentional versioning policy.
Upload times out Large file, slow network, or unsuitable timeout. Use multipart-capable upload behavior, increase bounded timeouts, and move work to a background job.
Rails attachment is missing Active Storage service or attachment call is misconfigured. Confirm config.active_storage.service, the S3 service definition, and that the attachment includes a filename and MIME type.

Or skip the browser setup

If your Ruby application first needs to create a clean PDF or image from a webpage, ScreenshotNeo provides a website screenshot API and MCP server. It removes cookie banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, failed loads, and cache hits are not billed. The response identifies the result with X-Page-Verdict and X-Billed headers. An MCP server lets Claude, Cursor, and other MCP clients call screenshot tools.

A clean capture can be generated before the resulting file is stored in S3.
A clean capture can be generated before the resulting file is stored in S3.

See the ScreenshotNeo API documentation for request options. The basic call is:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
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)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' }); const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

You can then write the returned bytes to a file or stream and upload that artifact to S3 with the Ruby code above. ScreenshotNeo includes 1,000 screenshots per month free with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

FAQ

Should I use Active Storage or the AWS SDK directly?

Use Active Storage when the PDF belongs to a Rails model and you want Rails to manage attachment integration. Use the SDK directly in standalone services, scripts, or workflows that need explicit S3 control.

Is setting the PDF MIME type mandatory?

S3 can store the object without it, but explicitly setting application/pdf avoids incorrect downstream content handling.

Does a successful upload make the PDF public?

No. Upload authorization and read or sharing authorization are separate. S3 objects are private by default.

Can I safely retry an upload?

Yes, but decide whether retries should overwrite the same key or create a new version. A deterministic key gives an idempotent destination; a UUID key creates a new object on each attempt.