PDF图片生成例程

本文提供了一个使用Java生成包含文字、图片及表格等元素的PDF文件的示例代码。介绍了如何设置字体以支持中文显示,并展示了如何添加表格及图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文通过一个简单的PDF文件生成例子,期望可以起到抛砖引玉的作用! :)

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;

public class TestPdf {
  public static void main(String[] args) {
    //创建一个文档对象
    Document doc = new Document();
    try {
      //定义输出位置并把文档对象装入输出对象中
      PdfWriter.getInstance(doc, new FileOutputStream("c:/hello.pdf"));
      //打开文档对象
      doc.open();
      // 加入文字“Hello World”
      doc.add(new Paragraph("HelloWorld"));

      BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
                                               BaseFont.NOT_EMBEDDED);
      Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
      // 在上面的代码中设置了中文字体的显示,你只要使用下面的代码就可以包中文加到PDF中了
      String title = "我爱喝咖啡";
      Paragraph t = new Paragraph(title, FontChinese);
      doc.add(t);

      Image jpeg = Image.getInstance("C:/girl.jpg");
      //图片居中
      jpeg.setAlignment(Image.ALIGN_CENTER);
      doc.add(jpeg);

      Table table = new Table(2);
      //设置表格边框
      table.setBorderWidth(1);
      table.setPadding(5);
      table.setBorderColor(new java.awt.Color(0, 0, 255));
      table.setBackgroundColor(new java.awt.Color(0, 100, 100));

      Cell cel0 = new Cell("Title");
      cel0.setHorizontalAlignment(1); //0:left ,1:center ,2:right
      cel0.setColspan(2);
      cel0.setHeader(true);
      table.endHeaders();

      Cell cel1 = new Cell("aaaaaaaa");

      Cell cel2 = new Cell("bbbbbbb");
      cel2.setHorizontalAlignment(1); //0:left ,1:center ,2:right
      //分列
      Cell cel3 = new Cell("cccccc");
      cel3.setColspan(2);

      Cell cel4 = new Cell("dddd");
      Cell cel5 = new Cell(t);

      table.addCell(cel0);
      table.addCell(cel1);
      table.addCell(cel2);
      table.addCell(cel3);
      table.addCell(cel4);
      table.addCell("");
      table.addCell("");
      table.addCell(cel5);
      doc.add(table);
      doc.close();
    }
    catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    catch (DocumentException e) {
      e.printStackTrace();
    }
    catch (Exception e) {}
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值