Post: [Java Tutorial #2] Convert small or large text files to PDF
01-22-2014, 05:59 AM #1
(adsbygoogle = window.adsbygoogle || []).push({}); Hi,

In my last Tutorial I shared the You must login or register to view this content.. Today I will be sharing code for converting small or large text files to pdf in java. Many few libraries are available online that allow users to perform this operation. As I told in my last tutorial that I use Aspose [URL=”[url]https://www.aspose.com/java/pdf-component.aspx”]PDF[/url] Java Library [/URL] for managing my PDF files and I am using this library also for conversion, you can use library of your own choice or can use the code in your application. You will find two sets of code below, one for converting small text file and second for converting large text files.

Convering Text file to PDF
    
try{

StringBuffer sb = new StringBuffer(1024);
BufferedReader reader = new BufferedReader(new FileReader("test.txt"));

int ch = -1;

while( (ch = reader.read()) > -1){
sb.append((char)ch);
}

reader.close();

//Instantiate Pdf pbject by calling its empty constructor
Pdf pdf1 = new Pdf();

//Create a new section in the Pdf object
Section sec1 = pdf1.getSections().add();

//Create a new text paragraph and pass the text to its constructor as argument
Text text1 = new Text(sec1,sb.toString());

sec1.getParagraphs().add(text1);

pdf1.save("d:/pdftest/Text_File_to_PDF.pdf");

}catch(java.io.IOException ioe){
System.out.println(ioe.getMessage());
}


Converting Large Text files to PDF
    

try{
//Instantiate Pdf pbject by calling its empty constructor
Pdf pdf1 = new Pdf();
//Create a new section in the Pdf object
Section sec1 = pdf1.getSections().add();

// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("d:/pdftest/LargeText.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null)
{
//Create a new text paragraph and pass the text to its constructor as argument
Text text1 = new Text(sec1,strLine);
sec1.getParagraphs().add(text1);
}

//Close the input stream
in.close();

// Save the PDF file
pdf1.save("d:/pdftest/LargeText.pdf");

}catch(java.io.IOException ioe){
System.out.println(ioe.getMessage());
}catch(Exception e){
System.out.println(e.getMessage());
}



Try the above code and share your views about the code.

Copyright © 2024, NextGenUpdate.
All Rights Reserved.

Gray NextGenUpdate Logo