aspose file tools*
The moose likes Other JSE/JEE APIs and the fly likes Java code to convert files to PDF Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Other JSE/JEE APIs
Bookmark "Java code to convert files to PDF" Watch "Java code to convert files to PDF" New topic
Author

Java code to convert files to PDF

Madhu Sudhan B T
Greenhorn

Joined: Nov 18, 2009
Posts: 21
Hi All,

I have a requirement to convert any input files (txt,doc,docx,jpg,html,xls etc) to PDF.

I am using the below code to convert the input file to PDF , it is working for txt file but not doc, xls etc as I am getting some special characters in the output file. Can anyone help me with code to accomplish the same.. Your help will be appreciated.. Thanks

private void createPdf(String inputFile, String outputFile, boolean isPictureFile)
{
Document pdfDocument = new Document();
String pdfFilePath = outputFile;
try
{
FileOutputStream fileOutputStream = new FileOutputStream(pdfFilePath);
PdfWriter writer = null;
writer = PdfWriter.getInstance(pdfDocument, fileOutputStream);
writer.open();
pdfDocument.open();
/**
34.
* Proceed if the file given is a picture file
35.
*/
if (isPictureFile)
{
pdfDocument.add(com.lowagie.text.Image.getInstance(inputFile));
}
/**
* Proceed if the file given is (.txt,.html,.doc etc)
*/
else
{
File file = new File(inputFile);
String temp=null;
pdfDocument.add(new Paragraph(org.apache.commons.io.FileUtils.readFileToString(file,temp)));
}
pdfDocument.close();
writer.close();
}
catch (Exception exception)
{
System.out.println("Document Exception!" + exception);
}
}
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42276
    
  64
There is no easy way to convert structured document formats like HTML, XLS, DOCX etc. to PDF. A library like JODConverter (which runs OpenOffice in server mode, so you need that as well) can probably accomplish most of the conversions.


Ping & DNS - my free Android networking tools app
Madhu Sudhan B T
Greenhorn

Joined: Nov 18, 2009
Posts: 21
Thanks Ulf Dittmer for the response.. can you please share some relevant sample java code/examples showing the usage of JODConverter api's? Thanks in advance
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42276
    
  64
I seem to recall that its web site and attendant documentation had sample code.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Java code to convert files to PDF