OCR PDF
Text recognition (OCR)
Optical character recognition (OCR) converts images to text so that you
and your users can fully interact with the PDF file. After performing
OCR, the PDF may be fully editable and searchable. The input format must
be application/pdf
.
This sample defaults to the en-us locale. For other languages, see OCR with specific language.
Java
.NET
Node JS
REST API
Copied to your clipboard1// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples2// Run the sample:3// mvn -f pom.xml exec:java -Dexec.mainClass=com.adobe.pdfservices.operation.samples.ocrpdf.OcrPDF45 public class OcrPDF {67 // Initialize the logger.8 private static final Logger LOGGER = LoggerFactory.getLogger(OcrPDF.class);910 public static void main(String[] args) {1112 try {1314 // Initial setup, create credentials instance.15 Credentials credentials = Credentials.serviceAccountCredentialsBuilder()16 .fromFile("pdfservices-api-credentials.json")17 .build();1819 //Create an ExecutionContext using credentials and create a new operation instance.20 ExecutionContext executionContext = ExecutionContext.create(credentials);21 OCROperation ocrOperation = OCROperation.createNew();2223 // Set operation input from a source file.24 FileRef source = FileRef.createFromLocalFile("src/main/resources/ocrInput.pdf");25 ocrOperation.setInput(source);2627 // Execute the operation28 FileRef result = ocrOperation.execute(executionContext);2930 // Save the result at the specified location31 result.saveAs("output/ocrOutput.pdf");3233 } catch (ServiceApiException | IOException | SdkException | ServiceUsageException ex) {34 LOGGER.error("Exception encountered while executing operation", ex);35 }36 }37 }
Copied to your clipboard1// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples2// Run the sample:3// cd OcrPDF/4// dotnet run OcrPDF.csproj56 namespace OcrPDF7 {8 class Program9 {10 private static readonly ILog log = LogManager.GetLogger(typeof(Program));11 static void Main()12 {13 //Configure the logging14 ConfigureLogging();15 try16 {17 // Initial setup, create credentials instance.18 Credentials credentials = Credentials.ServiceAccountCredentialsBuilder()19 .FromFile(Directory.GetCurrentDirectory() + "/pdfservices-api-credentials.json")20 .Build();2122 //Create an ExecutionContext using credentials and create a new operation instance.23 ExecutionContext executionContext = ExecutionContext.Create(credentials);24 OCROperation ocrOperation = OCROperation.CreateNew();2526 // Set operation input from a source file.27 FileRef sourceFileRef = FileRef.CreateFromLocalFile(@"ocrInput.pdf");28 ocrOperation.SetInput(sourceFileRef);2930 // Execute the operation.31 FileRef result = ocrOperation.Execute(executionContext);3233 // Save the result to the specified location.34 result.SaveAs(Directory.GetCurrentDirectory() + "/output/ocrOperationOutput.pdf");35 }36 catch (ServiceUsageException ex)37 {38 log.Error("Exception encountered while executing operation", ex);39 }40 // Catch more errors here. . .41 }4243 static void ConfigureLogging()44 {45 ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());46 XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));47 }48 }49 }
Copied to your clipboard1// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample2// Run the sample:3// node src/ocr/ocr-pdf.js45 const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');67 try {8 // Initial setup, create credentials instance.9 const credentials = PDFServicesSdk.Credentials10 .serviceAccountCredentialsBuilder()11 .fromFile("pdfservices-api-credentials.json")12 .build();1314 // Create an ExecutionContext using credentials and create a new operation instance.15 const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),16 ocrOperation = PDFServicesSdk.OCR.Operation.createNew();1718 // Set operation input from a source file.19 const input = PDFServicesSdk.FileRef.createFromLocalFile('resources/ocrInput.pdf');20 ocrOperation.setInput(input);2122 // Execute the operation and Save the result to the specified location.23 ocrOperation.execute(executionContext)24 .then(result => result.saveAsFile('output/ocrOutput.pdf'))25 .catch(err => {26 if(err instanceof PDFServicesSdk.Error.ServiceApiError27 || err instanceof PDFServicesSdk.Error.ServiceUsageError) {28 console.log('Exception encountered while executing operation', err);29 } else {30 console.log('Exception encountered while executing operation', err);31 }32 });33 } catch (err) {34 console.log('Exception encountered while executing operation', err);35 }
Copied to your clipboard1// Please refer our REST API docs for more information2// https://documentcloud.adobe.com/document-services/index.html#post-ocr34curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \5--header 'Authorization: Bearer {{Placeholder for token}}' \6--header 'Accept: application/json, text/plain, */*' \7--header 'x-api-key: {{Placeholder for client_id}}' \8--header 'Prefer: respond-async,wait=0' \9--form 'contentAnalyzerRequests="{10 \"cpf:inputs\": {11 \"documentIn\": {12 \"cpf:location\": \"InputFile0\",13 \"dc:format\": \"application/pdf\"14 }15 },16 \"cpf:engine\": {17 \"repo:assetId\": \"urn:aaid:cpf:Service-7e6a5d2b6bb141d7832398076914a07b\"18 },19 \"cpf:outputs\": {20 \"documentOut\": {21 \"cpf:location\": \"multipartLabelOut\",22 \"dc:format\": \"application/pdf\"23 }24 }25}"' \26--form 'InputFile0=@"{{Placeholder for input file (absolute path)}}"'
OCR with specific language
You can perform OCR on files in other languages, including German,
French, Danish, and other languages. Refer to OCRSupportedLocale
and
OCRSupportedType
in the API docs for a list of supported OCR locales
and OCR types.
As shown in the OcrPDFWithOptions sample, when you make a PDF file searchable, you specify both the locale (language) and the type. There are two types which produce a different result:
- One type ensures that text is searchable and selectable, but modifies the original image during the cleanup process (for example, deskews it) before placing an invisible text layer over it. This type removes unwanted artifacts and may result in a more readable document in some scenarios.
- The second (EXACT) type, also overlays a searchable text layer over the original image, but in this case, the original image is unchanged. This type produces maximum fidelity to the original image.
Java
.NET
Node JS
REST API
Copied to your clipboard1// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples2// Run the sample:3// mvn -f pom.xml exec:java Dexec.mainClass=com.adobe.pdfservices.operation.samples.ocrpdf.OcrPDFWithOptions45 public class OcrPDFWithOptions {67 // Initialize the logger.8 private static final Logger LOGGER = LoggerFactory.getLogger(OcrPDFWithOptions.class);910 public static void main(String[] args) {1112 try {1314 // Initial setup, create credentials instance.15 Credentials credentials = Credentials.serviceAccountCredentialsBuilder()16 .fromFile("pdfservices-api-credentials.json")17 .build();1819 //Create an ExecutionContext using credentials and create a new operation instance.20 ExecutionContext executionContext = ExecutionContext.create(credentials);21 OCROperation ocrOperation = OCROperation.createNew();2223 // Set operation input from a source file.24 FileRef source = FileRef.createFromLocalFile("src/main/resources/ocrInput.pdf");25 ocrOperation.setInput(source);2627 // Build OCR options from supported locales and OCR-types and set them into the operation28 OCROptions ocrOptions = OCROptions.ocrOptionsBuilder()29 .withOCRLocale(OCRSupportedLocale.EN_US)30 .withOCRType(OCRSupportedType.SEARCHABLE_IMAGE_EXACT)31 .build();32 ocrOperation.setOptions(ocrOptions);3334 // Execute the operation35 FileRef result = ocrOperation.execute(executionContext);3637 // Save the result at the specified location38 result.saveAs("output/ocrWithOptionsOutput.pdf");3940 } catch (ServiceApiException | IOException | SdkException | ServiceUsageException ex) {41 LOGGER.error("Exception encountered while executing operation", ex);42 }43 }44 }
Copied to your clipboard1// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples2// Run the sample:3// cd OcrPDFWithOptions4// dotnet run OcrPDFWithOptions.csproj56 namespace OcrPDFWithOptions7 {8 class Program9 {10 private static readonly ILog log = LogManager.GetLogger(typeof(Program));11 static void Main()12 {13 //Configure the logging14 ConfigureLogging();15 try16 {17 // Initial setup, create credentials instance.18 Credentials credentials = Credentials.ServiceAccountCredentialsBuilder()19 .FromFile(Directory.GetCurrentDirectory() + "/pdfservices-api-credentials.json")20 .Build();2122 //Create an ExecutionContext using credentials and create a new operation instance.23 ExecutionContext executionContext = ExecutionContext.Create(credentials);24 OCROperation ocrOperation = OCROperation.CreateNew();2526 // Set operation input from a source file.27 FileRef sourceFileRef = FileRef.CreateFromLocalFile(@"ocrWithOptionsInput.pdf");28 ocrOperation.SetInput(sourceFileRef);29 // Build OCR options from supported locales and OCR-types and set them into the operation30 OCROptions ocrOptions = OCROptions.OCROptionsBuilder()31 .WithOcrLocale(OCRSupportedLocale.EN_US)32 .WithOcrType(OCRSupportedType.SEARCHABLE_IMAGE_EXACT)33 .Build();34 ocrOperation.SetOptions(ocrOptions);3536 // Execute the operation.37 FileRef result = ocrOperation.Execute(executionContext);3839 // Save the result to the specified location.40 result.SaveAs(Directory.GetCurrentDirectory() + "/output/ocrOperationWithOptionsOutput.pdf");41 }42 catch (ServiceUsageException ex)43 {44 log.Error("Exception encountered while executing operation", ex);45 }46 // Catch more errors here . . .47 }4849 static void ConfigureLogging()50 {51 ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());52 XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));53 }54 }55 }
Copied to your clipboard1// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample2// Run the sample:3// node src/ocr/ocr-pdf-with-options.js45 const PDFServicesSdk = require('@adobe/pdfservices-node-sdk');67 try {8 // Initial setup, create credentials instance.9 const credentials = PDFServicesSdk.Credentials10 .serviceAccountCredentialsBuilder()11 .fromFile("pdfservices-api-credentials.json")12 .build();1314 //Create an ExecutionContext using credentials and create a new operation instance.15 const executionContext = PDFServicesSdk.ExecutionContext.create(credentials),16 ocrOperation = PDFServicesSdk.OCR.Operation.createNew();1718 // Set operation input from a source file.19 const input = PDFServicesSdk.FileRef.createFromLocalFile('resources/ocrInput.pdf');20 ocrOperation.setInput(input);2122 // Provide any custom configuration options for the operation.23 const options = new PDFServicesSdk.OCR.options.OCROptions.Builder()24 .withOcrType(PDFServicesSdk.OCR.options.OCRSupportedType.SEARCHABLE_IMAGE_EXACT)25 .withOcrLang(PDFServicesSdk.OCR.options.OCRSupportedLocale.EN_US)26 .build();27 ocrOperation.setOptions(options);2829 // Execute the operation and Save the result to the specified location.30 ocrOperation.execute(executionContext)31 .then(result => result.saveAsFile('output/ocrWithOptionsOutput.pdf'))32 .catch(err => {33 if(err instanceof PDFServicesSdk.Error.ServiceApiError34 || err instanceof PDFServicesSdk.Error.ServiceUsageError) {35 console.log('Exception encountered while executing operation', err);36 } else {37 console.log('Exception encountered while executing operation', err);38 }39 });40 } catch (err) {41 console.log('Exception encountered while executing operation', err);42 }
Copied to your clipboard1// Please refer our REST API docs for more information2// https://documentcloud.adobe.com/document-services/index.html#post-ocr34curl --location --request POST 'https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D' \5--header 'Authorization: Bearer {{Placeholder for token}}' \6--header 'Accept: application/json, text/plain, */*' \7--header 'x-api-key: {{Placeholder for client_id}}' \8--header 'Prefer: respond-async,wait=0' \9--form 'contentAnalyzerRequests="{10 \"cpf:inputs\": {11 \"params\": {12 \"cpf:inline\": {13 \"ocrLang\": \"en-US\",14 \"ocrType\": \"searchable_image\"15 }16 },17 \"documentIn\": {18 \"cpf:location\": \"InputFile0\",19 \"dc:format\": \"application/pdf\"20 }21 },22 \"cpf:engine\": {23 \"repo:assetId\": \"urn:aaid:cpf:Service-7e6a5d2b6bb141d7832398076914a07b\"24 },25 \"cpf:outputs\": {26 \"documentOut\": {27 \"cpf:location\": \"multipartLabelOut\",28 \"dc:format\": \"application/pdf\"29 }30 }31}"' \32--form 'InputFile0=@"{{Placeholder for input file (absolute path)}}"'