<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Khadija Mahanga - Medium]]></title>
        <description><![CDATA[Data Science Enthusiast from Dar-es-salaam - Medium]]></description>
        <link>https://medium.com/khadija-mahanga?source=rss----6cbedbb45e2b---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Khadija Mahanga - Medium</title>
            <link>https://medium.com/khadija-mahanga?source=rss----6cbedbb45e2b---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 08:04:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/khadija-mahanga" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Unstructured PDF Text Extraction]]></title>
            <link>https://medium.com/khadija-mahanga/unstructured-pdf-extraction-series-a8ba04da767f?source=rss----6cbedbb45e2b---4</link>
            <guid isPermaLink="false">https://medium.com/p/a8ba04da767f</guid>
            <category><![CDATA[unstructured-data]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pdf-extraction]]></category>
            <category><![CDATA[text-extraction]]></category>
            <dc:creator><![CDATA[Khadija Mahanga]]></dc:creator>
            <pubDate>Sat, 26 Apr 2025 16:02:05 GMT</pubDate>
            <atom:updated>2025-09-03T06:01:39.803Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever encountered a daunting task of extracting content from unstructured PDF files, only to find that existing Python packages fall short of meeting your requirements? By unstructured, I mean PDFs with multiple elements and varying page layouts. Picture a file containing a table on one page, two tables on another, or perhaps none at all. Imagine encountering single-column layouts on one page, and two or three-column layouts on another, with tables nestled within those columns. This was precisely the challenge I faced.</p><p>I experimented with various packages like <a href="https://pypi.org/project/tabula-py/">tabula</a>, among others. However, each had its strengths and weaknesses. While tabula excelled at extracting tables, it struggled with extracting merged cells information from tables and is not for text extraction. I discovered that <a href="https://github.com/pdfminer/pdfminer.six">pdfminer</a> was excellent for extracting text from pages with multiple columns, while <a href="https://github.com/jsvine/pdfplumber">pdfplumber</a> shone when it came to extracting tables with merged cells. I even found a package called <a href="https://github.com/Unstructured-IO/unstructured">unstructured</a>, which was a step in the right direction, meeting about 80% of my needs. Although it performed well in extracting some tables, it often missed others entirely. This issue was common among extraction packages utilizing Optical Character Recognition (OCR), where not all tables could be accurately extracted from PDF files, sometimes even omitting the last row or column of a table.</p><p>So, I devised a solution that successfully handled the majority of my sample PDFs. However, I’ll address the few exceptions later.</p><p>My approach involved combining pdfminer, pdfplumber, and fitz from pymupdf to extract text, table information, and images while preserving their layout and flow.</p><h3>Extracting text and tables</h3><p>To extract both text and tables in an organised manner, I used pdfplumber package function to identify and extract tables from a page. Subsequently, I utilized a pdfminer function to extract text elements sequentially from the page, excluding those within the boundaries of identified tables. When printing the output string, I ensured to preserve the reading flow and the position of tables.</p><p>Let us dive straight into the function without dwelling on packages installation:</p><p>In the initial phase of my function, I instantiated objects from each package to process a single PDF file comprehensively. Thereafter, I iterated through each page, prioritizing the identification of table objects that exist in a page using the pdfplumber’s find_tables function as seen in the code below.</p><pre>def pdf_process(path):<br>    plumberObj = pdfplumber.open(path)<br>    minerPages = extract_pages(path)<br>    fitzDoc = fitz.open(path)<br>    ...<br>    for i in enumerate(minerPages):<br>        tables = plumberPage.find_tables(table_settings={&quot;text_vertical_ttb&quot;: False})<br>        page_text = miner_extract_page(page_layout, tables)</pre><p>Once I had the table objects, I moved to pdfminer. While pdfminer isn&#39;t flawless in table extraction, it excels in handling different page layouts in a PDF. And note my sample PDF files had inconsistent layouts throughout its pages. Therefore, for each page layout, I ensured to crop out all table objects from that page using the helper check function is_obj_in_bbox</p><blockquote>Note, that table object includes a property for it’s boundary box called _<a href="https://github.com/jsvine/pdfplumber/blob/stable/pdfplumber/table.py#L378">bbox</a>. We use that boundary in the helper function.</blockquote><pre>def is_obj_in_bbox(obj, _bbox, page_height):<br>    &quot;&quot;&quot;<br>    checks if an element boundary box is within another boundary<br>    &quot;&quot;&quot;<br>    objx0, y0, objx1, y1 = obj<br>    x0, top, x1, bottom = _bbox<br>    return (objx0 &gt;= x0) and (objx1 &lt;= x1) and (page_height - y1 &gt;= top) and (page_height - y0 &lt;= bottom)</pre><p>You will notice here that I am employing page_height in the check function and this is due to differences in boundary dimensions between pdfplumber package and pdfminer package. <a href="https://github.com/jsvine/pdfplumber/issues/198">Read more about the bbox inversion between this two packages from this issues.</a></p><p>Now, let’s examine the miner_extract_page function:</p><pre>def miner_extract_page(page_layout, tables):<br>    &quot;&quot;&quot;<br>    this function extract texts, tables, images from a single page layout<br>    Paremeter:<br>      page_layout -&gt; A pdfminer page object<br>      tables -&gt; An array of pdfplumber table objects<br>    Returns:<br>      <br>    &quot;&quot;&quot;<br>    page_height = page_layout.height<br>    extractedTables = []<br>    page_output_str = &quot;&quot;<br>    <br>    for element in page_layout:<br>        if isinstance(element, LTTextContainer):<br>            tabBox = []<br>            # if current element exists in any of the tables, <br>            # append the t to tabBox<br>            for t in tables:<br>                is_obj_n_box = is_obj_in_bbox(element.bbox, t.bbox, page_height)<br>                if is_obj_n_box:<br>                    tabBox.append(t)<br>            # if tabBox is empty, extract the element with get_text() function<br>            if not len(tabBox):<br>                if isinstance(element, LTTextContainer):<br>                    elementText = element.get_text()<br>                    page_output_str += elementText<br>                else:<br>                    # check for figures layout at this point<br>                    # check for part 2 when I talk about images/figures<br>            # else, element exist in a certain table<br>            # therefore, we extract the found table <br>            # using pdfplumber table extract function and <br>            # concatenate to our end results<br>            else:<br>                if not tabBox[0] in extractedTables:<br>                    table_str = tabulate(tabBox[0].extract(**({&quot;vertical_ttb&quot;: False})), tablefmt=&quot;grid&quot;)<br>                    page_output_str += table_str<br>                    page_output_str += &quot;\n&quot;<br>                    # to avoid repetition we used extractedTables to <br>                    # filter already extracted tables. <br>                    extractedTables.append(tabBox[0])<br>    return page_out_str</pre><p>In the above function, I am using tabulate package for printing purposes on the final string. Otherwise it is not necessary. And in case you’re extracting a PDF for LLM models, its better to avoid it as it adds more characters to your final output. But also make sure you employ some sort of an organised way to print it to avoid confusion as the output of a table extraction is 2 dimensional array.</p><h3>Extracting Images</h3><p>This task also involved identifying certain pictograms/images with the PDF files. I had about 10 different pictograms that I was supposed to check if any of them existed in the file or not. My solution was to first extract all images on the PDF page, and utilize image hashing or other template comparison methods (<em>matchTemplate from cv2 package</em>) to determine if the extracted images for the PDF file matched any of the pictograms I had.</p><p>One effective package for extracting images is PyMuPDF (fitz), which I chose to utilize. However, I encountered a challenge where not all images were being properly identified or extracted. I speculated whether this was due to the types of images used during the PDF compilation process, such as PNGs or SVGs, but I couldn’t confirm this definitively.</p><p>For the image extraction process, I implemented a function called check_for_image:</p><pre>def check_for_image(pdf_path):<br>    &quot;&quot;&quot;<br>    Function that get images from pdf pages and save them to local drive<br>    Parameters:<br>    pdf_path -&gt; Path of the PDF file<br>    &quot;&quot;&quot;<br>    pdf_document = fitz.open(pdf_path)<br>    xreflist = []<br>    page_num = 0<br>    il = pdf_document.get_page_images(page_num)<br>    logger.info(f&quot;Found {len(il)} images&quot;)<br><br>    for img in il:<br>        xref = img[0]<br>        if xref in xreflist:<br>            continue<br>        width = img[2]<br>        height = img[3]<br>        <br>        #skip tiny images<br>        if min(width, height) &lt;= 5:<br>            continue<br>        imgdata = img[&quot;image&quot;]<br>        imgfile = os.path.join(f&quot;drawing-img-{xref}-{page_num + 1}.{img[&#39;ext&#39;]}&quot;)<br>        fout = open(imgfile, &quot;wb&quot;)<br>        fout.write(imgdata)<br>        fout.close()<br>        xreflist.append(xref)<br>    pdf_document.close()</pre><p>But because of the image challenge mentioned, I also implemented an extra function in addition to checking normal images. The function was to check for drawings. For drawing can be anything from a lines to more complex shapes (you may read more on the function <a href="https://pymupdf.readthedocs.io/en/latest/page.html#Page.get_drawings">get_drawings</a>), I employed various steps such as enlarging the rectangle size by a certain number, applying filters for anything smaller or any drawing within a bigger drawings, before getting apixmap of the enlarged area of page that include a drawing in it. I would subsequently compare the pixmap generated to the pictograms I have to make a decision.</p><pre>def check_for_drawings(pdf_path):<br>    &quot;&quot;&quot;<br>    Function that finds drawings from pdf pages and save pixmap of <br>    on enlarged drawing&#39;s rectangle to local drive<br><br>    Parameters:<br>    pdf_path -&gt; Path of the PDF file<br>    &quot;&quot;&quot;<br>    pdf_document = fitz.open(pdf_path)<br>    for page_num in range(pdf_document.page_count):<br>        page = pdf_document[page_num]<br>        d = page.get_drawings()<br>        new_rects = []<br>        for p in d:<br>            # filter emplty rectangle<br>            if p[&quot;rect&quot;].is_empty:<br>                continue<br>            w = p[&quot;width&quot;]<br>            if w:<br>                r = p[&quot;rect&quot;] + (-w, -w, w, w)  # enlarge each rectangle by width value<br>                for i in range(len(new_rects)):<br>                    if abs(r &amp; new_rects[i]) &gt; 0:  # touching one of the new rects?<br>                        new_rects[i] |= r  # enlarge it<br>                        break<br>                <br>                # now look if contained in one of the new rects<br>                remainder = [s for s in new_rects if r in s]<br>                if remainder == []:  # no ==&gt; add this rect to new rects<br>                    new_rects.append(r)<br>        <br>        new_rects = list(set(new_rects))  # remove any duplicates<br>        new_rects.sort(key=lambda r: abs(r), reverse=True)<br>        remove = []<br>        for j in range(len(new_rects)):<br>            for i in range(len(new_rects)):<br>                if new_rects[j] in new_rects[i] and i != j:<br>                    remove.append(j)<br>        remove = list(set(remove))<br>        for i in reversed(remove):<br>            del new_rects[i]<br>        new_rects.sort(key=lambda r: (r.tl.y, r.tl.x))  # sort by location<br><br>        mat = fitz.Matrix(5, 5)  # high resolution matrix<br>        for i, r in enumerate(new_rects):<br>            if r.width is None or r.height &lt;= 15 or r.width &lt;= 15:<br>                continue  # skip lines and empty rects<br>            pix = page.get_pixmap(matrix=mat, clip=r)<br>            hayPath = f&quot;drawing-rect{page_num}-{i}.png&quot;<br>            if pix.n - pix.alpha &gt;= 4:      # can be saved as PNG<br>                pix = fitz.Pixmap(fitz.csRGB, pix)<br>            pix.save(hayPath)<br>            pix = None                     # free Pixmap resources<br><br>   pdf_document.close()</pre><p>This comprehensive approach allowed me to successfully extract information from nearly all of the sample PDFs I encountered.</p><p>In reflecting on the limitations or edge cases of my solution, one challenge I faced was extracting tables that are border-less. Despite extensive efforts, I haven’t yet found a straightforward way to achieve this especially if you’re dealing with large set of PDF files that needs to be extracted. However, it’s worth noting that there are issues and discussions on pdfplumber github pages on the case of table borders. You may find all them using the following search query link <a href="https://github.com/jsvine/pdfplumber/issues?q=border">https://github.com/jsvine/pdfplumber/issues?q=border</a></p><p>In the meantime, I encourage exploration of open-source projects that may provide valuable insights and potential solutions to this particular challenge.</p><p><em>Anyone interested in the code, you may find it </em><a href="https://github.com/KhadijaMahanga/textract"><em>here</em></a><em> </em><a href="https://github.com/KhadijaMahanga/textract">https://github.com/KhadijaMahanga/textract</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8ba04da767f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/khadija-mahanga/unstructured-pdf-extraction-series-a8ba04da767f">Unstructured PDF Text Extraction</a> was originally published in <a href="https://medium.com/khadija-mahanga">Khadija Mahanga</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>