Pular para o conteúdo principal

Converter PDF para Editável PDF Usando OCR

PDF4me Converter PDF para Editável PDF usando OCR é um REST ponto final que realiza a digitalização PDFs Pesquisável e editável. POST a Base64 PDF para /api/v2/ConvertOcrPdf, escolha Rascunho ou Alta qualidade, e o OCR O mecanismo insere uma camada de texto real no documento. A resposta retorna o documento finalizado. PDF como Base64 JSON, pronto para decodificar e salvar.

O que este endpoint faz

Utiliza uma imagem ou um scanner. PDF e retorna o mesmo documento com o texto reconhecido e selecionável. qualityType alterna entre uma passagem única rápida (Rascunho, 1 API reconhecimento por arquivo e por página (Alto, 2 API chamadas por página), enquanto ocrWhenNeeded pula pages que já são pesquisáveis. O resultado chega como um Base64 docContent campo em um JSON resposta, ou por meio de um Location enquete URL em 202.

Artigos relacionados no blogue
Ainda não há nenhuma publicação no blogue sobre esta funcionalidade — em breve.
Entretanto, explore o blogue da PDF4me para encontrar tutoriais e fluxos de trabalho para todas as plataformas.
Visite o blogue

Autenticando seu API Solicitar

Todo PDF4me REST A chamada deve incluir o seu API chave no Authorization Defina o cabeçalho como autenticação básica. Obtenha ou altere sua chave no painel do desenvolvedor.

Ponto final

POST/api/v2/ConverterOcrPdf

Fatos importantes que você não deve perder

Tipos de campos mistos: strings E booleanos
ocrWhenNeeded e outputFormat são as CORDAS "verdadeiro" / "falso", enquanto isAsync e mergeAllSheets são JSON booleanos. Isso reflete os exemplos de código oficiais; confundi-los é uma causa comum de erros 400.
A resposta é JSON, não bytes brutos
Uma resposta de 200 carrega docName mais docContent, o acabado PDF como um Base64 string. Decodificar docContent Antes de salvar, não grave o corpo da resposta no disco tal como está.
Draft e High são cobrados de forma diferente.
Custos do rascunho 1 API chamada por arquivo; custos elevados 2 API chamadas por página e é o modo criado para varreduras. Mantenha ocrWhenNeeded: "verdadeiro" já pesquisável pages são ignorados em vez de serem reprocessados.

HTTP configurar

Método: POST
URL: https://api.pdf4me.com/api/v2/ConvertOcrPdf
Tipo de conteúdo: aplicativo/json
Authorization: Básico <seu PDF4me API chave>

Enviar isAsync: verdadeiro no corpo. 200 retornos JSON com o Base64 docContent. 202 retorna um Location cabeçalho com uma enquete URL; GET que URL com o mesmo Authorization cabeçalho até que retorne 200 com o JSON resultado.

Como se faz uma digitalização? PDF pesquisável?

Um digitalizado PDF são apenas fotos de pagesNada pode ser selecionado e nada corresponde a uma pesquisa de texto. OCR (reconhecimento óptico de caracteres, veja o visão geral de como OCR funcionaO programa lê cada imagem da página e insere as palavras reconhecidas no arquivo como uma camada de texto real. Após a conversão, o documento se comporta como um documento digital nativo. PDFA pesquisa, a cópia e os leitores de tela funcionam perfeitamente e o sistema está pronto para etapas subsequentes, como: PDF/A arquivamento ou localizar e substituir.

Draft vs HighRascunhoAlto
Ideal paraNormal PDFs que em sua maioria possuem uma camada de textoDocumentos digitalizados ou baseados em imagens
Custo1 API chamada por arquivo2 API chamadas por página
ReconhecimentoPassagem de luzCompleto por página OCR
Combine comocrWhenNeeded: "true" para ignorar a pesquisa pageslanguage quando o texto retorna ilegível

API campos corporais

ParâmetroObrigatórioTipoO que fazExemplo
docContentRequiredstringBase64-encoded bytes of the source PDF. Strip any data:application/pdf;base64, prefix before posting.JVBERi0xLjcK...
docNameRequiredstringSource filename including the .pdf extension. Used for the output docName.scanned-contract.pdf
qualityTypeRequiredstringDraft for normal PDFs (1 API call per file). High for scanned documents (2 API calls per page).High
ocrWhenNeededRequiredstringThe string "true" skips pages that already have a searchable text layer; "false" forces OCR on every page."true"
outputFormatRequiredstringOutput format flag, sent as the string "true" in the official samples."true"
languageConditionalstringLanguage of the source text (English, Spanish, French, German, and others). Set only when the recognized output is garbled; otherwise let the engine detect it.English
mergeAllSheetsOptionalbooleanJSON boolean carried by the official samples; relevant to sheet-based sources.true
isAsyncOptionalbooleantrue enables the 202 + Location polling pattern, recommended for large scans.true

Exemplos de cargas úteis

Modo alto. Documento digitalizado com OCR

{
"docContent": "JVBERi0xLjcKJcfsj6IKNSAwIG9iago8PAovVHlwZSAvQ2F0YWxvZw...",
"docName": "scanned-contract.pdf",
"qualityType": "High",
"ocrWhenNeeded": "true",
"language": "English",
"outputFormat": "true",
"isAsync": true
}

Modo rascunho. Documento misto, ignorar pesquisa. pages

{
"docContent": "JVBERi0xLjcKJcfsj6IKNSAwIG9iago8PAovVHlwZSAvQ2F0YWxvZw...",
"docName": "mixed-report.pdf",
"qualityType": "Draft",
"ocrWhenNeeded": "true",
"outputFormat": "true",
"isAsync": true
}

Dicas de coleta do carteiro

Headers
Content-Type: application/json + Authorization: Basic <apiKey>.
Body
raw JSON. Copy a payload above and replace docContent with your Base64. Keep the quotes around "true" for ocrWhenNeeded and outputFormat.
Response
The 200 body is JSON. Copy the docContent value and Base64-decode it to get the PDF. If 202, GET the Location URL with the same Authorization until 200.
Quality
Use High for scans and expect 2 API calls per page. Draft is enough when most pages already have selectable text.

exemplo de curl

curl -X POST https://api.pdf4me.com/api/v2/ConvertOcrPdf \
-H "Content-Type: application/json" \
-H "Authorization: Basic YOUR_API_KEY" \
-d '{
"docContent": "'"$(base64 -w 0 scanned-contract.pdf)"'",
"docName": "scanned-contract.pdf",
"qualityType": "High",
"ocrWhenNeeded": "true",
"outputFormat": "true",
"isAsync": true
}' | python -c "import sys, json, base64; open('searchable.pdf','wb').write(base64.b64decode(json.load(sys.stdin)['docContent']))"

O que significa o API retornar?

JSON, não bytes brutos do arquivo. Decodifique o docContent campo para obter o acabado PDF.

CampoTipoO que contém
docName (HTTP 200)StringThe output PDF filename, derived from the docName you sent.
docContent (HTTP 200)String (Base64)The searchable, editable PDF encoded as Base64. Decode to bytes and save with a .pdf extension.
Location header (HTTP 202)String (URL)Poll URL for an async job that is still running. GET it with the same Authorization header; the official samples poll every 10 seconds, up to 20 retries.
Poll response (HTTP 200)JSONThe same docName + docContent JSON, returned once processing completes.

Exemplos de código

Implementações funcionais de ponta a ponta, cada uma com um exemplo digitalizado. PDF e a carga útil exata desta página:

Perguntas frequentes

How do you make a scanned PDF searchable?+
Run it through OCR. POST the Base64 PDF to /api/v2/ConvertOcrPdf with qualityType High and ocrWhenNeeded "true"; the engine recognizes the text on each scanned page and writes a searchable, selectable text layer into the returned PDF.
Is the response the PDF file itself?+
No. ConvertOcrPdf returns JSON: a docName field and a docContent field holding the output PDF as a Base64 string. Decode docContent to bytes before saving the file.
What does ocrWhenNeeded do?+
Set to the string "true", it skips recognition on pages that already have a searchable text layer, saving processing on mixed documents. Set to "false", every page is OCR-processed regardless.
Which quality mode should I use, Draft or High?+
Draft costs 1 API call per file and suits normal PDFs. High costs 2 API calls per page and is built for scanned documents where every page needs recognition. Use High whenever the source is a scan or photo.
Why are some fields strings and others booleans?+
That is the contract the official code samples ship: ocrWhenNeeded and outputFormat are the strings "true" or "false", while isAsync and mergeAllSheets are JSON booleans. Sending the wrong type is a common cause of 400 errors.
The recognized text is garbled. What now?+
Set the language field to match the document (English, Spanish, French, German, and others) and rerun. Language only needs to be set when automatic detection gets it wrong.
Does OCR change how the pages look?+
No. The text layer is added behind the page image, so the visual appearance stays identical while search, selection, and copy start working.
Can I OCR a PDF and then extract its tables to Excel?+
Yes, but you do not need two calls: the Convert PDF to Excel endpoint runs OCR itself when you set its qualityType to High. Use ConvertOcrPdf when the deliverable should stay a PDF.

Ações relacionadas

A mesma tarefa em outras plataformas.

Obtenha ajuda