PDFOne .NET
Powerful all-in-one PDF library for .NET
Compatibility
VS 2005/2008/2010/2012/2013

How to save and retrieve PDF documents to and from a database using C#

Learn to create a database-based PDF document viewer with PDFOne .NET
By V. Subhash

PDF is a binary format. Before putting it in a database, we need to create a BLOB as temporary store. Fortunately, PDFOne supports loading and saving PDF documents from and to memory streams and byte arrays.

In this article, we will see how to create a simple database-based PDF document viewer using byte arrays. We will use the PDFDocument and PDFViewer components for this.

  1. Start Visual Studio and create a Windows Forms application.
  2. Drop the following components on the form:
    • BindingNavigator
    • PDFViewer
    • BindingSource
    • OpenFileDialog
  3. Add references to:
    • Ionic.Zlib.dll
    • BouncyCastle.Crypto.dll
    • Gnostice.XtremeFontEngine.dll
    • Gnostice.XtremeImageEngine.dll
    • Gnostice.PDFOne.dll
  4. Select the BindingNavigator component and set its BindingSource property to the dropped BindingSource component.
  5. Select the BindingNavigator component and click the drop-down button to add a ToolStripLabel component to the toolbar. We will be displaying the document file name on this label.
  6. In your database store, create a table named "docs" with these columns - doc_id, doc_name, doc_binary. For this article, I have used a MS Access database. "doc_id" should be an auto-incrementing field. "doc_name" will be used to store PDF file names. "doc_binary" should be the blob field in which the PDF content is stored.
  7. Select the BindingSource component and set its DataSource property to the database.
  8. If you have selected a flat-file database (an Access MDB file) as I have done, select the database in Solution Explorer and set its Copy to Output Directory property to "Copy if newer". Otherwise, your changes to the database store will get lost every time you run the project, as a fresh copy of the database will be copied to your debug/release folder.
  9. Switch to code view and set these imports.
    using Gnostice.PDFOne;
    using System.Data.OleDb;
    
  10. Add a PDFDocument component as a class variable.
    PDFDocument doc;
    
  11. Modify the form initialization event hander as shown below. Please change the license key.
    InitializeComponent();
    doc = new PDFDocument("your-license-key");
    openFileDialog1.Title = "Select a PDF file";
    openFileDialog1.FileName = "";
    openFileDialog1.Multiselect = false;
    openFileDialog1.Filter = "PDF files|*.pdf|All files|*.*";
    
  12. Add this method to the form source file. We will use it get the contents of a PDF file as a byte array. The byte array will be used to display the document in the viewer and also set the doc_binary fields in the database.
    byte[] getFileBytes(String sFileToBeRead) {
      byte[] ba1;
                
      System.IO.FileStream fs =
                     new System.IO.FileStream(openFileDialog1.FileName, 
                                              System.IO.FileMode.Open);
      lFileSize = fs.Length;
                
      System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
      ba1 = br.ReadBytes((Int32) lFileSize);
    
      br.Close();
      fs.Close();
    
      return (ba1);
    }
    
  13. Double-click on the AddNewItem button on the BindingNavigator toolstrip and set this event handler.
    private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e) {
      if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
        byte[] ba2;
        ba2 = getFileBytes(openFileDialog1.FileName);
    
        DataRow dr = ((DataRowView)bindingNavigator1.BindingSource.Current).Row;
        dr["doc_name"] = openFileDialog1.SafeFileName;
        dr["doc_binary"] = ba2;
    
        toolStripLabel1.Text = openFileDialog1.SafeFileName;
        pdfViewer1.LoadDocument(ba2);
      }
    }
    
    This will help the end-user to select a PDF file. The PDF file is then stored in a new record in the "docs" table and also displayed on the viewer.
  14. Back on the form, double-click the MoveNextItem button on the BindingNavigator toolbar and set the following click-event handler. Set this handler for click-handlers of other record navigation buttons as well and for the "TextChanged" event of the BindingNavigatorPositionItem, which is that little text box in the toolstrip.
    private void bindingNavigatorMoveNextItem_Click(object sender, EventArgs e) {
      byte[] ba2;
    
      if (bindingNavigator1.BindingSource == null) { return; }
      if (bindingNavigator1.BindingSource.Current == null) { return; }
    
      DataRow dr = ((DataRowView)bindingNavigator1.BindingSource.Current).Row;
    
      if (dr.IsNull(2)) { return; }
    
      if (bindingNavigator1.BindingSource.Count > 0) {
        toolStripLabel1.Text = (string)dr["doc_name"];
        ba2 = (byte[])dr["doc_binary"];
        pdfViewer1.LoadDocument(ba2);
      }
    }
    
    Here we load the PDF document from the current record as a byte array and display it in the viewer.
  15. Select the form and set this handler for the form-closing event.
    private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
      bindingSource1.EndEdit();
      if (this._doc_storeDataSet.docs != null) {
        docsTableAdapter.Update(this._doc_storeDataSet.docs);
      }
    }
    
    This will ensure that changes to the database are saved at the end.
  16. Build the project and run it.
  17. When the form is displayed, click the "Add new" button. An "open file" dialog will be displayed.
  18. Select a PDF file and press OK. The PDF file will be added to the database, and then displayed in the viewer.
  19. Repeat the above step several times to add more PDF files to your database.
  20. Close the form. This will save the updated records to the database store.
  21. In the form designer, double-click the form and add the following lines so that it will automatically display PDFs from the database when the application is started.
    if (bindingNavigator1.BindingSource.Count > 0) {
      DataRowView drv = (DataRowView)bindingNavigator1.BindingSource.Current;
      toolStripLabel1.Text = drv["doc_name"].ToString();                
    }
    
  22. Run the project again just to check if the PDF files added earlier have been saved to the database all right. Use the navigation buttons to view the documents.
Animation showing the database document viewer in action. [NOTE: This animation is in GIF format, whose max colors is 256. Rest assured that our viewer component suffers no such limitation.

Video Demo

In this article, you learned how to save and retrieve PDF documents to and from a database. You also learned how to browse documents from a database and display them in a PDF viewer component.

Modifying PDF documents in the database would be just as easy as displaying it in the viewer. Load the same byte array in a PDFDocument instance, make changes to it using PDFDocument methods, make the PDFDocument instance save the modified document back to the byte array, and finally set the updated byte array to the doc_binary field of the current record.

---o0O0o---

Our .NET Developer Tools
XtremeDocumentStudio .NET

Multi-format document-processing component suite for .NET developers.

PDFOne .NET

A .NET PDF component suite to create, edit, view, print, reorganize, encrypt, annotate, and bookmark PDF documents in .NET applications.

Our Delphi/C++Builder developer tools
XtremeDocumentStudio Delphi

Multi-format document-processing component suite for Delphi/C++Builder developers, covering both VCL and FireMonkey platforms.

eDocEngine VCL

A Delphi/C++Builder component suite for creating documents in over 20 formats and also export reports from popular Delphi reporting tools.

PDFtoolkit VCL

A Delphi/C++Builder component suite to edit, enhance, view, print, merge, split, encrypt, annotate, and bookmark PDF documents.

Our Java developer tools
XtremeDocumentStudio (for Java)

Multi-format document-processing component suite for Java developers.

PDFOne (for Java)

A Java PDF component suite to create, edit, view, print, reorganize, encrypt, annotate, bookmark PDF documents in Java applications.

Our Platform-Agnostic Cloud and On-Premises APIs
StarDocs

Cloud-hosted and On-Premises REST-based document-processing and document-viewing APIs

Privacy | Legal | Feedback | Newsletter | Blog | Resellers © 2002-2017 Gnostice Information Technologies Private Limited. All rights reserved.