Home > JAVA > Memahami Komponen Dasar iText

Memahami Komponen Dasar iText

Artikel ini akan membahas komponen-komponen dasar pembangun dokumen PDF di iText, seperti: Chunk, Phrase, Paragraph, List, Anchor, Chapter, Section, dan Image. 

Chunk

Merupakan bagian terkecil dari teks yang dapat ditambahkan ke dalam Document. Memiliki properti seperti: jenis font, ukuran font, warna font, style font, warna background, dapat dibuat superscript atau subscript, ditambahkan underline. Biasanya Chunk digunakan untuk membangun objek seperti Phrase atau Paragraph. Chunk tidak memperhatikan spasi antar baris, biasanya kita tambahkan leading secara manual. Untuk jenis font akan disesuaikan dengan font yang terinstal di sistem, jika font yang diminta tidak ada maka akan diberikan font yang masih satu family (terdeket). Defaultnya iText menggunakan font Helvetica dengan ukuran 12 pt.


public void createPDF(String fileName) throws FileNotFoundException, DocumentException, SQLException{
 //Langkah1
 Document doc = new Document();
 //Langkah 2, kita tambahin leading
 PdfWriter.getInstance(doc, new FileOutputStream(fileName)).setInitialLeading(16);
 //Langkah 3
 doc.open();
 //Langkah 4, ambil data dari db
 DatabaseConnection dbConn = new PostgreSQLConnection();
 Statement stmt = dbConn.createStatement();
 ResultSet rs = stmt.executeQuery("SELECT country, id FROM film_country ORDER BY country");
 //Definiskan font
 Font font = new Font(FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.BLUE);
 while(rs.next()){
 //Tambahkan content sebagai Chunk
 doc.add(new Chunk(rs.getString("country")));
 doc.add(new Chunk(""));
 //Set custom Chunk
 Chunk id = new Chunk(rs.getString("id"), font);
 id.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
 id.setTextRise(6);
 doc.add(id);
 doc.add(Chunk.NEWLINE);
 }
 stmt.close();
 dbConn.close();
 //Langkah 5
 doc.close();
 }

Phrase

Merupakan sekumpulan Chunk, otomatis ada leadingnya. Default leading menggunakan perhitungan 1.5 dikali ukuran font.


public static final Font BOLD_UNDERLINED =
 new Font(FontFamily.TIMES_ROMAN, 12, Font.BOLD | Font.UNDERLINE);
public static final Font NORMAL =
 new Font(FontFamily.TIMES_ROMAN, 12);

public Phrase createDirectorPhrase(ResultSet rs) throws UnsupportedEncodingException, SQLException{
 Phrase director = new Phrase();
 director.add(new Chunk(new String(rs.getBytes("name"), "UTF-8"), BOLD_UNDERLINED));
 director.add(new Chunk(",", BOLD_UNDERLINED));
 director.add(new Chunk(" ", NORMAL));
 director.add(new Chunk(new String(rs.getBytes("given_name"), "UTF-8"), NORMAL));
 return director;
 }

public void createPDF(String fileName) throws FileNotFoundException, DocumentException, SQLException, UnsupportedEncodingException{
 //Langkah 1
 Document doc = new Document();
 //Langkah 2
 PdfWriter.getInstance(doc, new FileOutputStream(fileName));
 //Langkah 3
 doc.open();
 //Langkah 4
 DatabaseConnection dbConn = new PostgreSQLConnection();
 Statement stmt = dbConn.createStatement();
 ResultSet rs = stmt.executeQuery("SELECT name, given_name FROM film_director ORDER BY name, given_name");
 while(rs.next()){
 doc.add(createDirectorPhrase(rs));
 doc.add(Chunk.NEWLINE);
 }
 rs.close();
 stmt.close();
 dbConn.close();
 //Langkah 5
 doc.close();
 }

Paragraph

Mirip seperti Phrase, hanya saja sudah ada newline otomatis. Selain itu kita juga dapat mengatur alignment, identasi dan spasi antar Paragraph.


public Paragraph createYearAndDuration(Movie movie) {
 Paragraph info = new Paragraph();
 info.setFont(FilmFonts.NORMAL);
 info.add(new Chunk("Year: ", FilmFonts.BOLDITALIC));
 info.add(new Chunk(String.valueOf(movie.getYear()), FilmFonts.NORMAL));
 info.add(new Chunk(" Duration: ", FilmFonts.BOLDITALIC));
 info.add(new Chunk(String.valueOf(movie.getDuration()), FilmFonts.NORMAL));
 info.add(new Chunk(" minutes", FilmFonts.NORMAL));
 return info;
 }
 public void createPDF(String fileName) throws SQLException, FileNotFoundException, DocumentException, UnsupportedEncodingException{
 DatabaseConnection dbConn = new PostgreSQLConnection();
 //Langkah 1
 Document doc = new Document();
 //Langkah 2
 PdfWriter.getInstance(doc, new FileOutputStream(fileName));
 //Langkah 3
 doc.open();
 //Langkah 4
 List<Movie> movies = PojoFactory.getMovies(dbConn);
 for(Movie movie: movies){
 Paragraph title = new Paragraph(PojoToElementFactory.getMovieTitlePhrase(movie));
 title.setAlignment(Element.ALIGN_LEFT);
 doc.add(title);
 if(movie.getOriginalTitle() != null){
 Paragraph dummy = new Paragraph("\u00a0", FilmFonts.NORMAL);
 dummy.setLeading(-18);
 doc.add(dummy);
 Paragraph originalTitle = new Paragraph(PojoToElementFactory.getOriginalTitlePhrase(movie));
 originalTitle.setAlignment(Element.ALIGN_RIGHT);
 doc.add(originalTitle);
 }
 Paragraph director;
 float indent = 20;
 for(Director pojo: movie.getDirectors()){
 director = new Paragraph(PojoToElementFactory.getDirectorPhrase(pojo));
 director.setIndentationLeft(indent);
 doc.add(director);
 indent += 20;
 }
 Paragraph country;
 indent = 20;
 for(Country pojo: movie.getCountries()){
 country = new Paragraph(PojoToElementFactory.getCountryPhrase(pojo));
 country.setAlignment(Element.ALIGN_RIGHT);
 country.setIndentationRight(indent);
 doc.add(country);
 indent += 20;
 }
 Paragraph info = createYearAndDuration(movie);
 info.setAlignment(Element.ALIGN_CENTER);
 info.setSpacingAfter(36);
 doc.add(info);
 }
 dbConn.close();
 //Langkah 5
 doc.close();
 }

Kode di atas menggunakan sedikit bantuan factory untuk menyederhanakan dan juga supaya kode tersbeut bisa dipakai berulang-ulang. Selain itu juga menggunakan bean (Movie, Director dan Country).

List

Ada dua jenis yaitu ordered list dan unordered list.Untuk ordered list bisa menggunakan angka atau huruf, defaultnya adalah angka.


public void createPDF(String fileName) throws FileNotFoundException, DocumentException, SQLException, UnsupportedEncodingException{
 //Langkah 1
 Document doc = new Document();
 //Langkah 2
 PdfWriter.getInstance(doc, new FileOutputStream(fileName));
 //Langkah 3
 doc.open();
 //Langkah 4
 DatabaseConnection dbConn = new PostgreSQLConnection();
 Statement stmt = dbConn.createStatement();
 ResultSet rs = stmt.executeQuery("SELECT DISTINCT mc.country_id, c.country, count(*) AS c "
 + "FROM film_country c, film_movie_country mc "
 + "WHERE c.id = mc.country_id "
 + "GROUP BY mc.country_id, country ORDER BY c DESC");
 //Buat ordered list
 List list = new List(List.ORDERED);
 while(rs.next()){
 ListItem item = new ListItem(String.format("%s: %d movies", rs.getString("country"), rs.getInt("c")), FilmFonts.BOLDITALIC);
 //Ordered list huruf
 List movieList = new List(List.ORDERED, List.ALPHABETICAL);
 movieList.setLowercase(List.LOWERCASE);
 for(Movie movie : PojoFactory.getMovies(dbConn, rs.getString("country_id"))){
 ListItem movieItem = new ListItem(movie.getMovieTitle());
 List directorList = new List(List.UNORDERED);
 for(Director director : movie.getDirectors()){
 directorList.add(String.format("%s, %s", director.getName(), director.getGivenName()));
 }
 movieItem.add(directorList);
 movieList.add(movieItem);
 }
 item.add(movieList);
 list.add(item);
 }
 doc.add(list);
 rs.close();
 stmt.close();
 dbConn.close();
 //Langkah 5
 doc.close();
 }

String dapat langsung ditambahkan ke dalam List.


public void createPDF(String fileName) throws FileNotFoundException, DocumentException, SQLException, UnsupportedEncodingException{
 //Langkah 1
 Document doc = new Document();
 //Langkah 2
 PdfWriter.getInstance(doc, new FileOutputStream(fileName));
 //Langkah 3
 doc.open();
 //Langkah 4
 DatabaseConnection dbConn = new PostgreSQLConnection();
 Statement stmt = dbConn.createStatement();
 ResultSet rs = stmt.executeQuery("SELECT DISTINCT mc.country_id, c.country, count(*) AS c "
 + "FROM film_country c, film_movie_country mc "
 + "WHERE c.id = mc.country_id "
 + "GROUP BY mc.country_id, country ORDER BY c DESC");
 //Buat ordered list
 List list = new List(List.ORDERED);
 while(rs.next()){
 ListItem item = new ListItem(String.format("%s: %d movies", rs.getString("country"), rs.getInt("c")), FilmFonts.BOLDITALIC);
 //Custom list simbol
 item.setListSymbol(new Chunk(rs.getString("country_id")));
 //Ordered list huruf
 List movieList = new List(List.ORDERED, List.ALPHABETICAL);
 movieList.setLowercase(List.LOWERCASE);
 for(Movie movie : PojoFactory.getMovies(dbConn, rs.getString("country_id"))){
 ListItem movieItem = new ListItem(movie.getMovieTitle());
 List directorList = new List(List.ORDERED);
 directorList.setPreSymbol("Director ");
 directorList.setPostSymbol(": ");
 for(Director director : movie.getDirectors()){
 //String ditambahkan langsung ke list
 directorList.add(String.format("%s, %s", director.getName(), director.getGivenName()));
 }
 movieItem.add(directorList);
 movieList.add(movieItem);
 }
 item.add(movieList);
 list.add(item);
 }
 doc.add(list);
 rs.close();
 stmt.close();
 dbConn.close();
 //Langkah 5
 doc.close();
 }

Anchor

Pernahkah kita melihat teks di dalam dokumen PDF berbentuk link? Nah di iText cara membuatnya adalah menggunakan Anchor.


public void createPDF(String fileName) throws FileNotFoundException, DocumentException, SQLException, UnsupportedEncodingException{
 //Langkah 1
 Document doc = new Document();
 //Langkah 2
 PdfWriter.getInstance(doc, new FileOutputStream(fileName));
 //Langkah 3
 doc.open();
 //Langkah 4
 DatabaseConnection dbConn = new PostgreSQLConnection();
 Statement stmt = dbConn.createStatement();
 ResultSet rs = stmt.executeQuery("SELECT DISTINCT mc.country_id, c.country, count(*) AS c "
 + "FROM film_country c, film_movie_country mc "
 + "WHERE c.id = mc.country_id "
 + "GROUP BY mc.country_id, country ORDER BY c DESC");
 Anchor imdb;
 while(rs.next()){
 Paragraph country = new Paragraph();
 Anchor tujuan = new Anchor(rs.getString("country"), FilmFonts.BOLD);
 //Memberi nama anchor
 tujuan.setName(rs.getString("country_id"));
 country.add(tujuan);
 country.add(String.format(": %d movies", rs.getInt("c")));
 doc.add(country);
 for(Movie movie : PojoFactory.getMovies(dbConn, rs.getString("country_id"))){
 imdb = new Anchor(movie.getMovieTitle());
 imdb.setReference("http://www.itfromzerotohero.wordpress.com/");
 doc.add(imdb);
 doc.add(Chunk.NEWLINE);
 }

doc.newPage();
 }
 //Anchor ini akan kembali ke anchor dengan name=US
 Anchor toTOP = new Anchor("Kembali ke atas");
 toTOP.setReference("#US");
 doc.add(toTOP);

 rs.close();
 stmt.close();
 dbConn.close();
 //Langkah 5
 doc.close();
 }

Bisa juga menggunakan Chunk


public void createPDF(String fileName) throws FileNotFoundException, DocumentException, SQLException, UnsupportedEncodingException{
 //Langkah 1
 Document doc = new Document();
 //Langkah 2
 PdfWriter.getInstance(doc, new FileOutputStream(fileName));
 //Langkah 3
 doc.open();
 //Langkah 4
 //Buat dstination lokal untuk bagian paling atas
 Paragraph p = new Paragraph();
 Chunk top = new Chunk("Country List", FilmFonts.BOLD);
 top.setLocalDestination("top");
 p.add(top);
 doc.add(top);
 //Buat link eksternal
 Chunk imdb = new Chunk("Blog keren", FilmFonts.ITALIC);
 imdb.setAnchor("http://www.itfromzerotohero.wordpress.com/");
 p = new Paragraph("Klik di nama negara");
 p.add(imdb);
 p.add(".");
 doc.add(p);
 //Link ke dokumen PDF lain
 p = new Paragraph("Pergi ke PDF lain");
 Chunk halaman1 = new Chunk("dokumen lain");
 halaman1.setRemoteGoto("HelloWorld.pdf", 1);
 p.add(halaman1);
 p.add(".");
 doc.add(p);
 doc.add(Chunk.NEWLINE);
 DatabaseConnection dbConn = new PostgreSQLConnection();
 Statement stmt = dbConn.createStatement();
 ResultSet rs = stmt.executeQuery("SELECT DISTINCT mc.country_id, c.country, count(*) AS c "
 + "FROM film_country c, film_movie_country mc "
 + "WHERE c.id = mc.country_id "
 + "GROUP BY mc.country_id, country ORDER BY c DESC");
 while(rs.next()){
 Paragraph country = new Paragraph(rs.getString("country"), FilmFonts.BOLD);
 country.add(": ");
 Chunk link = new Chunk(String.format("%d movies", rs.getInt("c")));
 link.setRemoteGoto("SimpleAnchorOne.pdf", rs.getString("country_id"));
 country.add(link);
 doc.add(country);
 }
 doc.add(Chunk.NEWLINE);
 //Lokal goto ke top
 p = new Paragraph("Go To ");
 top = new Chunk("top");
 top.setLocalGoto("top");
 p.add(top);
 p.add(".");
 doc.add(p);

 rs.close();
 stmt.close();
 dbConn.close();
 //Langkah 5
 doc.close();
 }

  • Chunk.setLocalDestination() sama dengan Anchor.setName().
  • Chunk.setLocalGoto() sama dengan Anchor.setReference().
  • Chunk.setRemoteGoto() sama dengan Anchor.serReference() (untuk link luar) atau dapat digunakan untuk merujuk pada dokumen PDF lain.
Categories: JAVA
  1. December 23, 2012 at 10:03 am

    Hi! I just wanted to ask if you ever have any trouble with hackers?
    My last blog (wordpress) was hacked and I ended up losing
    several weeks of hard work due to no data backup. Do you have any solutions
    to protect against hackers?

  2. June 29, 2013 at 6:27 am

    Kereeennnnn !!!!!!!!!!!!!
    #TwoThumbsUp

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: