Saltar al contenido principal

Convertir PDF a editable PDF Usando OCR

PDF4me Convertir PDF a editable PDF usando OCR es un REST punto final que realiza el escaneo PDFs Se puede buscar y editar. POST a Base64 PDF a /api/v2/ConvertOcrPdf, elija Borrador o Alta calidad, y el OCR El motor escribe una capa de texto real en el documento. La respuesta devuelve el documento terminado. PDF como Base64 JSON, listo para decodificar y guardar.

Lo que hace este punto final

Toma una imagen o un escaneo PDF y devuelve el mismo documento con el texto reconocido y seleccionable. qualityType cambia entre un paso único rápido (Borrador, 1 API llamada por archivo) y reconocimiento por página (Alto, 2 API llamadas por página), mientras que ocrWhenNeeded saltos pages que ya se pueden buscar. El resultado llega como un Base64 docContent campo en un JSON respuesta, o a través de una Location encuesta URL en 202.

Entradas de blog relacionadas
Aún no hay ninguna entrada de blog sobre esta función; estará disponible próximamente.
Mientras tanto, echa un vistazo al blog de PDF4me para encontrar tutoriales y flujos de trabajo para todas las plataformas.
Visita el blog

Autenticando su API Pedido

Cada PDF4me REST La llamada debe incluir su API clave en el Authorization Encabezado como autenticación básica. Obtenga o cambie su clave desde el panel de desarrollador.

Punto final

POST/api/v2/ConvertirOcrPdf

Datos importantes que no debes perderte

Tipos de campos mixtos: cadenas de texto Y booleanos
ocrWhenNeeded y outputFormat son las CUERDAS "verdadero" / "FALSO", mientras isAsync y mergeAllSheets son JSON booleanos. Esto refleja los ejemplos de código oficiales; mezclarlos es una causa común de errores 400.
La respuesta es JSONno bytes sin procesar
Una respuesta de 200 lleva docName más docContent, el terminado PDF como un Base64 cadena. Decodificar docContent Antes de guardar, no escriba el cuerpo de la respuesta en el disco tal cual.
Draft y High se facturan de forma diferente.
Costes de borrador 1 API Llamada por archivo; Costos elevados 2 API llamadas por página y es el modo diseñado para escaneos. Mantener ocrWhenNeeded: "verdadero" por lo que ya se puede buscar pages se omiten en lugar de reprocesarse.

HTTP configuración

Método: POST
URL: https://api.pdf4me.com/api/v2/ConvertOcrPdf
Tipo de contenido: aplicación/json
Authorization: Básico <tu PDF4me API clave>

Enviar isAsync: verdadero en el cuerpo. 200 devoluciones JSON con el Base64 docContent. 202 devuelve un Location encabezado con una encuesta URL; GET eso URL con el mismo Authorization encabezado hasta que devuelva 200 con el JSON resultado.

¿Cómo se hace un escaneo? PDF ¿Se puede buscar?

Un escaneo PDF son solo imágenes de pagesNo hay nada seleccionable y nada coincide con una búsqueda de texto. OCR (reconocimiento óptico de caracteres, véase el Descripción general de cómo OCR obrasEl programa lee la imagen de cada página y escribe las palabras reconocidas en el archivo como una capa de texto real. Tras la conversión, el documento se comporta como un documento digital nativo. PDF: la búsqueda, la copia y los lectores de pantalla funcionan correctamente, y está listo para pasos posteriores como PDF/A archivado o buscar y reemplazar.

Draft vs HighBorradorAlto
Lo mejor paraNormal PDFs que en su mayoría tienen una capa de textoDocumentos escaneados o basados en imágenes
Costo1 API llamada por archivo2 API llamadas por página
ReconocimientoPaso de luzPágina completa OCR
Emparejar conocrWhenNeeded: "true" para omitir la búsqueda pageslanguage cuando el texto aparece distorsionado

API campos corporales

ParámetroRequeridoTipoLo que haceEjemplo
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

Cargas útiles de ejemplo

Modo alto. Documento escaneado con OCR

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

Modo borrador. Documento mixto, omitir búsqueda. pages

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

Consejos para el cobro de carteros

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.

Ejemplo 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']))"

¿Qué significa el API ¿devolver?

JSON, no bytes de archivo sin procesar. Decodifique el docContent campo para obtener el terminado PDF.

CampoTipoLo que contiene
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.

Ejemplos de código

Implementaciones de extremo a extremo en funcionamiento, cada una con una muestra escaneada. PDF y la carga útil exacta de esta página:

Preguntas frecuentes

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.

Acciones relacionadas

La misma tarea en otras plataformas.

Obtén ayuda