How to save generated PDF files to MySQL database using Java? - java

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:
what datatype should I use in MySQL column of PDF table to save PDF
file
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.

Datatype that you can use is BLOB.
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();
}
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();

Related

iText7 : how to use the same reader in multiple page of the same pdf

As the title said,I have an existing pdf that contains an empty table with a custom design, I want to create a pdf file that write data in that table, but I need to have that same table on every page of my new pdf.
public byte[] pdfRdv(Rdv rdv, List<RdvClient> clients) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//this file contains a empty table in which I want to insert each iteration of my
//table clients
String src = "C://Users//ASUS//Downloads//rdv.pdf";
PdfReader reader = new PdfReader(src);
PdfWriter writer = new PdfWriter(baos);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
Document document = new Document(pdfDoc);
for(int i = 0; i < clients.size(); i++){
if(i > 0){
// I tried to add for each itaration a new page but i don't know how to insert in
//it the table in the existing pdf (reader)
pdfDoc.addNewPage(i+2);
}
Paragraph p1 = new Paragraph(clients.get(i).getId().toString()).setFontSize(10);
p1.setFixedPosition(140, 687, 400);
document.add(p1);
//..
}
document.close();
pdfDoc.close();
byte[] pdf = baos.toByteArray();
return pdf;
}
Thank you in advance

ByteArrayOutputStream size is zero in PDFWriter?

I have been breaking my head from past 1 hour i am not able to solve this issue...i know its easy to write the PDF in java but my outputstream size is zero,... here is my code..
Document document = new Document();
try
{
ByteArrayOutputStream dsf = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, dsf);
document.open();
document.add(new Paragraph("Some content here"));
// Set attributes here
document.addAuthor("Lokesh Gupta");
document.addCreationDate();
document.addCreator("HowToDoInJava.com");
document.addTitle("Set Attribute Example");
document.addSubject("An example to show how attributes can be added to pdf files.");
if (frontPageMap != null && !frontPageMap.isEmpty()) {
PdfPTable table = new PdfPTable(frontPageMap.size()); // creating
// columns.
table.setWidthPercentage(100); // Width 100%
table.setSpacingBefore(10f); // Space before table
table.setSpacingAfter(10f); // Space after table
for (Map.Entry<String, Object> entry : frontPageMap.entrySet()) {
PdfPCell tempCell = new PdfPCell(new Paragraph(entry.getKey()));
tempCell.setBorderColor(BaseColor.BLUE);
tempCell.setPaddingLeft(10);
tempCell.setHorizontalAlignment(Element.ALIGN_CENTER);
tempCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell(tempCell);
}
document.add(table);
}
System.out.println("Size Of Byte Array is "+dsf.size());
ByteArrayInputStream bInput = new ByteArrayInputStream(dsf.toByteArray());
file = new DefaultStreamedContent(bInput, "pdf", fileName);
document.close();
writer.close();
NOTE:I am able to print map key values also but When i download PDF the size is zero.
Maybe you should finish creating the PDF (with document.close() and writer.close()), before you try to access the contents:
//Finish writing the PDF
document.close();
writer.close();
//now check what's been written:
System.out.println("Size Of Byte Array is "+dsf.size());
ByteArrayInputStream bInput = new ByteArrayInputStream(dsf.toByteArray());
file = new DefaultStreamedContent(bInput, "pdf", fileName);
document.close();
writer.close();
ByteArrayInputStream bInput = new ByteArrayInputStream(dsf.toByteArray());
file = new DefaultStreamedContent(bInput, "pdf", fileName);
System.out.println("Size Of Byte Array is "+dsf.size());
Add this code. Here you finish writing the pdf file and then you can print the size of the file. The size my be zero according to the content , but the pdf file generated should have all the records written in it ... Cheers :)

Vaadin Convert and display image as PDF

Does anyone know how image file can be easily converted into PDF format. What I need is to get the image from database and display it on the screen as PDF. What am I doing wrong? I tried to use iText but with no results.
My code:
StreamResource resource = file.downloadFromDatabase();//get file from db
Document converToPdf=new Document();//Create Document Object
PdfWriter.getInstance(convertToPdf, new FileOutputStream(""));//Create PdfWriter for Document to hold physical file
convertToPdf.open();
Image convertJpg=Image.getInstance(resource); //Get the input image to Convert to PDF
convertToPdf.add(convertJpg);//Add image to Document
Embedded pdf = new Embedded("", convertToPdf);//display document
pdf.setMimeType("application/pdf");
pdf.setType(Embedded.TYPE_BROWSER);
pdf.setSizeFull();
Thanks.
You're not using iText correctly:
You never close your writer, so the addition of the image never gets written to the outputstream.
You pass an empty string to your FileOutputStream. If you want to keep the pdf in memory, use a ByteArrayOutputStream. If not, define a temporary name instead.
You pass your Document object, which is a iText-specific object to your Embedded object and treat it like a file. It is not a pdf-file or byte[]. You'll probably want to pass either your ByteArrayOutputStream or read the temp file as a ByteArrayOutputStream into memory and pass that to Embedded.
Maybe someone will use (Vaadin + iText)
Button but = new Button("FV");
StreamResource myResource = getPDFStream();
FileDownloader fileDownloader = new FileDownloader(myResource);
fileDownloader.extend(but);
hboxBottom.addComponent( but );
private StreamResource getPDFStream() {
StreamResource.StreamSource source = new StreamResource.StreamSource() {
public InputStream getStream() {
// step 1
com.itextpdf.text.Document document = new com.itextpdf.text.Document();
// step 2
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
com.itextpdf.text.pdf.PdfWriter.getInstance(document, baos);
// step 3
document.open();
document.add(Chunk.NEWLINE); //Something like in HTML :-)
document.add(new Paragraph("TEST" ));
document.add(Chunk.NEWLINE); //Something like in HTML :-)
document.newPage(); //Opened new page
//document.add(list); //In the new page we are going to add list
document.close();
//file.close();
System.out.println("Pdf created successfully..");
} catch (DocumentException ex) {
Logger.getLogger(WndOrderZwd.class.getName()).log(Level.SEVERE, null, ex);
}
ByteArrayOutputStream stream = baos;
InputStream input = new ByteArrayInputStream(stream.toByteArray());
return input;
}
};
StreamResource resource = new StreamResource ( source, "test.pdf" );
return resource;
}

Retrieve Image From JLabel and store it in a variable in Java

How do I retrieve an my image that has been fetched from mysql database and store it in a variable?
The image retrieved from the database is as follows:
byte[] imageData = rs.getBytes("Image");
format = new ImageIcon(imageData);
lblimg.setIcon(format);
Now what I want to do, to store the lblimg into a variable. Then I can use the variable which contains the image to add in a pdf file.
Document doc = new Document();
PdfWriter.getInstance(doc, new FileOutputStream("Report.pdf"));
doc.open();
doc.add(new Paragraph( // img to be added here ));
Please help me to achieve that. Thanks

java generate PDF in separate class but return from controller

I'm trying to add a PDF generator to my website. Everything works fine as far as the generator in the controller
ConsumerController.java:
public String downloadPDF(#PathVariable("id") Long id, #PathVariable("transaction") Long transaction, Model uiModel, HttpServletRequest httpServletRequest, HttpServletResponse response) {
Document document = new Document();
try{
response.setContentType("application/pdf");
PdfWriter.getInstance(document, response.getOutputStream());
document.open();
document.add(new Paragraph("Hello Kiran"));
document.add(new Paragraph("Hello" + id));
document.add(new Paragraph("For"+ transaction));
document.add(new Paragraph(new Date().toString()));
}catch(Exception e){
e.printStackTrace();
}
document.close();
return null;
}
this is what i have at the moment and this is exactly how i want it to work, but the one i would like to add would be better off in its own class (code below).
PDFGenerator.java:
public void generatorPDF() throws Exception{
Document d = new Document();
try{
PdfWriter writer = PdfWriter.getInstance(d, new FileOutputStream("CodeOfDoom.pdf"));
d.open();
for(int i=0; i<10; i++){
PdfPTable table = generateLineItemTable(_order.getLineItems());
PdfPTable headerTable= generateHeaderTable(_order.getCustomer());
addBarcode(writer,headerTable);
//add customer barcode to the header
d.add(headerTable);
d.add(table);
Paragraph p = new Paragraph("\n\nFor more, please visit ");
Anchor anchor = new Anchor("www.codeofdoom.com/wordpress");
p.add(anchor);
d.add(p);
d.newPage();
}
d.close();
}catch(Exception e){
e.printStackTrace();
}
}
so far with anything that i have tried, the PDF writer seems to be the issue, because I'm not sure how to go about adding the document to the writer from a separate class
In the first instance, you're creating the PDF and writing it directly to the response stream. In the second class, you are writing it to a file.
If you want to create the PDF in a different class, one solution would be to pass the output stream into the constructor of the class. If you don't want to pass a reference to the output stream, you could create the PDF in memory by writing to a ByteArrayOutputStream and then return the generated array of bytes. With that approach, you could then write the generated PDF bytes back to the response stream. This approach assumes your PDF is small enough to fit into memory, though.

Categories

Resources