PDF 支持

使用 Claude 处理 PDF:从您的文档中提取文本、分析图表并理解视觉内容。

您可以向 Claude 询问您所提供的 PDF 中的任何文本、图片、图表和表格。一些示例用例:

  • 分析财务报告并理解图表/表格
  • 从法律文档中提取关键信息
  • 协助文档翻译
  • 将文档信息转换为结构化格式

开始之前

检查 PDF 要求

Claude 可处理任何标准 PDF。请确保您的请求大小满足以下要求:

要求限制
最大请求大小第一方 Claude API 上为 128 MB(因平台而异;请参阅请求大小限制)
每个请求的最大页数600(当请求的上下文窗口小于 1M 令牌时为 100)
格式标准 PDF(无密码/加密)

这两项限制均针对整个请求负载,包括与 PDF 一起发送的任何其他内容。对于大型 PDF,请考虑使用 Files API 上传并通过 file_id 引用,以保持请求负载较小。

由于 PDF 支持依赖于 Claude 的视觉能力,因此它与其他视觉任务一样受到相同的限制和注意事项的约束。

支持的平台和模型

所有活跃模型均支持 PDF 处理。

使用 Claude 处理 PDF

发送您的第一个 PDF 请求

从一个使用 Messages API 的简单示例开始。您可以通过三种方式向 Claude 提供 PDF:

  1. 作为指向在线托管 PDF 的 URL 引用
  2. 作为 document 内容块中的 base64 编码 PDF
  3. 通过来自 Files API 的 file_id

选项 1:基于 URL 的 PDF 文档

最简单的方法是直接从 URL 引用 PDF:

示例代码
curl https://api.anthropic.com/v1/messages \
  -H "content-type: application/json" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2026-10-21" \
  -d '{
    "model": "claude-opus-5-5",
    "max_tokens": 1024,
    "messages": [{
      "role": "user",
      "content": [{
        "type": "document",
        "source": {
          "type": "url",
          "url": "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf"
        }
      },
      {
        "type": "text",
        "text": "What are the key findings in this document?"
      }]
    }]
  }'
示例代码
ant messages create <<'YAML'
model: claude-opus-5-5
max_tokens: 1024
messages:
  - role: user
    content:
      - type: document
        source:
          type: url
          url: https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf
      - type: text
        text: What are the key findings in this document?
YAML
示例代码
client = anthropic.Anthropic()
message = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "document",
                    "source": {
                        "type": "url",
                        "url": "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf",
                    },
                },
                {"type": "text", "text": "What are the key findings in this document?"},
            ],
        }
    ],
)

print(message.content)
示例代码
const anthropic = new Anthropic();

const response = await anthropic.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 1024,
  messages: [
    {
      role: "user",
      content: [
        {
          type: "document",
          source: {
            type: "url",
            url: "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf"
          }
        },
        {
          type: "text",
          text: "What are the key findings in this document?"
        }
      ]
    }
  ]
});

console.log(response);
示例代码
var client = new AnthropicClient();

// 使用 URL 创建文档块
var documentParam = new DocumentBlockParam
{
    Source = new UrlPdfSource
    {
        Url = "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf",
    },
};

// 创建包含文档和文本内容块的消息
var message = await client.Messages.Create(new MessageCreateParams
{
    Model = Model.ClaudeOpus5_5,
    MaxTokens = 1024,
    Messages =
    [
        new UserMessageParam
        {
            Content = new List<ContentBlockParam>
            {
                documentParam,
                new TextBlockParam("What are the key findings in this document?"),
            },
        },
    ],
});

Console.WriteLine(string.Join("\n", message.Content));
示例代码
client := anthropic.NewClient()

message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
	Model:     anthropic.ModelClaudeOpus5_5,
	MaxTokens: 1024,
	Messages: []anthropic.MessageParam{
		anthropic.NewUserMessage(
			anthropic.NewDocumentBlock(anthropic.URLPDFSourceParam{
				URL: "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf",
			}),
			anthropic.NewTextBlock("What are the key findings in this document?"),
		),
	},
})
if err != nil {
	panic(err)
}

fmt.Printf("%+v\n", message.Content)
示例代码
AnthropicClient client = AnthropicOkHttpClient.fromEnv();

// 创建带有 URL 的文档块
DocumentBlockParam documentParam = DocumentBlockParam.builder()
    .source(
        UrlPdfSource.builder()
            .url(
                "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf"
            )
            .build()
    )
    .build();

// 创建包含文档和文本内容块的消息
MessageCreateParams params = MessageCreateParams.builder()
    .model(Model.CLAUDE_OPUS_5_5)
    .maxTokens(1024)
    .addUserMessageOfContentBlockParams(
        List.of(
            ContentBlockParam.ofDocument(documentParam),
            ContentBlockParam.ofText(
                TextBlockParam.builder()
                    .text("What are the key findings in this document?")
                    .build()
            )
        )
    )
    .build();

Message message = client.messages().create(params);
System.out.println(message.content());
示例代码
$client = new Client();

$message = $client->messages->create(
    maxTokens: 1024,
    messages: [
        [
            'role' => 'user',
            'content' => [
                [
                    'type' => 'document',
                    'source' => [
                        'type' => 'url',
                        'url' => 'https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf',
                    ],
                ],
                [
                    'type' => 'text',
                    'text' => 'What are the key findings in this document?',
                ],
            ],
        ],
    ],
    model: 'claude-opus-5-5',
);

echo $message;
示例代码
anthropic = Anthropic::Client.new

message = anthropic.messages.create(
  model: "claude-opus-5-5",
  max_tokens: 1024,
  messages: [
    {
      role: "user",
      content: [
        {
          type: "document",
          source: {
            type: "url",
            url: "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf"
          }
        },
        {type: "text", text: "What are the key findings in this document?"}
      ]
    }
  ]
)

puts(message.content)

响应会在 content 中以文本块的形式返回 Claude 的分析,并在 usage 中返回令牌消耗情况:

示例代码
{
  "id": "msg_01Hfp8YuFjQ55VgWbpdHDehB",
  "type": "message",
  "role": "assistant",
  "model": "claude-opus-5-5",
  "content": [
    {
      "type": "text",
      "text": "This document is an addendum to the Claude 3 model card, reporting updated evaluation results. The key findings include..."
    }
  ],
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 45000,
    "output_tokens": 300
  }
}

选项 2:Base64 编码的 PDF 文档

如果您需要从本地系统发送 PDF,或者在没有可用 URL 的情况下:

示例代码
# 方法 1:获取远程 PDF 并进行编码
curl -sL "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf" | base64 | tr -d '\n' > pdf_base64.txt

# 方法 2:对本地 PDF 文件进行编码
# base64 document.pdf | tr -d '\n' > pdf_base64.txt

# 使用 pdf_base64.txt 的内容创建 JSON 请求文件
jq -n --rawfile PDF_BASE64 pdf_base64.txt '{
  "model": "claude-opus-5-5",
  "max_tokens": 1024,
  "messages": [{
    "role": "user",
    "content": [{
      "type": "document",
      "source": {
        "type": "base64",
        "media_type": "application/pdf",
        "data": $PDF_BASE64
      }
    },
    {
      "type": "text",
      "text": "What are the key findings in this document?"
    }]
  }]
}' > request.json

# 使用该 JSON 文件发送 API 请求
curl https://api.anthropic.com/v1/messages \
  -H "content-type: application/json" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2026-10-21" \
  -d @request.json
示例代码
ant messages create --model claude-opus-5-5 --max-tokens 1024 <<'YAML'
messages:
  - role: user
    content:
      - type: document
        source:
          type: base64
          media_type: application/pdf
          data: "@./document.pdf"
      - type: text
        text: What are the key findings in this document?
YAML
示例代码
import base64
import httpx2

# 首先,加载 PDF 并进行编码
pdf_url = "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf"
pdf_data = base64.standard_b64encode(
    httpx2.get(pdf_url, follow_redirects=True).content
).decode("utf-8")

# 替代方案:从本地文件加载
# with open("document.pdf", "rb") as f:
#     pdf_data = base64.standard_b64encode(f.read()).decode("utf-8")

# 使用 base64 编码发送给 Claude
client = anthropic.Anthropic()
message = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "document",
                    "source": {
                        "type": "base64",
                        "media_type": "application/pdf",
                        "data": pdf_data,
                    },
                },
                {"type": "text", "text": "What are the key findings in this document?"},
            ],
        }
    ],
)

print(message.content)
示例代码
// 方法 1:获取远程 PDF 并进行编码
const pdfURL =
  "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf";
const pdfResponse = await fetch(pdfURL);
const arrayBuffer = await pdfResponse.arrayBuffer();
const pdfBase64 = Buffer.from(arrayBuffer).toString("base64");

// 方法 2:从本地文件加载
// import { readFile } from "node:fs/promises";
// const pdfBase64 = (await readFile("document.pdf")).toString("base64");

// 发送包含 base64 编码 PDF 的 API 请求
const anthropic = new Anthropic();
const response = await anthropic.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 1024,
  messages: [
    {
      role: "user",
      content: [
        {
          type: "document",
          source: {
            type: "base64",
            media_type: "application/pdf",
            data: pdfBase64
          }
        },
        {
          type: "text",
          text: "What are the key findings in this document?"
        }
      ]
    }
  ]
});

console.log(response);
示例代码
var client = new AnthropicClient();

// 方法 1:下载远程 PDF 并进行编码
var pdfUrl = "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf";
using var httpClient = new HttpClient();
var pdfBase64 = Convert.ToBase64String(await httpClient.GetByteArrayAsync(pdfUrl));

// 方法 2:从本地文件加载
// var pdfBase64 = Convert.ToBase64String(await File.ReadAllBytesAsync("document.pdf"));

// 使用 base64 数据创建文档块
var documentParam = new DocumentBlockParam
{
    Source = new Base64PdfSource { Data = pdfBase64 },
};

// 创建包含文档和文本内容块的消息
var message = await client.Messages.Create(new MessageCreateParams
{
    Model = Model.ClaudeOpus5_5,
    MaxTokens = 1024,
    Messages =
    [
        new UserMessageParam
        {
            Content = new List<ContentBlockParam>
            {
                documentParam,
                new TextBlockParam("What are the key findings in this document?"),
            },
        },
    ],
});

Console.WriteLine(string.Join("\n", message.Content));
示例代码
// 首先,加载 PDF 并进行编码
pdfURL := "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf"
resp, err := http.Get(pdfURL)
if err != nil {
	panic(err)
}
defer resp.Body.Close()
pdfBytes, err := io.ReadAll(resp.Body)
if err != nil {
	panic(err)
}
pdfBase64 := base64.StdEncoding.EncodeToString(pdfBytes)

// 替代方案:从本地文件加载(需在导入中添加 "os")
// pdfBytes, err := os.ReadFile("document.pdf")
// pdfBase64 := base64.StdEncoding.EncodeToString(pdfBytes)

// 使用 base64 编码发送给 Claude
client := anthropic.NewClient()
message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
	Model:     anthropic.ModelClaudeOpus5_5,
	MaxTokens: 1024,
	Messages: []anthropic.MessageParam{
		anthropic.NewUserMessage(
			anthropic.NewDocumentBlock(anthropic.Base64PDFSourceParam{
				Data: pdfBase64,
			}),
			anthropic.NewTextBlock("What are the key findings in this document?"),
		),
	},
})
if err != nil {
	panic(err)
}

fmt.Printf("%+v\n", message.Content)
示例代码
AnthropicClient client = AnthropicOkHttpClient.fromEnv();

// 方法 1:下载远程 PDF 并进行编码
String pdfUrl =
    "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf";
HttpClient httpClient = HttpClient.newBuilder()
    .followRedirects(HttpClient.Redirect.NORMAL)
    .build();
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create(pdfUrl))
    .GET()
    .build();

HttpResponse<byte[]> response = httpClient.send(
    request,
    HttpResponse.BodyHandlers.ofByteArray()
);
String pdfBase64 = Base64.getEncoder().encodeToString(response.body());

// 方法 2:从本地文件加载
// byte[] fileBytes = Files.readAllBytes(Path.of("document.pdf"));
// String pdfBase64 = Base64.getEncoder().encodeToString(fileBytes);

// 使用 base64 数据创建文档块
DocumentBlockParam documentParam = DocumentBlockParam.builder()
    .source(Base64PdfSource.builder()
        .data(pdfBase64)
        .build())
    .build();

// 创建包含文档和文本内容块的消息
MessageCreateParams params = MessageCreateParams.builder()
    .model(Model.CLAUDE_OPUS_5_5)
    .maxTokens(1024)
    .addUserMessageOfContentBlockParams(
        List.of(
            ContentBlockParam.ofDocument(documentParam),
            ContentBlockParam.ofText(
                TextBlockParam.builder()
                    .text("What are the key findings in this document?")
                    .build()
            )
        )
    )
    .build();

Message message = client.messages().create(params);
System.out.println(message.content());
示例代码
$client = new Client();

// 首先,加载 PDF 并进行编码
$pdf_url = 'https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf';
$pdf_data = base64_encode(file_get_contents($pdf_url));

// 替代方案:从本地文件加载
// $pdf_data = base64_encode(file_get_contents('document.pdf'));

// 使用 base64 编码发送给 Claude
$message = $client->messages->create(
    maxTokens: 1024,
    messages: [
        [
            'role' => 'user',
            'content' => [
                [
                    'type' => 'document',
                    'source' => [
                        'type' => 'base64',
                        'media_type' => 'application/pdf',
                        'data' => $pdf_data,
                    ],
                ],
                [
                    'type' => 'text',
                    'text' => 'What are the key findings in this document?',
                ],
            ],
        ],
    ],
    model: 'claude-opus-5-5',
);

echo $message;
示例代码
require "open-uri"

# 首先,加载 PDF 并进行编码
pdf_url = "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf"
pdf_bytes = URI.open(pdf_url, "rb") { |f| f.read }
pdf_data = [pdf_bytes].pack("m0") # Encode as base64 without newlines

# 替代方案:从本地文件加载
# pdf_data = [File.binread("document.pdf")].pack("m0")

# 使用 base64 编码发送给 Claude
anthropic = Anthropic::Client.new
message = anthropic.messages.create(
  model: Anthropic::Model::CLAUDE_OPUS_5_5,
  max_tokens: 1024,
  messages: [
    {
      role: "user",
      content: [
        {
          type: "document",
          source: {
            type: "base64",
            media_type: "application/pdf",
            data: pdf_data
          }
        },
        {type: "text", text: "What are the key findings in this document?"}
      ]
    }
  ]
)

puts(message.content)

选项 3:Files API

对于您将重复使用的 PDF,或者当您希望避免编码开销时,请使用 Files API:

示例代码
# 首先,将您的 PDF 上传到 Files API
curl -sS -X POST https://api.anthropic.com/v1/files \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2026-10-21" \
  -F "file=@document.pdf"

# 然后在您的消息中使用上传响应中的 file_id
curl https://api.anthropic.com/v1/messages \
  -H "content-type: application/json" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2026-10-21" \
  -d '{
    "model": "claude-opus-5-5",
    "max_tokens": 1024,
    "messages": [{
      "role": "user",
      "content": [{
        "type": "document",
        "source": {
          "type": "file",
          "file_id": "'"$FILE_ID"'"
        }
      },
      {
        "type": "text",
        "text": "What are the key findings in this document?"
      }]
    }]
  }'
示例代码
# 首先,将您的 PDF 上传到 Files API
ant files upload --file ./document.pdf

# 然后在您的消息中使用上传响应中的 file_id
ant messages create <<YAML
model: claude-opus-5-5
max_tokens: 1024
messages:
  - role: user
    content:
      - type: document
        source:
          type: file
          file_id: $FILE_ID
      - type: text
        text: What are the key findings in this document?
YAML
示例代码
client = anthropic.Anthropic()

# 上传 PDF 文件
with open("/path/to/document.pdf", "rb") as f:
    file_upload = client.files.upload(file=("document.pdf", f, "application/pdf"))

# 在消息中使用已上传的文件
message = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "document",
                    "source": {"type": "file", "file_id": file_upload.id},
                },
                {"type": "text", "text": "What are the key findings in this document?"},
            ],
        }
    ],
)

print(message.content)
示例代码
import Anthropic, { toFile } from "@anthropic-ai/sdk";
import fs from "node:fs";

const anthropic = new Anthropic();

// 上传 PDF 文件
const fileUpload = await anthropic.files.upload({
  file: await toFile(fs.createReadStream("/path/to/document.pdf"), undefined, {
    type: "application/pdf"
  })
});

// 在消息中使用已上传的文件
const response = await anthropic.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 1024,
  messages: [
    {
      role: "user",
      content: [
        {
          type: "document",
          source: {
            type: "file",
            file_id: fileUpload.id
          }
        },
        {
          type: "text",
          text: "What are the key findings in this document?"
        }
      ]
    }
  ]
});

console.log(response);
示例代码
var client = new AnthropicClient();

// 上传 PDF 文件
var fileUpload = await client.Files.Upload(new FileUploadParams
{
    File = new BinaryContent
    {
        Stream = File.OpenRead("/path/to/document.pdf"),
        FileName = "document.pdf",
        ContentType = new("application/pdf"),
    },
});

// 在消息中使用已上传的文件
var message = await client.Messages.Create(new MessageCreateParams
{
    Model = Model.ClaudeOpus5_5,
    MaxTokens = 1024,
    Messages =
    [
        new UserMessageParam
        {
            Content = new List<ContentBlockParam>
            {
                new DocumentBlockParam
                {
                    Source = new FileDocumentSource { FileID = fileUpload.ID },
                },
                new TextBlockParam("What are the key findings in this document?"),
            },
        },
    ],
});

Console.WriteLine(string.Join("\n", message.Content));
示例代码
client := anthropic.NewClient()

// 上传 PDF 文件
pdfFile, err := os.Open("/path/to/document.pdf")
if err != nil {
	panic(err)
}
defer pdfFile.Close()

fileUpload, err := client.Files.Upload(context.TODO(), anthropic.FileUploadParams{
	File: anthropic.File(pdfFile, "document.pdf", "application/pdf"),
})
if err != nil {
	panic(err)
}

// 在消息中使用已上传的文件
message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
	Model:     anthropic.ModelClaudeOpus5_5,
	MaxTokens: 1024,
	Messages: []anthropic.MessageParam{
		anthropic.NewUserMessage(
			anthropic.NewDocumentBlock(anthropic.FileDocumentSourceParam{
				FileID: fileUpload.ID,
			}),
			anthropic.NewTextBlock("What are the key findings in this document?"),
		),
	},
})
if err != nil {
	panic(err)
}

fmt.Printf("%+v\n", message.Content)
示例代码
AnthropicClient client = AnthropicOkHttpClient.fromEnv();

// 上传 PDF 文件
FileMetadata file = client
    .files()
    .upload(FileUploadParams.builder()
        .file(Path.of("/path/to/document.pdf"))
        .build());

// 在消息中使用已上传的文件
MessageCreateParams params = MessageCreateParams.builder()
    .model(Model.CLAUDE_OPUS_5_5)
    .maxTokens(1024)
    .addUserMessageOfContentBlockParams(
        List.of(
            ContentBlockParam.ofDocument(
                DocumentBlockParam.builder()
                    .fileSource(file.id())
                    .build()
            ),
            ContentBlockParam.ofText(
                TextBlockParam.builder()
                    .text("What are the key findings in this document?")
                    .build()
            )
        )
    )
    .build();

Message message = client.messages().create(params);
System.out.println(message.content());
示例代码
use Anthropic\Core\FileParam;

$client = new Client();

// 上传 PDF 文件
$file_upload = $client->files->upload(
    file: FileParam::fromResource(fopen('/path/to/document.pdf', 'r'), contentType: 'application/pdf'),
);

// 在消息中使用已上传的文件
$message = $client->messages->create(
    maxTokens: 1024,
    messages: [
        [
            'role' => 'user',
            'content' => [
                [
                    'type' => 'document',
                    'source' => [
                        'type' => 'file',
                        'fileID' => $file_upload->id,
                    ],
                ],
                [
                    'type' => 'text',
                    'text' => 'What are the key findings in this document?',
                ],
            ],
        ],
    ],
    model: 'claude-opus-5-5',
);

echo $message;
示例代码
anthropic = Anthropic::Client.new

# 上传 PDF 文件
file_upload = File.open("/path/to/document.pdf", "rb") do |f|
  anthropic.files.upload(
    file: Anthropic::FilePart.new(f, filename: "document.pdf", content_type: "application/pdf")
  )
end

# 在消息中使用已上传的文件
message = anthropic.messages.create(
  model: Anthropic::Model::CLAUDE_OPUS_5_5,
  max_tokens: 1024,
  messages: [
    {
      role: "user",
      content: [
        {
          type: "document",
          source: {type: "file", file_id: file_upload.id}
        },
        {type: "text", text: "What are the key findings in this document?"}
      ]
    }
  ]
)

puts(message.content)

PDF 支持的工作原理

当您向 Claude 发送 PDF 时,会发生以下步骤:

系统提取文档的内容。

  • 系统将文档的每一页转换为图像。
  • 每一页的文本会被提取出来,并与每一页的图像一起提供。

Claude 同时分析文本和图像。

  • 文档以文本和图像组合的形式提供以供分析。
  • 这使用户能够就 PDF 的视觉元素(如图表、示意图和其他非文本内容)寻求见解。

Claude 作出响应,并在相关时引用 PDF 的内容。

Claude 在响应时可以同时引用文本和视觉内容。您可以通过将 PDF 支持与以下功能集成来进一步提升性能:

估算您的成本

PDF 文件的令牌数取决于从文档中提取的文本总量和页数:

  • 文本令牌成本:根据内容密度,每页通常使用 1,500–3,000 个令牌。适用标准 API 定价,无额外的 PDF 费用。
  • 图像令牌成本:由于每页都会被转换为图像,因此适用相同的基于图像的成本计算。

您可以使用令牌计数来估算您特定 PDF 的成本。

优化 PDF 处理

提升性能

遵循以下最佳实践以获得最佳结果:

  • 在请求中将 PDF 放在文本之前
  • 使用标准字体
  • 确保文本清晰易读
  • 将页面旋转至正确的竖直方向
  • 在提示中使用逻辑页码(来自 PDF 查看器)
  • 必要时将大型 PDF 拆分为多个部分
  • 为重复分析启用提示缓存

扩展您的实现

对于大批量处理,请考虑以下方法:

使用提示缓存

使用提示缓存缓存 PDF,以提高重复查询的性能:

示例代码
curl -sL "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf" |
  base64 | tr -d '\n' |
  jq -Rs '{
    model: "claude-opus-5-5",
    max_tokens: 1024,
    messages: [{
      role: "user",
      content: [
        {
          type: "document",
          source: {type: "base64", media_type: "application/pdf", data: .},
          cache_control: {type: "ephemeral"}
        },
        {type: "text", text: "Which model has the highest human preference win rates across each use-case?"}
      ]
    }]
  }' |
  curl https://api.anthropic.com/v1/messages \
    -H "content-type: application/json" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -d @-
示例代码
ant messages create <<'YAML'
model: claude-opus-5-5
max_tokens: 1024
messages:
  - role: user
    content:
      - type: document
        source:
          type: base64
          media_type: application/pdf
          data: "@./document.pdf"
        cache_control:
          type: ephemeral
      - type: text
        text: Which model has the highest human preference win rates across each use-case?
YAML
示例代码
import base64
import httpx2

# 首先,加载 PDF 并对其进行编码
pdf_url = "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf"
pdf_data = base64.standard_b64encode(
    httpx2.get(pdf_url, follow_redirects=True).content
).decode("utf-8")

# 使用已缓存的文档创建消息
client = anthropic.Anthropic()
message = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "document",
                    "source": {
                        "type": "base64",
                        "media_type": "application/pdf",
                        "data": pdf_data,
                    },
                    "cache_control": {"type": "ephemeral"},
                },
                {
                    "type": "text",
                    "text": "Which model has the highest human preference win rates across each use-case?",
                },
            ],
        }
    ],
)

print(message.content)
示例代码
// 首先,加载 PDF 并对其进行编码
const pdfURL =
  "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf";
const pdfResponse = await fetch(pdfURL);
const arrayBuffer = await pdfResponse.arrayBuffer();
const pdfBase64 = Buffer.from(arrayBuffer).toString("base64");

// 使用已缓存的文档创建消息
const anthropic = new Anthropic();
const response = await anthropic.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 1024,
  messages: [
    {
      role: "user",
      content: [
        {
          type: "document",
          source: {
            type: "base64",
            media_type: "application/pdf",
            data: pdfBase64
          },
          cache_control: { type: "ephemeral" }
        },
        {
          type: "text",
          text: "Which model has the highest human preference win rates across each use-case?"
        }
      ]
    }
  ]
});

console.log(response);
示例代码
var client = new AnthropicClient();

// 下载 PDF 并进行编码
var pdfUrl = "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf";
using var httpClient = new HttpClient();
var pdfBase64 = Convert.ToBase64String(await httpClient.GetByteArrayAsync(pdfUrl));

var message = await client.Messages.Create(new MessageCreateParams
{
    Model = Model.ClaudeOpus5_5,
    MaxTokens = 1024,
    Messages =
    [
        new UserMessageParam
        {
            Content = new List<ContentBlockParam>
            {
                new DocumentBlockParam
                {
                    Source = new Base64PdfSource { Data = pdfBase64 },
                    CacheControl = new CacheControlEphemeral(),
                },
                new TextBlockParam("Which model has the highest human preference win rates across each use-case?"),
            },
        },
    ],
});

Console.WriteLine(message);
示例代码
// 首先,加载 PDF 并对其进行编码
pdfURL := "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf"
resp, err := http.Get(pdfURL)
if err != nil {
	panic(err)
}
defer resp.Body.Close()
pdfBytes, err := io.ReadAll(resp.Body)
if err != nil {
	panic(err)
}
pdfBase64 := base64.StdEncoding.EncodeToString(pdfBytes)

// 创建带有缓存控制的文档块
client := anthropic.NewClient()
message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
	Model:     anthropic.ModelClaudeOpus5_5,
	MaxTokens: 1024,
	Messages: []anthropic.MessageParam{
		anthropic.NewUserMessage(
			anthropic.ContentBlockParamUnion{
				OfDocument: &anthropic.DocumentBlockParam{
					Source: anthropic.DocumentBlockParamSourceUnion{
						OfBase64: &anthropic.Base64PDFSourceParam{
							Data: pdfBase64,
						},
					},
					CacheControl: anthropic.NewCacheControlEphemeralParam(),
				},
			},
			anthropic.NewTextBlock("Which model has the highest human preference win rates across each use-case?"),
		),
	},
})
if err != nil {
	panic(err)
}

fmt.Printf("%+v\n", message.Content)
示例代码
AnthropicClient client = AnthropicOkHttpClient.fromEnv();

// 下载 PDF 并进行编码
String pdfUrl =
    "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf";
HttpClient httpClient = HttpClient.newBuilder()
    .followRedirects(HttpClient.Redirect.NORMAL)
    .build();
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create(pdfUrl))
    .GET()
    .build();

HttpResponse<byte[]> response = httpClient.send(
    request,
    HttpResponse.BodyHandlers.ofByteArray()
);
String pdfBase64 = Base64.getEncoder().encodeToString(response.body());

MessageCreateParams params = MessageCreateParams.builder()
    .model(Model.CLAUDE_OPUS_5_5)
    .maxTokens(1024)
    .addUserMessageOfContentBlockParams(
        List.of(
            ContentBlockParam.ofDocument(
                DocumentBlockParam.builder()
                    .source(Base64PdfSource.builder()
                        .data(pdfBase64)
                        .build())
                    .cacheControl(CacheControlEphemeral.builder().build())
                    .build()
            ),
            ContentBlockParam.ofText(
                TextBlockParam.builder()
                    .text(
                        "Which model has the highest human preference win rates across each use-case?"
                    )
                    .build()
            )
        )
    )
    .build();

Message message = client.messages().create(params);
System.out.println(message);
示例代码
$client = new Client();

// 加载 PDF 并进行编码
$pdf_url = 'https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf';
$pdf_data = base64_encode(file_get_contents($pdf_url));

$message = $client->messages->create(
    maxTokens: 1024,
    messages: [
        [
            'role' => 'user',
            'content' => [
                [
                    'type' => 'document',
                    'source' => [
                        'type' => 'base64',
                        'media_type' => 'application/pdf',
                        'data' => $pdf_data,
                    ],
                    'cache_control' => ['type' => 'ephemeral'],
                ],
                [
                    'type' => 'text',
                    'text' => 'Which model has the highest human preference win rates across each use-case?',
                ],
            ],
        ],
    ],
    model: 'claude-opus-5-5',
);

echo $message;
示例代码
require "open-uri"

# 加载 PDF 并进行编码
pdf_url = "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf"
pdf_bytes = URI.open(pdf_url, "rb") { |f| f.read }
pdf_data = [pdf_bytes].pack("m0") # Encode as base64 without newlines

anthropic = Anthropic::Client.new

message = anthropic.messages.create(
  model: Anthropic::Model::CLAUDE_OPUS_5_5,
  max_tokens: 1024,
  messages: [
    {
      role: "user",
      content: [
        {
          type: "document",
          source: {
            type: "base64",
            media_type: "application/pdf",
            data: pdf_data
          },
          cache_control: {type: "ephemeral"}
        },
        {
          type: "text",
          text: "Which model has the highest human preference win rates across each use-case?"
        }
      ]
    }
  ]
)

puts(message.content)

处理文档批次

使用 Message Batches API 在一个请求中处理多个 PDF:

示例代码
curl -sL "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf" | base64 | tr -d '\n' > pdf_base64.txt
# 使用 pdf_base64.txt 的内容创建 JSON 请求文件
jq -n --rawfile PDF_BASE64 pdf_base64.txt '{
  "requests": [
  {
    "custom_id": "my-first-request",
    "params": {
      "model": "claude-opus-5-5",
      "max_tokens": 1024,
      "messages": [{
        "role": "user",
        "content": [{
          "type": "document",
          "source": {
            "type": "base64",
            "media_type": "application/pdf",
            "data": $PDF_BASE64
          }
        },
        {
          "type": "text",
          "text": "Which model has the highest human preference win rates across each use-case?"
        }]
      }]
    }
  },
  {
    "custom_id": "my-second-request",
    "params": {
      "model": "claude-opus-5-5",
      "max_tokens": 1024,
      "messages": [{
        "role": "user",
        "content": [{
          "type": "document",
          "source": {
            "type": "base64",
            "media_type": "application/pdf",
            "data": $PDF_BASE64
          }
        },
        {
          "type": "text",
          "text": "Extract 5 key insights from this document."
        }]
      }]
    }
  }]
}' > request.json

# 然后使用该 JSON 文件调用 API
curl https://api.anthropic.com/v1/messages/batches \
  -H "content-type: application/json" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2026-10-21" \
  -d @request.json
示例代码
ant messages:batches create <<'YAML'
requests:
  - custom_id: my-first-request
    params:
      model: claude-opus-5-5
      max_tokens: 1024
      messages:
        - role: user
          content:
            - type: document
              source:
                type: base64
                media_type: application/pdf
                data: "@./document.pdf"
            - type: text
              text: >-
                Which model has the highest human preference win rates
                across each use-case?
  - custom_id: my-second-request
    params:
      model: claude-opus-5-5
      max_tokens: 1024
      messages:
        - role: user
          content:
            - type: document
              source:
                type: base64
                media_type: application/pdf
                data: "@./document.pdf"
            - type: text
              text: Extract 5 key insights from this document.
YAML
示例代码
import base64
import httpx2

# 首先,加载 PDF 并对其进行编码
pdf_url = "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf"
pdf_data = base64.standard_b64encode(
    httpx2.get(pdf_url, follow_redirects=True).content
).decode("utf-8")

# 创建一批使用该文档的请求
client = anthropic.Anthropic()
message_batch = client.messages.batches.create(
    requests=[
        {
            "custom_id": "my-first-request",
            "params": {
                "model": "claude-opus-5-5",
                "max_tokens": 1024,
                "messages": [
                    {
                        "role": "user",
                        "content": [
                            {
                                "type": "document",
                                "source": {
                                    "type": "base64",
                                    "media_type": "application/pdf",
                                    "data": pdf_data,
                                },
                            },
                            {
                                "type": "text",
                                "text": "Which model has the highest human preference win rates across each use-case?",
                            },
                        ],
                    }
                ],
            },
        },
        {
            "custom_id": "my-second-request",
            "params": {
                "model": "claude-opus-5-5",
                "max_tokens": 1024,
                "messages": [
                    {
                        "role": "user",
                        "content": [
                            {
                                "type": "document",
                                "source": {
                                    "type": "base64",
                                    "media_type": "application/pdf",
                                    "data": pdf_data,
                                },
                            },
                            {
                                "type": "text",
                                "text": "Extract 5 key insights from this document.",
                            },
                        ],
                    }
                ],
            },
        },
    ]
)

print(message_batch)
示例代码
// 首先,加载 PDF 并进行编码
const pdfURL =
  "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf";
const pdfResponse = await fetch(pdfURL);
const arrayBuffer = await pdfResponse.arrayBuffer();
const pdfBase64 = Buffer.from(arrayBuffer).toString("base64");

// 创建一批使用该文档的请求
const anthropic = new Anthropic();
const response = await anthropic.messages.batches.create({
  requests: [
    {
      custom_id: "my-first-request",
      params: {
        model: "claude-opus-5-5",
        max_tokens: 1024,
        messages: [
          {
            role: "user",
            content: [
              {
                type: "document",
                source: {
                  type: "base64",
                  media_type: "application/pdf",
                  data: pdfBase64
                }
              },
              {
                type: "text",
                text: "Which model has the highest human preference win rates across each use-case?"
              }
            ]
          }
        ]
      }
    },
    {
      custom_id: "my-second-request",
      params: {
        model: "claude-opus-5-5",
        max_tokens: 1024,
        messages: [
          {
            role: "user",
            content: [
              {
                type: "document",
                source: {
                  type: "base64",
                  media_type: "application/pdf",
                  data: pdfBase64
                }
              },
              {
                type: "text",
                text: "Extract 5 key insights from this document."
              }
            ]
          }
        ]
      }
    }
  ]
});

console.log(response);
示例代码
var client = new AnthropicClient();

// 下载 PDF 并进行编码
var pdfUrl = "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf";
using var httpClient = new HttpClient();
var pdfBase64 = Convert.ToBase64String(await httpClient.GetByteArrayAsync(pdfUrl));

var batch = await client.Messages.Batches.Create(new BatchCreateParams
{
    Requests =
    [
        new()
        {
            CustomID = "my-first-request",
            Params = new()
            {
                Model = Model.ClaudeOpus5_5,
                MaxTokens = 1024,
                Messages =
                [
                    new UserMessageParam
                    {
                        Content = new List<ContentBlockParam>
                        {
                            new DocumentBlockParam
                            {
                                Source = new Base64PdfSource { Data = pdfBase64 },
                            },
                            new TextBlockParam("Which model has the highest human preference win rates across each use-case?"),
                        },
                    },
                ],
            },
        },
        new()
        {
            CustomID = "my-second-request",
            Params = new()
            {
                Model = Model.ClaudeOpus5_5,
                MaxTokens = 1024,
                Messages =
                [
                    new UserMessageParam
                    {
                        Content = new List<ContentBlockParam>
                        {
                            new DocumentBlockParam
                            {
                                Source = new Base64PdfSource { Data = pdfBase64 },
                            },
                            new TextBlockParam("Extract 5 key insights from this document."),
                        },
                    },
                ],
            },
        },
    ],
});

Console.WriteLine(batch);
示例代码
// 首先,加载 PDF 并对其进行编码
pdfURL := "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf"
resp, err := http.Get(pdfURL)
if err != nil {
	panic(err)
}
defer resp.Body.Close()
pdfBytes, err := io.ReadAll(resp.Body)
if err != nil {
	panic(err)
}
pdfBase64 := base64.StdEncoding.EncodeToString(pdfBytes)

// 创建一批使用该文档的请求
client := anthropic.NewClient()
batch, err := client.Messages.Batches.New(context.TODO(), anthropic.MessageBatchNewParams{
	Requests: []anthropic.MessageBatchNewParamsRequest{
		{
			CustomID: "my-first-request",
			Params: anthropic.MessageBatchNewParamsRequestParams{
				Model:     anthropic.ModelClaudeOpus5_5,
				MaxTokens: 1024,
				Messages: []anthropic.MessageParam{
					anthropic.NewUserMessage(
						anthropic.NewDocumentBlock(anthropic.Base64PDFSourceParam{
							Data: pdfBase64,
						}),
						anthropic.NewTextBlock("Which model has the highest human preference win rates across each use-case?"),
					),
				},
			},
		},
		{
			CustomID: "my-second-request",
			Params: anthropic.MessageBatchNewParamsRequestParams{
				Model:     anthropic.ModelClaudeOpus5_5,
				MaxTokens: 1024,
				Messages: []anthropic.MessageParam{
					anthropic.NewUserMessage(
						anthropic.NewDocumentBlock(anthropic.Base64PDFSourceParam{
							Data: pdfBase64,
						}),
						anthropic.NewTextBlock("Extract 5 key insights from this document."),
					),
				},
			},
		},
	},
})
if err != nil {
	panic(err)
}

fmt.Printf("%+v\n", batch)
示例代码
AnthropicClient client = AnthropicOkHttpClient.fromEnv();

// 下载并编码 PDF
String pdfUrl =
    "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf";
HttpClient httpClient = HttpClient.newBuilder()
    .followRedirects(HttpClient.Redirect.NORMAL)
    .build();
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create(pdfUrl))
    .GET()
    .build();

HttpResponse<byte[]> response = httpClient.send(
    request,
    HttpResponse.BodyHandlers.ofByteArray()
);
String pdfBase64 = Base64.getEncoder().encodeToString(response.body());

BatchCreateParams params = BatchCreateParams.builder()
    .addRequest(
        BatchCreateParams.Request.builder()
            .customId("my-first-request")
            .params(
                BatchCreateParams.Request.Params.builder()
                    .model(Model.CLAUDE_OPUS_5_5)
                    .maxTokens(1024)
                    .addUserMessageOfContentBlockParams(
                        List.of(
                            ContentBlockParam.ofDocument(
                                DocumentBlockParam.builder()
                                    .source(Base64PdfSource.builder()
                                        .data(pdfBase64)
                                        .build())
                                    .build()
                            ),
                            ContentBlockParam.ofText(
                                TextBlockParam.builder()
                                    .text(
                                        "Which model has the highest human preference win rates across each use-case?"
                                    )
                                    .build()
                            )
                        )
                    )
                    .build()
            )
            .build()
    )
    .addRequest(
        BatchCreateParams.Request.builder()
            .customId("my-second-request")
            .params(
                BatchCreateParams.Request.Params.builder()
                    .model(Model.CLAUDE_OPUS_5_5)
                    .maxTokens(1024)
                    .addUserMessageOfContentBlockParams(
                        List.of(
                            ContentBlockParam.ofDocument(
                                DocumentBlockParam.builder()
                                    .source(Base64PdfSource.builder()
                                        .data(pdfBase64)
                                        .build())
                                    .build()
                            ),
                            ContentBlockParam.ofText(
                                TextBlockParam.builder()
                                    .text("Extract 5 key insights from this document.")
                                    .build()
                            )
                        )
                    )
                    .build()
            )
            .build()
    )
    .build();

MessageBatch batch = client.messages().batches().create(params);
System.out.println(batch);
示例代码
$client = new Client();

// 加载 PDF 并进行编码
$pdf_url = 'https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf';
$pdf_data = base64_encode(file_get_contents($pdf_url));

$batch = $client->messages->batches->create(
    requests: [
        [
            'custom_id' => 'my-first-request',
            'params' => [
                'model' => 'claude-opus-5-5',
                'max_tokens' => 1024,
                'messages' => [
                    [
                        'role' => 'user',
                        'content' => [
                            [
                                'type' => 'document',
                                'source' => [
                                    'type' => 'base64',
                                    'media_type' => 'application/pdf',
                                    'data' => $pdf_data,
                                ],
                            ],
                            [
                                'type' => 'text',
                                'text' => 'Which model has the highest human preference win rates across each use-case?',
                            ],
                        ],
                    ],
                ],
            ],
        ],
        [
            'custom_id' => 'my-second-request',
            'params' => [
                'model' => 'claude-opus-5-5',
                'max_tokens' => 1024,
                'messages' => [
                    [
                        'role' => 'user',
                        'content' => [
                            [
                                'type' => 'document',
                                'source' => [
                                    'type' => 'base64',
                                    'media_type' => 'application/pdf',
                                    'data' => $pdf_data,
                                ],
                            ],
                            [
                                'type' => 'text',
                                'text' => 'Extract 5 key insights from this document.',
                            ],
                        ],
                    ],
                ],
            ],
        ],
    ],
);

echo $batch;
示例代码
require "open-uri"

# 加载 PDF 并进行编码
pdf_url = "https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf"
pdf_bytes = URI.open(pdf_url, "rb") { |f| f.read }
pdf_data = [pdf_bytes].pack("m0") # Encode as base64 without newlines

anthropic = Anthropic::Client.new

message_batch = anthropic.messages.batches.create(
  requests: [
    {
      custom_id: "my-first-request",
      params: {
        model: Anthropic::Model::CLAUDE_OPUS_5_5,
        max_tokens: 1024,
        messages: [
          {
            role: "user",
            content: [
              {
                type: "document",
                source: {
                  type: "base64",
                  media_type: "application/pdf",
                  data: pdf_data
                }
              },
              {
                type: "text",
                text: "Which model has the highest human preference win rates across each use-case?"
              }
            ]
          }
        ]
      }
    },
    {
      custom_id: "my-second-request",
      params: {
        model: Anthropic::Model::CLAUDE_OPUS_5_5,
        max_tokens: 1024,
        messages: [
          {
            role: "user",
            content: [
              {
                type: "document",
                source: {
                  type: "base64",
                  media_type: "application/pdf",
                  data: pdf_data
                }
              },
              {
                type: "text",
                text: "Extract 5 key insights from this document."
              }
            ]
          }
        ]
      }
    }
  ]
)

puts(message_batch)

批次以异步方式处理。要检查进度并在处理结束后获取结果,请参阅批处理。

后续步骤

视觉

Claude 的视觉能力使其能够处理和分析图像,为多模态交互开辟了令人兴奋的可能性。

可用性

PDF 支持在所有模型上可用,并具备零数据保留和HIPAA 就绪资格。

API 支持

Messages API

  • 可用性:始终开启
  1. file_id 源需要托管在 Anthropic 上的部署。
  2. 仅支持 Base64 源。

Managed Agents

  • 可用性:始终开启
状态云平台
可用所有支持的平台

数据处理

数据处理概览

项目零数据保留HIPAA
状态具备资格(不包括 涵盖的模型)具备资格
详细信息—HIPAA 资格适用于通过 Messages API 内联发送的 PDF,不适用于通过 Files API 发送的 PDF。

适用的端点:

  • /v1/messages
文档内容持续同步更新