当前位置: 首页 > article >正文

java: itext 5.5 create pdf

/**
 * encoding: utf-8
 * 版权所有 2024 ©涂聚文有限公司
 * 许可信息查看: https://github.com/itext/itext-publications-examples-java/blob/develop/src/main/java/com/itextpdf/samples/sandbox/fonts/FreeSansBold.java
 * 描述:https://mvnrepository.com/artifact/com.itextpdf/kernel
 * # Author    : geovindu,Geovin Du 涂聚文.
 * # IDE       : IntelliJ IDEA 2023.1 Java 17
 * # Datetime  : 2024 - 2024/11/20 - 20:13
 * # User      : geovindu
 * # Product   : IntelliJ IDEA
 * # Project   : EssentialAlgorithms
 * # File      : SimpleItext.java
 * # explain   : 学习  类
 **/

package BLL;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.itextpdf.awt.geom.Point2D;
//import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.Element.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.font.*;
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.kernel.pdf.canvas.draw.*;
import com.itextpdf.text.pdf.PdfEncodings;
//import static com.itextpdf.kernel.pdf.PdfName.BaseFont;
import com.itextpdf.text.io.*;
//import com.itextpdf.io.font.PdfEncodings.*;
//import com.itextpdf.layout.Document;
//import com.itextpdf.layout.element.Paragraph;
//import com.itextpdf.layout.element.Text;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.fonts.*;

import java.util.List;
import java.util.ArrayList;

import Model.Orders;






public class SimpleItext {

    private static String USER_PASSWORD = "geovindu";
    private static String OWNER_PASSWORD = "geovindu";

   
    public void Createpdf()
   {
      Document document = new Document();
      try
      {
          PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("itextExample.pdf"));
          //设置打开文档必码
         // writer.setEncryption(USER_PASSWORD.getBytes(),
                  //OWNER_PASSWORD.getBytes(), PdfWriter.ALLOW_PRINTING,
                  //PdfWriter.ENCRYPTION_AES_128);
          String fontFile2 = "font\\MHeiHK-Light.TTF";
          //BaseFont FSChinese = BaseFont.createFont(fontFile2,BaseFont.is,BaseFont.NOT_EMBEDDED);//这是设置仿宋基本字体


          String path = "C:/WINDOWS/Fonts/simhei.ttf";//windows里的字体资源路径
          BaseFont bf = BaseFont.createFont(fontFile2, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
          Font font = new Font(bf, 10f, Font.NORMAL, BaseColor.BLACK);

          //PdfFont f2 = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H");
         // PdfFont pfont = PdfFontFactory.createFont(fontFile2, PdfEncodings.IDENTITY_H);//PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED
         // PdfFont pfont2= PdfFontFactory.createRegisteredFont(fontFile2, PdfEncodings.IDENTITY_H);

          //Font text=new Font(font,16,Font.NORMAL);//这里设置字体大小和粗细

          //PdfFont f = PdfFontFactory.createFont(fontFile2, PdfEncodings.IDENTITY_H);
          //Paragraph p = new Paragraph("H\u2082SO\u2074").setFont(f).setFontSize(10);

          document.open();
          //document.setFont(pfont);
          document.open();
          document.add(new Paragraph("Some content here",font));

          //Set attributes here
          document.addAuthor("Geovin Du 涂聚文");
          document.addCreationDate();
          document.addCreator("dusystem.com");
          document.addTitle("Set Attribute Example");
          document.addSubject("An example to show how attributes can be added to pdf files.");
          PdfPTable table = new PdfPTable(3); // 3 columns.
          table.setWidthPercentage(100); //Width 100%
          table.setSpacingBefore(10f); //Space before table
          table.setSpacingAfter(10f); //Space after table


          //Set Column widths
          float[] columnWidths = {1f, 1f, 1f};
          table.setWidths(columnWidths);

          PdfPCell cell1 = new PdfPCell(new Paragraph("深圳市",font));
          cell1.setBorderColor(BaseColor.BLUE);
          cell1.setPaddingLeft(10);
          cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
          cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);

          PdfPCell cell2 = new PdfPCell(new Paragraph("南山區",font));
          cell2.setBorderColor(BaseColor.GREEN);
          cell2.setPaddingLeft(10);
          cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
          cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);

          PdfPCell cell3 = new PdfPCell(new Paragraph("科技園",font));
          cell3.setBorderColor(BaseColor.RED);
          cell3.setPaddingLeft(10);
          cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
          cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);

          //To avoid having the cell border and the content overlap, if you are having thick cell borders
          //cell1.setUserBorderPadding(true);
          //cell2.setUserBorderPadding(true);
          //cell3.setUserBorderPadding(true);
          List<Orders> orders = new ArrayList<>();
          Orders order = new Orders();
          order.setProductId(1); ;
          order.setProduct("中國電器");
          order.setQty(50);
          order.setPrice(52.0);
          orders.add(order);

          order = new Orders();
          order.setProductId(2);
          order.setProduct ("日本電器");
          order.setQty(150);
          order.setPrice(252.0);
          orders.add(order);


          table.addCell(cell1);
          table.addCell(cell2);
          table.addCell(cell3);

          document.add(table);

          table = new PdfPTable(new float[] { 2, 1, 2 });
          table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
          table.addCell(new Paragraph("產品ID",font));
          table.addCell(new Paragraph("名稱",font));
          table.addCell(new Paragraph("書量",font));
          table.setHeaderRows(1);
          PdfPCell[] cells = table.getRow(0).getCells();
          for (int j=0;j<cells.length;j++){
              cells[j].setBackgroundColor(BaseColor.GRAY);
          }
          for (Orders s:orders){
              table.addCell(String.valueOf(s.getProductId()));
              table.addCell(new Paragraph(s.getProduct(),font));
              table.addCell(String.valueOf(s.getQty()));
        }

          document.add(table);

          //Add Image
          Image image1 = Image.getInstance("geovindu.jpg");
          //Fixed Positioning
          image1.setAbsolutePosition(205f, 150f);
          //Scale to new height and new width of image
          image1.scaleAbsolute(100, 100);
          //Add to document
          document.add(image1);


          document.close();
          writer.close();

      } catch (Exception e)
      {
          e.printStackTrace();
      }

  }
 

}

/**
 * encoding: utf-8
 * 版权所有 2024 ©涂聚文有限公司
 * 许可信息查看:
 * 描述:
 * # Author    : geovindu,Geovin Du 涂聚文.
 * # IDE       : IntelliJ IDEA 2023.1 Java 17
 * # Datetime  : 2024 - 2024/11/20 - 20:57
 * # User      : geovindu
 * # Product   : IntelliJ IDEA
 * # Project   : EssentialAlgorithms
 * # File      : Orders.java
 * # explain   : 学习  类
 **/

package Model;

/**
 * 订单实体类
 */
public class Orders
{


    private int productId;

    private String product;

    private int qty;
    private double price;


    /**
     * id
     * @return
     */
    public int getProductId() { return productId; }

    /**
     *
     * @param proudctid
     */
    public void setProductId(int proudctid)
    {
        this.productId=proudctid;
    }

    /**
     * 产品名称
     * @return
     */
    public String getProduct() { return product; }

    /**
     *
     * @param proudct
     */
    public void setProduct(String proudct)
    {
        this.product=proudct;
    }


    /**
     * 数量
     * @return
     */
    public int getQty() { return qty; }

    /**
     *
     * @param qt
     */
    public void setQty(int qt)
    {
        this.qty=qt;
    }

    /**
     * 价格
     * @return
     */
    public double getPrice() { return price; }

    /**
     *
     * @param pric
     */
    public void setPrice(double pric)
    {
        this.price=pric;
    }
}

调用:

      //
        SimpleItext itextpdf=new SimpleItext();
        itextpdf.Createpdf();


http://www.kler.cn/a/408177.html

相关文章:

  • HarmonyOs鸿蒙开发实战(20)=>一文学会基础使用组件导航Navigation
  • 聊聊主流几个JDK版本:JDK 8、JDK 11、JDK 17 和 JDK 21 的区别
  • 如何在 UniApp 中实现 iOS 版本更新检测
  • app小程序web安全—sign签名绕过
  • NFS搭建
  • 修改一下达梦disql 提示符
  • HBU算法设计与分析 贪心算法
  • springboot实战(16)(Validation参数校验冲突问题、分组校验、默认分组)
  • opencv进行rtsp推流
  • Python 将彩色视频转换为黑白视频(MP4-格式可选)
  • luckfox_pico_yolov5
  • AT_abc380
  • 游戏引擎学习第22天
  • Midjourney以图生图攻略,6个案例以学代练
  • 图文检索(27):Generalising Fine-Grained Sketch-Based Image Retrieval
  • (四)3D视觉机器人的手眼标定(眼在手外)
  • 16. 清理Python包管理工具(pip 和 conda)的缓存和冗余文件
  • 2024年 数模美赛 D题 湖流网络水位控制
  • Qt如何屏蔽工具栏(QToolBar)自动折叠功能
  • 嵌入式软件工程师岗位细分全景图
  • 嵌入式开发工程师面试题 - 2024/11/24
  • MATLAB的addpath和rmpath函数增加或删除路径
  • flink学习(6)——自定义source和kafka
  • CCF认证202406-02 | 矩阵重塑(其二)
  • 计算机网络socket编程(6)_TCP实网络编程现 Command_server
  • node报错:cb.apply is not a function