Pages

how to write pdf file in java simple example


Very Simple methods

But before you start this application you must download iTextpdf related jar(s).

you need to use jar files Click Here 

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class SimplePdf {
   
    public static void main(String[] args) {
       
        try {
            int Count=0;
           
            File myDir=new File("D:/new/files");
            myDir.mkdirs();
            Count++;
            //File file1 = new File(myDir, "filename.pdf");
           
            String fname = "file" + Count + ".pdf";
            File file1 = new File (myDir, fname);
            myDir.mkdirs();
            Count++;
            System.out.println(file1);
       
            System.out.println(Count);
            OutputStream file = new FileOutputStream(file1);
            Document document = new Document();
            PdfWriter.getInstance(document, file);
           
           
            String name="Srini";
            String address="India";
            PdfPTable table=new PdfPTable(2);
            PdfPCell cell = new PdfPCell (new Paragraph ("Beautyton"));
            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(name);
            table.addCell(address);
       
            table.setSpacingBefore(50.0f);       // Space Before table starts, like margin-top in CSS
            table.setSpacingAfter(50.0f);        // Space After table starts, like margin-Bottom in CSS                                         
            document.open();//PDF document opened........                 
            document.add(Chunk.NEWLINE);   //Something like in HTML :-)
            document.add(new Paragraph("Welcome"));
            document.add(new Paragraph("Document Generated On - "+new Date().toString()));   
            document.add(table);
            document.add(Chunk.NEWLINE);   //Something like in HTML :-)                               
            document.close();
            file.close();
            System.out.println("Pdf created successfully..");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

No comments:

Post a Comment