Free Support Forum - aspose.com

Creating PDF file containing chinease characters in JAVA

Hi,
What is the basic sample code to create a PDF file using java 1.6 with the help of Aspose.
For the input text I have some Chinese or Greek or some other UTF-8 encoded text.

I’m attaching here one text file and one PDF file. I’m using the below code to read the text from the text file and generate the PDF file. In the output PDF file some garbage characters are coming. To view the actual characters just copy the characters from the text file and paste into some word file.

try {
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(“c:/outputFile.txt”)));

String str = in.readLine();

Pdf pdf = new Pdf();
Section sec = pdf.getSections().add();

Text text = new Text(sec, str);
sec.getParagraphs().add(text);
text.getSegments().add(new Segment(text));

pdf.save(new FileOutputStream(“c:/TextExample.pdf”));
} catch (Exception e) {
System.out.println(e.getMessage());
}

Hi,

Thanks for using our products. In order to convert UTF-8 characters inside PDF document, first read the source file with UTF-8 encoding and please specify Arial Unicode MS as font file and also please call Pdf.SetUnicode(); method to include font subset in resultant PDF document. Please take a look over attached resultant PDF document that I have generated using following code snippet with Aspose.Pdf for Java 3.0.1. In case you still encounter any issue or you have any further query, please feel free to contact. We apologize for your inconvenience.

[Java]
try{
StringBuffer sb = new StringBuffer(1024);
BufferedReader reader =new BufferedReader(new InputStreamReader(new FileInputStream(“d:\pdftest\outputFile.txt”), “UTF-8”));

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());
//text1.setIsAutoFontAdjustProcessed(true);
text1.getTextInfo().setFontName(“Arial Unicode MS”);
// add text to paragraphs collection of section
sec1.getParagraphs().add(text1);
// include Unicode characters subset inside the resultant PDF
pdf1.SetUnicode();
// save the resultant PDF files
pdf1.save(“d:\pdftest\outputFile-Converted.pdf”);
}catch(java.io.IOException ioe){

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

}

Thanks a lot. It worked for me. :slight_smile: