Java PDF: Créer une nouvelle section dans un document PDF

Author:

Java PDF:  Créer une nouvelle section dans un document PDF
{filelink=10348}

/***** Code de MesExemples.com *******/
/**
 * @(#)NewSectionPDF.java
 *
 *
 * @author 
 *sakoba(java.mesexemples.com) @version 1.00 2013/4/26
 */



import java.awt.Color;
import java.io.FileOutputStream;

import com.itextpdf.text.Chapter;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.PdfWriter;

public class NewSectionPDF {
  public static void main(String[] args) {
    Document document = new Document(PageSize.A4, 50, 50, 50, 50);
    try {
      PdfWriter pdf_writer = PdfWriter.getInstance(document, 
      	new FileOutputStream("NewSectionPagePDF.pdf"));
       // Définir la version du PDF
       pdf_writer.setPdfVersion(PdfWriter.PDF_VERSION_1_7);
       // Définir le type d'affichage
      pdf_writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
      document.open(); // Ouvrir le document PDF
      
      Font chapterFont = FontFactory.getFont(FontFactory.HELVETICA, 24);
      Font sectionFont = FontFactory.getFont(FontFactory.HELVETICA);
      Font subsectionFont = FontFactory.getFont(FontFactory.HELVETICA);
      
      // Créer deux paragraphes
      Paragraph paragraphe1 = new Paragraph("text 1");
      Paragraph paragraphe2 = new Paragraph("text 2");

      // Ajouter un chapitre dans le premier paragraphe
      Paragraph cTitle = new Paragraph("Ceci est un chapitre ", chapterFont);
      Chapter chapter = new Chapter(cTitle, 1);

      paragraphe2.setAlignment(Element.ALIGN_JUSTIFIED);
      paragraphe1.setAlignment(Element.ALIGN_JUSTIFIED);
      chapter.add(paragraphe1);
      
      // Ajouter une section dans le premier chapitre
      Paragraph sTitle = new Paragraph("Section de chapitre" , sectionFont);
      Section section = chapter.addSection(sTitle, 1);
      section.add(paragraphe1);
      section.add(Chunk.NEXTPAGE);
      
      // Créer une soussection
      Paragraph subTitle = new Paragraph("Ceci est une sous section de section 
    1", subsectionFont);
      Section subsection = section.addSection(subTitle, 3);
      
      document.add(chapter);
    } catch (Exception de) {
      de.printStackTrace();
    }
    document.close();
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *