Java使用itexpdf生成PDF,正常情況下,新建一個段落Paragraph,然后可以給段落添加一個格式BaseFont
Paragraph paragraphBlue = new Paragraph("我是藍色字體", blueFont); document.add(paragraphBlue);
效果如下:
但是這樣整個段落只能是一個格式,如果我想讓前面的字是藍色,后面的字是紅色,中間還插一張圖片,這樣的方法就無法做到了
后來發現,這時就用到了com.itextpdf.text.Chunk這個類了
效果如下:
代碼為:
import com.itextpdf.text.*; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfWriter; import java.io.FileOutputStream; import java.io.IOException; public class TestDemo { public static void main(String[] args) throws DocumentException, IOException { //創建文件 Document document = new Document(); //建立一個書寫器 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E:/test.pdf")); //打開文件 document.open(); //中文字體,解決中文不能顯示問題 BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); //藍色字體 Font blueFont = new Font(bfChinese); blueFont.setColor(BaseColor.BLUE); //紅色字體 Font redFont = new Font(bfChinese); redFont.setColor(BaseColor.RED); //段落文本 Paragraph paragraph = new Paragraph(); Chunk chunkBlue = new Chunk("我是藍色字體", blueFont); Chunk chunkRed = new Chunk("我是紅色字體", redFont); paragraph.add(chunkBlue); paragraph.add(chunkRed); document.add(paragraph); //關閉文檔 document.close(); //關閉書寫器 writer.close(); } }
當然也可以在段落中添加圖片
Image image = Image.getInstance("E:/test.gif"); Chunk chunkImage = new Chunk(image,0,0); paragraph.add(chunkImage);