itexpdf同一个段落不同文字,如何设置不同的格式

1 Paragraph paragraphBlue = new Paragraph(“我是蓝色字体”, blueFont);
2 document.add(paragraphBlue);

 

效果如下:

但是这样整个段落只能是一个格式,如果我想让前面的字是蓝色,后面的字是红色,中间还插一张图片,这样的方法就无法做到了

后来发现,这时就用到了com.itextpdf.text.Chunk这个类了

效果如下:

代码为:

 1 import com.itextpdf.text.*;
 2 import com.itextpdf.text.pdf.BaseFont;
 3 import com.itextpdf.text.pdf.PdfWriter;
 4 
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 
 8 public class TestDemo {
 9 public static void main(String[] args) throws DocumentException, IOException {
10 //创建文件
11 Document document = new Document();
12 //建立一个书写器
13 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(“E:/test.pdf”));
14 //打开文件
15 document.open();
16 
17     //中文字体,解决中文不能显示问题
18     BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
19 
20     //蓝色字体
21     Font blueFont = new Font(bfChinese);
22     blueFont.setColor(BaseColor.BLUE);
23     //红色字体
24     Font redFont = new Font(bfChinese);
25     redFont.setColor(BaseColor.RED);
26 
27     //段落文本
28     Paragraph paragraph = new Paragraph();
29 
30     Chunk chunkBlue = new Chunk("我是蓝色字体", blueFont);
31     Chunk chunkRed = new Chunk("我是红色字体", redFont);
32 
33     paragraph.add(chunkBlue);
34     paragraph.add(chunkRed);
35 
36     document.add(paragraph);
37 
38     //关闭文档
39     document.close();
40     //关闭书写器
41     writer.close();
42 }
43 }

 

当然也可以在段落中添加图片

在这里插入图片描述

1 Image image = Image.getInstance(“E:/test.gif”);
2 Chunk chunkImage = new Chunk(image,0,0);
3 paragraph.add(chunkImage);

 

posted @ 2021-08-06 14:55  赵瑛  阅读(134)  评论(0编辑  收藏  举报

版权所有 © 2022 沅来是澧

如果有程序开发、网站建设等需求的请联系我,QQ:47419233