To create a PDF file from the TEXT file using Java. The Text file withe path is given as input and the created PDF will be saved in the same path .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | package createPDF; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import com.itextpdf.text.Chunk; import com.itextpdf.text.Document; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; public class TextfiletoPDFCreation { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub if (args.length> 0 ) { File file= new File(args[ 0 ]); if (file.getName().endsWith( ".txt" )) { if (convertTextfileToPDF(file)) { System.out.println( "PDF created" ); } } } } public static boolean convertTextfileToPDF(File file) { FileInputStream iStream= null ; DataInputStream in= null ; InputStreamReader is= null ; BufferedReader br= null ; try { Document pdfDoc = new Document(); String text_file_name =file.getParent()+ "\\" + "texttpPDF.pdf" ; PdfWriter writer=PdfWriter.getInstance(pdfDoc, new FileOutputStream(text_file_name)); pdfDoc.open(); pdfDoc.setMarginMirroring( true ); pdfDoc.setMargins( 36 , 72 , 108 , 180 ); pdfDoc.topMargin(); Font normal_font = new Font(); Font bold_font = new Font(); bold_font.setStyle(Font.BOLD); bold_font.setSize( 10 ); normal_font.setStyle(Font.NORMAL); normal_font.setSize( 10 ); pdfDoc.add( new Paragraph( "\n" )); if (file.exists()) { iStream = new FileInputStream(file); in = new DataInputStream(iStream); is= new InputStreamReader(in); br = new BufferedReader(is); String strLine; while ((strLine = br.readLine()) != null ) { Paragraph para = new Paragraph(strLine+ "\n" ,normal_font); para.setAlignment(Element.ALIGN_JUSTIFIED); pdfDoc.add(para); } } else { System.out.println( "file does not exist" ); return false ; } pdfDoc.close(); } catch (Exception e) { System.out.println( "FileUtility.covertEmailToPDF(): exception = " + e.getMessage()); } finally { try { if (br!= null ) { br.close(); } if (is!= null ) { is.close(); } if (in!= null ) { in.close(); } if (iStream!= null ) { iStream.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return true ; } } |
Very informative code. Thanks for Sharing. I have also found code to convert small and large text files to pdf format in java, its also very useful and very few lines of code to perform this task.