Introdução ao jText gerando PDF

  

1. Trabalho de preparação

       Primeiro, você precisa carregar dois pacotes jar, itext-1.1.4.jar e iTextAsian.jar, dos quais iTextAsian.jar é usado para exibir caracteres chineses, japoneses e coreanos.

2. Categorias principais   

  • com.lowagie.text.Paragraph  – Esta classe representa um parágrafo recuado.
  • com.lowagie.text.Chapter  – Esta classe representa capítulos em um documento PDF.  Crie-o usando  Paragraph como título e como número do capítulo.int
  • com.lowagie.text.Font  – Esta classe contém todas as especificações de fonte, como fonte, tamanho, estilo e cor. Várias fontes são declaradas como constantes estáticas nesta classe.
  • com.lowagie.text.List  – Esta classe representa uma lista contendo muitos em ordem  ListItems.
  • com.lowagie.text.Table  – Esta classe representa uma tabela contendo células ordenadas em uma matriz.
  • SIMSUN.TTC: Dinastia Song e Nova Dinastia Song

    SIMKAI.TTF: escrita em itálico

    SIMHEI.TTF: corpo em negrito

    SIMFANG.TTF: imitação da Dinastia Song

    3. Etapas

         A saída de um arquivo PDF requer apenas 5 etapas no total:
           a. Criar uma instância de Document
           Document document = new Document( PageSize.A4, 50, 50, 50, 50 );

          O primeiro parâmetro é o tamanho da página A4. O padrão é vertical . Se for alterado para horizontal , PageSize.A4.rotate() ; Os próximos parâmetros são as margens esquerda, direita, superior e inferior .

         b. Vincule a instância Document e o fluxo de saída do arquivo usando a classe PdfWriter
         PdfWriter Writer = PdfWriter.getInstance(document,new FileOutputStream("HelloWorld.pdf"));

           Outros escritores são HtmlWriter, RtfWriter, XmlWriter, etc. Diferentes classes correspondem a diferentes formatos de arquivo ..
          c. Abra o documento
        document.open();


         d. Adicione texto, imagens, tabelas, títulos, etc. ao documento.

       1.Adicionar capítulo

       ChapterFont = FontFactory.getFont(FontFactory.HELVETICA, 18,
         com.lowagie.text.Font.NORMAL, Color.black);   // Definir tamanho e cor da fonte

        Parágrafo cTítulo = new Parágrafo("第一章", capítuloFont);
         capítulo1  = novo capítulo (cTítulo, 1);      

        document.add(chapter1);  //Novo capítulo adicional

      2.添加节

       Paragraph sTitle = new Paragraph("第一章第一节", , sectionFont);
       Section section = chapter1.addSection(sTitle, 2); 

       3.添加表格

         table = new Table(n);  //n表示有多少列

        Table table = new Table(8);
         float[] widths = { 0.10f0.15f0.21f0.22f0.08f0.08f0.10f,
                        
    0.06f };
        table.setWidths(widths);  //假设有8列,并设置每列的列宽

      table中添加cell内容,

        Cell cell = new Cell(new Phrase("内容", tableHeaderFont));// 或者   Cell cell = new Cell("内容");
        cell.setBackgroundColor(Color.gray);  //设置背景色
        cell.setHorizontalAlignment(Element.ALIGN_CENTER); //设置为居中,默认为左对齐
        table.addCell(cell);

    section.add(table); //把表加入节中

    4.添加图片

    Section subsection = section21.addSection(subTitle, 3); //节下再加新的节

    subsection.add("图表"); //给图表加个小标题

       通过URL得到图片实例:

    Image wmf = Image.getInstance(new URL("../examples/harbour.wmf"));

    Image gif = Image.getInstance(new URL("../examples/vonnegut.gif"));

    Image jpeg = Image.getInstance(new URL("../examples/myKids.jpg"));

    Image png = Image.getInstance(new URL("../examples/hitchcock.png"));

    通过文件名得到图片实例:

    Image gif = Image.getInstance("vonnegut.gif");

    Image jpeg = Image.getInstance("myKids.jpg");

    Image png = Image.getInstance("hitchcock.png"); // 在本地的完整路径也可以

     subsection.add(image);
      Paragraph endPgh = new Paragraph("\n");   //换行的作用
      endPgh.setAlignment(com.lowagie.text.Image.MIDDLE); //设置图表位置
      subsection.add(endPgh);

    5.一般的文字
     document.add(new Paragraph("Hello World"));

    6.添加页码

     HeaderFooter footer = new HeaderFooter(new Phrase("页码:",getChineseFont()), true);
                 footer.setBorder(Rectangle.NO_BORDER);
                 document.setFooter(footer);
                 document.open();

        e.关闭文档
      document.close();

     

     

     

おすすめ

転載: blog.csdn.net/linwei_hello/article/details/17142313