Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java code to convert files to PDF

 
Madhu Sudhan B T
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Pie
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Madhu Sudhan B T
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Pie
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I seem to recall that its web site and attendant documentation had sample code.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic