2

I have a Java class which is generating PDF file using iText library. Now as per my need I have to save this generated PDF file to MySQL database table but I have no idea how to do it.

My concerns are:

  1. what datatype should I use in MySQL column of PDF table to save PDF file
  2. which query will insert generated PDF file to database

At present I am generating PDF file and storing it into hard-coded file path of my local disk.

Here is my PDF generation code in Java:

OutputStream file = new FileOutputStream(new File("D://timer.pdf"));
Document document = new Document();
PdfWriter.getInstance(document, file);

//Inserting Table in PDF
PdfPTable table = new PdfPTable(3);

PdfPCell cell = new PdfPCell(new Paragraph("Java4s.com"));

cell.setColspan(3);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setPadding(10.0f);
cell.setBackgroundColor(new BaseColor(140, 221, 8));

table.addCell(cell);

table.addCell("Name");
table.addCell("Address");
table.addCell("Country");
table.addCell("Java4s");
table.addCell("NC");
table.addCell("United States");
table.setSpacingBefore(30.0f);  // Space Before table starts, like margin-top in CSS
table.setSpacingAfter(30.0f);   // Space After table starts, like margin-Bottom in CSS

//Inserting List in PDF
List list = new List(true, 30);
list.add(new ListItem("Java4s"));
list.add(new ListItem("Php4s"));
list.add(new ListItem("Some Thing..."));

//Text formating in PDF
Chunk chunk = new Chunk("Welecome To Java4s Programming Blog...");
chunk.setUnderline(+1f, -2f);//1st co-ordinate is for line width,2nd is space between
Chunk chunk1 = new Chunk("Php4s.com");
chunk1.setUnderline(+4f, -8f);
chunk1.setBackground(new BaseColor(17, 46, 193));

//Now Insert Every Thing Into PDF Document
document.open();//PDF document opened........                  
document.add(Chunk.NEWLINE);   //Something like in HTML :-)
document.add(new Paragraph("Dear Java4s.com"));
document.add(new Paragraph("Document Generated On - " + newDate().toString()));
document.add(table);
document.add(list);            //In the new page we are going to add list
document.close();

file.close();

System.out.println("Pdf created successfully..");


Please help me.
Thanks in advance.

2
  • store texts rather than pdf. whenever you want retrive and create a pdf Commented Nov 14, 2013 at 6:26
  • 1
    You can read the file into a byte[], save the raw data in the table, retrieve it and write it back using a fileoutputstream.write(byte[] array) Commented Nov 14, 2013 at 6:26

1 Answer 1

5
  1. Datatype that you can use is BLOB.
  2. Convert the PDF file and persist the byte[] array in database.

    private byte[] getByteArrayFromFile(final Document handledDocument) throws IOException {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final InputStream in = new FileInputStream(handledDocument);
        final byte[] buffer = new byte[500];
    
        int read = -1;
        while ((read = in.read(buffer)) > 0) {
            baos.write(buffer, 0, read);
        }
        in.close();
    
        return baos.toByteArray();
    }
    
  3. To insert it into DB If you are using any ORM tools you just have to map the column as blob and the tool will handle it for you. In case you are not using it then you can create a prepared statement. Statement has a method called setBlob() which will be useful. Consider the below example and create a normal insert query with blob column.

    String sql = "INSERT INTO testtable(stringcolumn, blobcolumn) VALUES(?,?)";
    
    PreparedStatement statement = conn.getConnection().prepareStatement(sql);
    statement.setLong(1, version);
    ByteArrayInputStream bais = new ByteArrayInputStream(getByteArrayFromFile(document));
    statement.setBlob(2, bais);          
    statement.execute();
    
    conn.commit();
    
Sign up to request clarification or add additional context in comments.

3 Comments

I'll give you plus1 for creating byte array of given file. Thanks for posting this.
Thank you, i can save the file in the sql. but how can i download this file?
I have tried your code; however I get an error. I need to store a pdf (each pdf will be < 5 pages maximum) in a mySQL database. The column is defined as mediumblob. The test pdf is 198 KB. I get the error "Errors occurred in addMedicalPlan: java.io.FileNotFoundException: " followed by a dump of the file " JVBERi0xLjcKCjQgMCBvYmoKKElkZW50aXR5KQplbmRvYmoKNS ......" and at the end "(The filename or extension is too long)". Your help would be greatly appreciated. I am not a programmer and am doing this pro-bono for my Scouts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.