Wednesday, September 11, 2013

Java - Generate PDF file using local machine's .txt file

Following sample explain how to create pdf file using iText.jar(used iText 5.0.4 for following sample)

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Date;

import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class GeneratePDF {

    public static void main(String[] args) {
        try {
            OutputStream file = new FileOutputStream(new File("D:\\Test.pdf"));

            Document document = new Document();
            PdfWriter.getInstance(document, file);

            document.open();
            document.setMargins(50, 50, 50, 50);
            document.add(new Paragraph("Page 1"));
            document.add(new Paragraph(new Date().toString()));

            document.newPage();// new Page
            document.add(new Paragraph("Page 2"));

            document.newPage();// new Page
            document.add(new Paragraph("Page 3 : Added external text file"));

            // read file from location and add to same PDF
            File fileIn = new File("D:\\sampleTextFileInYourMachine.txt");
            FileInputStream fi = new FileInputStream(fileIn);

            String text = getFileContent(fi);
            document.add(new Paragraph(text));
            document.close();
            file.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getFileContent(FileInputStream fis) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
                sb.append('\n');
            }
            return sb.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

}

No comments:

This site providing you to JAVA Language easy way. I think if you are beginner to JAVA refer this to implements you knowledge using only with very simplest codes.