开通文字识别SDK
创建秘钥
引入sdk依赖
我的项目管理工具是Gradle Maven项目到Maven仓库复制就好
implementation group: 'com.tencentcloudapi', name: 'tencentcloud-sdk-java', version: '3.1.296'
核心代码
public class VatInvoiceOCRUtils {
private String secretId = "";
private String secretKey = "";
private String invoiceOcrUrl = "ocr.tencentcloudapi.com";
public Map<String, String> vatInvoiceNo(String imgUrl) throws TencentCloudSDKException {
// 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
// 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
Credential cred = new Credential(secretId, secretKey);
// 实例化一个http选项,可选的,没有特殊需求可以跳过
HttpProfile httpProfile = new HttpProfile();
httpProfile.setEndpoint(invoiceOcrUrl);
// 实例化一个client选项,可选的,没有特殊需求可以跳过
ClientProfile clientProfile = new ClientProfile();
clientProfile.setHttpProfile(httpProfile);
VatInvoiceOCRRequest req = new VatInvoiceOCRRequest();
req.setIsPdf(true);
// 实例化要请求产品的client对象,clientProfile是可选的
OcrClient client = new OcrClient(cred, "ap-shanghai", clientProfile);
req.setImageUrl(imgUrl);
// 返回的resp是一个VatInvoiceOCRResponse的实例,与请求对象对应
VatInvoiceOCRResponse resp = client.VatInvoiceOCR(req);
TextVatInvoice[] invoiceInfos = resp.getVatInvoiceInfos();
List<String> textNameArray = new ArrayList<>();
Collections.addAll(textNameArray,"购买方名称", "购买方识别号","发票号码","发票代码","开票日期","金额");
Map<String,String> resultMap = new HashMap<>();
Arrays.stream(invoiceInfos).forEach(item->{
if (textNameArray.contains(item.getName()) && StrUtil.isNotEmpty(item.getValue())){
resultMap.put(item.getName(),item.getValue());
}
});
return resultMap;
}
}