paololatoja
8/24/2018 - 2:55 AM

PDF Print Lib

PDF Print Lib

package demo.pdf.writing;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import helper.Reader;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class WriteToPdfDemo {

public static void main(String[] args) throws IOException {
String subjects[] = new String[5];

intializeArray(subjects);
askSubjects(subjects);
printArray(subjects);
printArrayToPdf(subjects);
saveRecordsToXML(subjects);
}

public static void intializeArray(String [] subjects) { 
	for (int counter = 0; counter < subjects.length; counter++) {
		subjects[counter] = new String();
	}
}

public static void askSubjects(String [] subjects) throws IOException { 
	for (int counter = 0; counter < subjects.length; counter++) { 
		subjects[counter] = Reader.readString("Enter subject " + (counter + 1) 
		+ ": "); 
	}
}

public static void printArray(String [] subjects) {
System.out.println("\nYour subjects are: ");

	for (int counter = 0; counter < subjects.length; counter++) {
		System.out.println("\t" + subjects[counter]);
	}
}

public static void printArrayToPdf(String [] subjects) {
Document document = new Document();

try {
PdfWriter.getInstance(document,
new FileOutputStream("C:\\Users\\201601120\\Downloads\\subjects.pdf"));

document.open();

Paragraph paragraph = new Paragraph();

Image imageSchoolLogo = Image.getInstance("C:\\Users\\201601120\\Downloads\\iacademy-logo.png");

document.add(imageSchoolLogo);
paragraph.add("\n\nListed are my enrolled subjects:\n");

for (int counter = 0; counter < subjects.length; counter++) {
Chunk chunk = new Chunk("\t" + (counter + 1) + ". "
+ subjects[counter] + "\n");

paragraph.add(chunk);
}

document.add(paragraph);
document.close();
} catch (DocumentException e) {
	e.printStackTrace();
} catch (FileNotFoundException e) {
	e.printStackTrace();
} catch (IOException ioe) {
	ioe.printStackTrace();
}
	}
	
	public static void saveRecordsToXML(String [] subjects) throws FileNotFoundException
	{
		XMLEncoder e = new XMLEncoder(
				new BufferedOutputStream(
				new FileOutputStream("C:\\Users\\201601120\\Downloads"
						+ new Date().getTime()+ ".xml")));
		
		e.writeObject(subjects);
		e.close();
	}
	
	public static String[] readRecordsFromXML(String[] subjects) throws FileNotFoundException
	{
		XMLDecoder d = new XMLDecoder(
				new BufferedInputStream(
						new FileInputStream("C:\\Users\\201601120")));
		String paksa[] = (String[]) d.readObject();
		d.close();
		
		return paksa;
				
	}
}