{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import fitz\n",
    "from io import BytesIO"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n"
     ]
    }
   ],
   "source": [
    "pdf_path = \"/mnt/ssd1T/hoanglv/Projects/KIE/DATA/SDSAP_Invoice/raw/batch_1/PDF/eReceipt/(Sol tech Grp)_202303_Receipt_Transfort #1.pdf\"\n",
    "with open(pdf_path, 'rb') as f:\n",
    "    pdf_bytes = f.read()\n",
    "doc = fitz.open(stream=pdf_bytes, filetype='pdf')\n",
    "print(doc.page_count)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "isinstance(pdf_bytes, bytes)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np \n",
    "import os \n",
    "\n",
    "def pdf_to_image(pdf, dpi=300, is_get_first_page=False, max_page=1000):\n",
    "    \"\"\"_summary_\n",
    "\n",
    "    Args:\n",
    "        pdf (_type_): _description_\n",
    "        dpi (int, optional): _description_. Defaults to 300.\n",
    "        is_get_first_page (bool, optional): _description_. Defaults to False.\n",
    "        max_page (int, optional): _description_. Defaults to 1000.\n",
    "\n",
    "    Raises:\n",
    "        NotImplementedError: _description_\n",
    "\n",
    "    Returns:\n",
    "        _type_: _description_\n",
    "    \"\"\"\n",
    "    if isinstance(pdf, str):\n",
    "        if not os.path.exists(pdf):\n",
    "            print(f\"Not found pdf path at {pdf}\")\n",
    "            return []\n",
    "        doc = fitz.open(pdf)  # open document\n",
    "    elif isinstance(pdf, bytes):\n",
    "        doc = fitz.open(stream=pdf, filetype='pdf')\n",
    "    else:\n",
    "        raise NotImplementedError(f\"Not yet implement for {type(pdf)} type !!!\")\n",
    "    \n",
    "    zoom = dpi // 72\n",
    "    magnify = fitz.Matrix(zoom, zoom) \n",
    "    imgs = []\n",
    "    for idx, page in enumerate(doc):\n",
    "        pix = page.get_pixmap(matrix=magnify)  # render page to an image\n",
    "        \n",
    "        im = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.h, pix.w, pix.n)\n",
    "        im = np.ascontiguousarray(im[..., [2, 1, 0]])  # rgb to bgr\n",
    "        imgs.append(im)\n",
    "        if is_get_first_page or idx >= max_page:\n",
    "            break\n",
    "    return imgs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "ename": "FileNotFoundError",
     "evalue": "no such file: '/mnt/ssd1T/hoanglv/Projects/KIE/DATA/SDSAP_Invoice/raw/batch_1/PDF/eReceipt/(Sol tech Grp)_202303_Rec eipt_Transfort #1.pdf'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mFileNotFoundError\u001b[0m                         Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[18], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m imgs \u001b[39m=\u001b[39m pdf_to_image(pdf\u001b[39m=\u001b[39;49m\u001b[39m\"\u001b[39;49m\u001b[39m/mnt/ssd1T/hoanglv/Projects/KIE/DATA/SDSAP_Invoice/raw/batch_1/PDF/eReceipt/(Sol tech Grp)_202303_Rec eipt_Transfort #1.pdf\u001b[39;49m\u001b[39m\"\u001b[39;49m)\n\u001b[1;32m      2\u001b[0m \u001b[39mprint\u001b[39m(\u001b[39mlen\u001b[39m(imgs))\n",
      "Cell \u001b[0;32mIn[13], line 5\u001b[0m, in \u001b[0;36mpdf_to_image\u001b[0;34m(pdf, dpi, is_get_first_page)\u001b[0m\n\u001b[1;32m      3\u001b[0m \u001b[39mdef\u001b[39;00m \u001b[39mpdf_to_image\u001b[39m(pdf, dpi\u001b[39m=\u001b[39m\u001b[39m300\u001b[39m, is_get_first_page\u001b[39m=\u001b[39m\u001b[39mFalse\u001b[39;00m):\n\u001b[1;32m      4\u001b[0m     \u001b[39mif\u001b[39;00m \u001b[39misinstance\u001b[39m(pdf, \u001b[39mstr\u001b[39m):\n\u001b[0;32m----> 5\u001b[0m         doc \u001b[39m=\u001b[39m fitz\u001b[39m.\u001b[39;49mopen(pdf)  \u001b[39m# open document\u001b[39;00m\n\u001b[1;32m      6\u001b[0m     \u001b[39melif\u001b[39;00m \u001b[39misinstance\u001b[39m(pdf, \u001b[39mbytes\u001b[39m):\n\u001b[1;32m      7\u001b[0m         doc \u001b[39m=\u001b[39m fitz\u001b[39m.\u001b[39mopen(stream\u001b[39m=\u001b[39mpdf, filetype\u001b[39m=\u001b[39m\u001b[39m'\u001b[39m\u001b[39mpdf\u001b[39m\u001b[39m'\u001b[39m)\n",
      "File \u001b[0;32m~/miniconda3/envs/py38_hoanglv/lib/python3.8/site-packages/fitz/fitz.py:3867\u001b[0m, in \u001b[0;36mDocument.__init__\u001b[0;34m(self, filename, stream, filetype, rect, width, height, fontsize)\u001b[0m\n\u001b[1;32m   3865\u001b[0m \u001b[39mif\u001b[39;00m \u001b[39mnot\u001b[39;00m os\u001b[39m.\u001b[39mpath\u001b[39m.\u001b[39mexists(filename):\n\u001b[1;32m   3866\u001b[0m     msg \u001b[39m=\u001b[39m \u001b[39mf\u001b[39m\u001b[39m\"\u001b[39m\u001b[39mno such file: \u001b[39m\u001b[39m'\u001b[39m\u001b[39m{\u001b[39;00mfilename\u001b[39m}\u001b[39;00m\u001b[39m'\u001b[39m\u001b[39m\"\u001b[39m\n\u001b[0;32m-> 3867\u001b[0m     \u001b[39mraise\u001b[39;00m \u001b[39mFileNotFoundError\u001b[39;00m(msg)\n\u001b[1;32m   3868\u001b[0m \u001b[39melif\u001b[39;00m \u001b[39mnot\u001b[39;00m os\u001b[39m.\u001b[39mpath\u001b[39m.\u001b[39misfile(filename):\n\u001b[1;32m   3869\u001b[0m     msg \u001b[39m=\u001b[39m \u001b[39mf\u001b[39m\u001b[39m\"\u001b[39m\u001b[39m'\u001b[39m\u001b[39m{\u001b[39;00mfilename\u001b[39m}\u001b[39;00m\u001b[39m'\u001b[39m\u001b[39m is no file\u001b[39m\u001b[39m\"\u001b[39m\n",
      "\u001b[0;31mFileNotFoundError\u001b[0m: no such file: '/mnt/ssd1T/hoanglv/Projects/KIE/DATA/SDSAP_Invoice/raw/batch_1/PDF/eReceipt/(Sol tech Grp)_202303_Rec eipt_Transfort #1.pdf'"
     ]
    }
   ],
   "source": [
    "imgs = pdf_to_image(pdf=\"/mnt/ssd1T/hoanglv/Projects/KIE/DATA/SDSAP_Invoice/raw/batch_1/PDF/eReceipt/(Sol tech Grp)_202303_Rec eipt_Transfort #1.pdf\")\n",
    "print(len(imgs))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 43756 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import  matplotlib.pyplot as plt \n",
    "plt.imshow(imgs[0])\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# import module\n",
    "from pdf2image import convert_from_path\n",
    " \n",
    " \n",
    "# Store Pdf with convert_from_path function\n",
    "images = convert_from_path('/mnt/hdd2T/AICR/Projects/2023/Invoices_SL_HCM/EAS03581488.pdf', dpi=300)\n",
    " \n",
    "for i in range(len(images)):\n",
    "   \n",
    "      # Save pages as images in the pdf\n",
    "    images[i].save('page'+ str(i) +'.jpg', 'JPEG')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "py38_hoanglv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.16"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
