Aspose.Pdf

Converting text file to PDF

We often get queries from customers who would like to convert their text files to PDF. We are often asked if we can quickly provide some code which can accomplish this task and save them the effort of going through the documentation. So for the benefit of everyone, we present here a simple example which can be used as it is to easily and efficiently convert a text file to PDF using Aspose.Pdf.

 

[C#]

 

System.IO.TextReader tr = new StreamReader("test.txt");

 

//Instantiate Pdf pbject by calling its empty constructor

Aspose.Pdf.Pdf pdf1 = new Aspose.Pdf.Pdf();

 

//Create a new section in the Pdf object

Aspose.Pdf.Section sec1 = pdf1.Sections.Add();

 

//Create a new text paragraph and pass the text to its constructor as argument

Aspose.Pdf.Text t2 = new Aspose.Pdf.Text(tr.ReadToEnd());

 

sec1.Paragraphs.Add(t2);

 

pdf1.Save("test.Pdf");

 

 

[VB.NET]

 

Dim tr As System.IO.TextReader = New StreamReader("test.txt")

 

'Instantiate Pdf pbject by calling its empty constructor

Dim pdf1 As Aspose.Pdf.Pdf = New Aspose.Pdf.Pdf()

 

'Create a new section in the Pdf object

Dim sec1 As Aspose.Pdf.Section = pdf1.Sections.Add()

 

'Create a new text paragraph and pass the text to its constructor as argument

Dim t2 As Aspose.Pdf.Text = New Aspose.Pdf.Text(tr.ReadToEnd())

 

sec1.Paragraphs.Add(t2)

 

pdf1.Save("test.Pdf")

 

 

[Java]

 

 

try{

 

   StringBuffer sb = new StringBuffer(1024);

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

                                   

   char[] chars = new char[1024];

 

   int numRead = 0;

 

   while( (numRead = reader.read(chars)) > -1){

      sb.append(String.valueOf(chars));     

   }

 

   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(new FileOutputStream(new File("test.pdf")));

 

}catch(java.io.IOException ioe){

   System.out.println(ioe.getMessage());

}catch(AsposeBaseException e){

   System.out.println(e.getMessage());

}