DEV Community

Cover image for PDF Documents in Oracle Database – Beyond Simple File Storage
Laszlo Lokodi
Laszlo Lokodi

Posted on

PDF Documents in Oracle Database – Beyond Simple File Storage

  1. Let's think a little differently about the database! When we start working with an Oracle database, the first data types we usually learn are NUMBER, DATE, and VARCHAR2. We create tables, define relationships between them, store data, and write SQL queries. However, the modern Oracle database is capable of much more than this. Over the years, many additional data types and technologies have been introduced: • XMLTYPE – handling XML documents. • JSON – storing and processing JSON documents. • SDO_GEOMETRY – managing geospatial data. • CLOB – storing large amounts of text data. • BLOB – storing binary data, images, and documents. • VECTOR – storing embeddings generated by artificial intelligence, among other uses. These capabilities significantly expand the range of applications that can be implemented in the database. Let's look at a simple example! We are developing an invoicing application. Our database contains customers, invoices, invoice items, payment due dates, and financial transactions. We also generate PDF documents from invoices. But where do we store these PDFs? In a directory on the application server? In a cloud-based object store? Or maybe in the Oracle database itself? All three solutions can work. Let's explore what options we have!
  2. Why store PDF documents in the database? From a business perspective, a PDF associated with an invoice is just as much a part of the invoice as its amount or issue date. If we store the document outside the database, we have to take care of different parts of the same business object in two separate systems. Let's imagine the following case:
    1. We create an invoice in the database.
    2. We generate the corresponding PDF document.
    3. We save the PDF to an external file system.
    4. Due to an error, the database transaction is rolled back. What happens to the PDF document that has already been created? A ROLLBACK in the database will not delete the PDF in the file system. The application must take care of this separately. However, if the document is also stored in the database, the invoice data and the storage of the PDF can be part of the same transaction. This is just one example of the benefits of storing documents within a database. Additional benefits include: • Unified access control. • Ensuring integrity between business data and documents. • Auditing and encryption options. • Integrated backup and recovery. • Use of the database's high availability features. • Direct access to documents from SQL and PL/SQL environments. Of course, this does not mean that we necessarily have to store every document in the database.
  3. First option: store only metadata and a reference This is perhaps the simplest and one of the most commonly used solutions. We create a table in which we store the document name, the associated business record ID, and the document path. CREATE TABLE invoice_links ( invoice_id NUMBER PRIMARY KEY, file_name VARCHAR2(255), file_url VARCHAR2(2000) ); The actual content of the PDF resides in an external system. This could be a traditional file system, a document management system, or even Amazon S3, Oracle Cloud Object Storage, or another object storage service. The advantage of this solution is that documents do not significantly increase the size of the database, and the file storage infrastructure can be scaled independently of the database. The disadvantage is that the database only knows where the document should be. If someone deletes, renames, or moves the PDF, the link stored in the database may become invalid. We also need to manage the security, backup, and availability of documents separately.
  4. Second option: the BFILE data type Did you know that Oracle has a data type specifically for accessing external binary files? This is the BFILE (Binary File) data type. BFILE allows us to reference an external file in such a way that its contents can be accessed using Oracle's built-in LOB handling functions. First, we need an Oracle DIRECTORY object: CREATE DIRECTORY pdf_dir AS '/data/pdf'; A DIRECTORY is a database object that refers to a directory on the file system accessible to the database server. Creating it requires appropriate privileges, and the application schema must be granted READ access to the DIRECTORY object. The Oracle database server process also needs operating system read access to the files. Then we can create our table: CREATE TABLE invoice_files ( invoice_id NUMBER PRIMARY KEY, pdf_file BFILE ); Let's add a document: INSERT INTO invoice_files VALUES ( 1001, BFILENAME('PDF_DIR', 'INV-1001.pdf') ); This hasn't loaded the PDF into the database yet. We've just created a file locator that Oracle can handle natively. For example, we can use the following query to check whether the referenced file exists: SELECT invoice_id, DBMS_LOB.FILEEXISTS(pdf_file) AS file_exists FROM invoice_files; The most important limitation of BFILE is that we can only read the contents of the file from the database. The document still resides outside the database, so its physical contents are not part of database transactions and database backups. BFILE can be particularly useful for accessing existing file collections or loading documents into the database.
  5. Third option: External Tables Oracle's external table feature allows you to access the contents of external files as SQL tables. Most developers use this technology to import CSV files, but it is less well known that it can also be used to handle binary documents. With the LOBFILE transformation of the ORACLE_LOADER access driver, we can assign the entire contents of external files to a BLOB column of an external table. Imagine that we need to import thousands of PDF invoices from an old application. We have the PDF files and a CSV file containing the invoice IDs and file names: 1001,INV-1001.pdf 1002,INV-1002.pdf 1003,INV-1003.pdf With a properly defined external table, the invoice IDs and the binary content of the PDFs can be accessed in a single SQL query. Moreover, we can also load the data into a traditional database table with an INSERT INTO ... SELECT statement. External tables are worth considering primarily for integration, migration, and bulk data loading tasks.
  6. Fourth option: store the entire PDF in a BLOB column!
    BLOB (Binary Large Object) is an Oracle data type for storing binary data.
    A BLOB column can store a PDF document, an image, a ZIP file, a Word document, or any other binary data.
    Let's create a simple document table:
    CREATE TABLE invoice_documents (
    invoice_id NUMBER PRIMARY KEY,
    file_name VARCHAR2(255) NOT NULL,
    mime_type VARCHAR2(100) DEFAULT 'application/pdf',
    pdf_content BLOB NOT NULL
    )
    LOB (pdf_content) STORE AS SECUREFILE;
    Notice that the document and its metadata are in the same table.
    In the example, we also specified the storage mode: SecureFiles. This requires a suitable tablespace that uses automatic segment space management (ASSM).
    SecureFiles is Oracle's modern LOB storage technology that offers compression, deduplication, and encryption capabilities, among other things. Some of these features are dependent on the Oracle Database edition and licensing requirements.
    Let's load a PDF document using the DIRECTORY object we created earlier.
    DECLARE
    l_source BFILE;
    l_target BLOB;
    l_src_offset INTEGER := 1;
    l_dest_offset INTEGER := 1;
    BEGIN
    l_source := BFILENAME(
    'PDF_DIR',
    'INV-1001.pdf'
    );

    INSERT INTO invoice_documents (
    invoice_id,
    file_name,
    pdf_content
    )
    VALUES (
    1001,
    'INV-1001.pdf',
    EMPTY_BLOB()
    )
    RETURNING pdf_content INTO l_target;

    DBMS_LOB.FILEOPEN(l_source);

    DBMS_LOB.LOADBLOBFROMFILE(
    dest_lob => l_target,
    src_bfile => l_source,
    amount => DBMS_LOB.LOBMAXSIZE,
    dest_offset => l_dest_offset,
    src_offset => l_src_offset
    );

    DBMS_LOB.FILECLOSE(l_source);

EXCEPTION
WHEN OTHERS THEN
IF DBMS_LOB.FILEISOPEN(l_source) = 1 THEN
DBMS_LOB.FILECLOSE(l_source);
END IF;
RAISE;
END;
/
After successful execution, we can finalize the transaction with a COMMIT statement.
What happened in the example above?
We created an empty BLOB using EMPTY_BLOB, and then used the RETURNING INTO clause to obtain its LOB locator.
We used the DBMS_LOB.LOADBLOBFROMFILE procedure to copy the entire contents of the external PDF file into the BLOB object in the database.
Now we no longer need the original external file to access the PDF.
For example, let's check the size of the stored document:
SELECT invoice_id,
file_name,
DBMS_LOB.GETLENGTH(pdf_content) AS file_size
FROM invoice_documents;
For a BLOB, GETLENGTH returns the size of the stored content in bytes.
It is important to note that when storing large numbers of documents, LOB segments can even be placed in a separate tablespace. This way, the physical storage of relational data and documents can be separated.

  1. Fifth option: Oracle Database File System (DBFS) What happens if we want to take advantage of the benefits of in-database storage, but our existing application can only work with a traditional file system? Oracle offers a solution for this as well. With the Oracle Database File System (DBFS), we can access files stored in the database through a file system-like interface. In the case of SecureFiles-based DBFS, documents are physically located in the database, while in a properly configured environment they can also be managed as files. So in this case, DBFS is not a new data storage method, but an additional access option. It requires a more complex infrastructure, but can be an interesting solution when integrating existing file-based applications.
  2. Storage is just the beginning! So far, we've talked about where and how to store PDF documents. But what do we do with them once they're in the database? A PDF stored in a BLOB column does not automatically become interpretable business data. For Oracle, it is essentially a sequence of bytes. To process the PDF format, we need appropriate programs, functions, and procedures. For example, Oracle Text allows you to perform full-text searches within the content of supported PDF documents. Oracle AI Database also offers new capabilities. The UTL_TO_TEXT function of the DBMS_VECTOR_CHAIN package can be used to extract the text content of a PDF and return it as a CLOB: SELECT DBMS_VECTOR_CHAIN.UTL_TO_TEXT(pdf_content) FROM invoice_documents WHERE invoice_id = 1001; The text extracted in this way can later be used to generate embeddings, perform semantic search, or develop retrieval-augmented generation (RAG) applications. Of course, in the case of a PDF containing only scanned images, we may need optical character recognition (OCR) processing. But what happens if we don't simply want to search a document, but rather create or modify it? Native PL/SQL libraries, such as PLslash's document processing components, allow you to perform many additional operations directly in the Oracle database: • Generating PDF documents from business data. • Merging and splitting documents. • Extracting text and metadata. • Filling out PDF forms. • Creating and verifying digital signatures. • Converting between document formats. This way, we don't have to transfer documents to an external application server for each processing operation.
  3. So should we store all PDF documents in the database? Of course not! If you have several terabytes of rarely used archived documents, external object storage may be a more economical solution. If an application already has a well-functioning corporate document management system, it is not necessarily worth replacing it. We can also consider hybrid solutions. Actively used business documents are stored in the database, while finalized and rarely accessed documents are moved to an external archive. To choose the right architecture, it is worth answering a few questions: • How many documents do we want to store? • How often do we use them? • Do we need transactional consistency? • What security and auditing requirements do we need to meet? • Do we want to process or search the content of the documents? • What are the costs of database growth and backups? Based on the answers, it will be much easier to choose the right solution.
  4. Summary As Oracle developers, we tend to think of databases primarily as systems for storing structured data. However, Oracle has provided many features for decades that allow us to create significantly more complex applications. Storing and processing PDF documents within a database is a good example of this. The next time you develop an application that uses PDF documents, don't automatically think of an external file system. Consider the benefits of storing and processing documents in the same environment as their associated business data. The solution may be simpler than we first think. A PDF document is not just a file. It is part of your business data.

Top comments (0)