1. 程式人生 > >pdf轉成圖片

pdf轉成圖片

public List<EcdInvoiceOcrDto> pdfFileToPic(String picName,File invoiceFile
   ,String invoiceTypeCode) throws Exception{
  List<EcdInvoiceOcrDto> picPathList = new ArrayList<EcdInvoiceOcrDto>();
  PDDocument doc = PDDocument.load(invoiceFile);
  PDFRenderer reader = new PDFRenderer(doc);
  int pageNo = doc.getNumberOfPages();
  for (int i = 0; i < pageNo; i++) {
   //1.將pdf轉為圖片
   BufferedImage bfi = reader.renderImageWithDPI(i, 96);
   //2.獲取圖片儲存路勁
   File file2 = ocrRecognitionService.getPicPath(picName);
   ImageIO.write(bfi, picName.split("\\.")[1
], file2);
   /*
    * 3.新建發票實體類並設定發票的存放路勁
    * 若發票為專票或是普票則將發票圖片變成二進位制陣列 傳回 待發票識別時使用
    */
   EcdInvoiceOcrDto ecdInvoiceOcrDto = new EcdInvoiceOcrDto();
   ByteArrayOutputStream bos = null;
   FileInputStream fis=null;
   try {
    if(invoiceTypeCode.equals(IConstants.INVOICE_TYPE_SPECIAL)
      ||invoiceTypeCode.equals(IConstants.INVOICE_TYPE_PLAIN)){
     bos = new ByteArrayOutputStream();
     fis = new FileInputStream(file2);
     byte[] data=new byte[2048];
     int len=0;
     while((len=fis.read(data))!=-1){
      bos.write(data, 0, len);
     }
     bos.flush();
     ecdInvoiceOcrDto.setImageStreamStr(new BASE64Encoder().encode(bos.toByteArray()));
    }
   } catch (Exception e) {
    logger.error("讀取圖片成二進位制陣列失敗",e);
    throw new Exception();
   }finally{
    if(bos!=null){
     bos.close();
    }
    if(fis!=null){
     fis.close();
    }
   }
   
   ecdInvoiceOcrDto.setPicPath(file2.getAbsolutePath());
   ecdInvoiceOcrDto.setImageName(file2.getName());
   picPathList.add(ecdInvoiceOcrDto);
  }
  return picPathList;
 }