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

java: itext8.05 create pdf

只能调用windows 已安装的字体,这样可以在系统中先预装字体,5.0 可以调用自配文件夹的字体文件。CSharp donetItext8.0 可以调用。

/**
 * 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  itext8.05
 * # File      : SimpleItext.java
 * # explain   : 学习  类
 **/

package BLL;

//import java.awt.*;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.io.font.TrueTypeFont;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.colors.Color;
import com.itextpdf.kernel.colors.*;
import com.itextpdf.kernel.colors.gradients.*;
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.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.io.font.FontProgramFactory;
import com.itextpdf.layout.element.*;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.borders.Border;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.UnitValue;
import com.itextpdf.layout.properties.VerticalAlignment;
import com.itextpdf.layout.properties.HorizontalAlignment;
import com.itextpdf.layout.element.Text;
import com.itextpdf.layout.borders.*;
import com.itextpdf.layout.borders.SolidBorder;
import com.itextpdf.io.util.StreamUtil;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;


import java.io.File;
import java.util.HashSet;
import java.util.Set;
import java.io.FileInputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

import Model.Orders;


public class SimpleItext {

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

    public static final String FONTDIR = "font/";
    public void test()
    {
        try {

            String fontFile2 = "font/MHeiHK-Light.TTF";
            String path = "C:/WINDOWS/Fonts/simhei.ttf";//windows里的字体资源路径

            String getfont="";

            // Creating a PdfWriter object
            String dest = "coloredBorders.pdf";

            //PdfFont pfont=null;

            PdfWriter writer = new PdfWriter(dest);

            // Creating a PdfDocument object
            PdfDocument pdfDoc = new PdfDocument(writer);

            // Creating a Document object
            Document doc = new Document(pdfDoc);

            PdfFontFactory.registerDirectory(FONTDIR);
            byte[] bytes;
            FileInputStream myflie = new FileInputStream(fontFile2);
            //var is = getClass().getResourceAsStream(fontFile2);
            bytes = StreamUtil.inputStreamToArray(myflie);
            //byte[] tem = new byte[myflie.available()];//创建一个长度为myflie长的竹筒
            //myflie.read(tem);
            //var pfont = FontProgramFactory.createFont(bytes);

            //PdfFont pfont = PdfFontFactory.createFont(bytes, PdfEncodings.UTF8);
            /*
            Set<String> fonts = new HashSet<String>(FontProgramFactory.getRegisteredFonts());
            for (String fontname : fonts) {
                System.out.print(fontname);
                getfont=fontname;
                pfont = PdfFontFactory.createRegisteredFont(getfont, PdfEncodings.IDENTITY_H);
                doc.add(new Paragraph(String.format("Postscript name for %s: %s", getfont,
                        pfont.getFontProgram().getFontNames().getFontName())));
            }
            */
            //PdfFont f2 = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H");
            PdfFont  pfont = PdfFontFactory.createFont(path, PdfEncodings.IDENTITY_H);//PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED



            // Creating a table
            float[] pointColumnWidths = {200F, 200F};
            Table table = new Table(pointColumnWidths);

            // Adding row 1 to the table
            Cell c1 = new Cell();

            // Adding the contents of the cell
            c1.add(new Paragraph("Name").setFont(pfont));

            // Setting the back ground color of the cell
            c1.setBackgroundColor(ColorConstants.DARK_GRAY);

            // Instantiating the Border class
            Border b1 = new DashedBorder(ColorConstants.RED, 3);

            // Setting the border of the cell
            c1.setBorder(b1);

            // Setting the text alignment
            c1.setTextAlignment(TextAlignment.CENTER);

            // Adding the cell to the table
            table.addCell(c1);
            Cell c2 = new Cell();
            c2.add(new Paragraph("涂聚文").setFont(pfont));
            c1.setBorder(new SolidBorder(ColorConstants.RED, 3));
            c2.setTextAlignment(TextAlignment.CENTER);
            table.addCell(c2);

            // Adding row 2 to the table
            Cell c3 = new Cell();
            c3.add(new Paragraph("Id").setFont(pfont));
            c3.setBorder(new DottedBorder(ColorConstants.DARK_GRAY, 3));
            c3.setTextAlignment(TextAlignment.CENTER);
            table.addCell(c3);

            Cell c4 = new Cell();
            c4.add(new Paragraph("001").setFont(pfont));
            c4.setBorder(new DoubleBorder(ColorConstants.DARK_GRAY, 3));
            c4.setTextAlignment(TextAlignment.CENTER);
            table.addCell(c4);

            // Adding row 3 to the table
            Cell c5 = new Cell();
            c5.add(new Paragraph("Designation").setFont(pfont));
            c5.setBorder(new RoundDotsBorder(ColorConstants.RED, 3));
            c5.setTextAlignment(TextAlignment.CENTER);
            table.addCell(c5);

            Cell c6 = new Cell();
            c6.add(new Paragraph("Programmer").setFont(pfont));
            c6.setBorder(new RoundDotsBorder(ColorConstants.RED, 3));
            c6.setTextAlignment(TextAlignment.CENTER);
            table.addCell(c6);

            // Adding Table to document
            doc.add(table);

            // Closing the document
            doc.close();

            System.out.println("Borders added successfully..");
        }
        catch(IOException oex)
        {
            oex.printStackTrace();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }


    }




    public void Createpdf()
   {

      try
      {
          String dem="itextExample.pdf";
          PdfWriter writer =new PdfWriter(dem);
          //设置打开文档必码
         // writer.setEncryption(USER_PASSWORD.getBytes(),
                  //OWNER_PASSWORD.getBytes(), PdfWriter.ALLOW_PRINTING,
                  //PdfWriter.ENCRYPTION_AES_128);
          String fontFile2 = "font\\MHeiHK-Light.TTF";    // 这个报错: Type of font is not recognized
          String path = "C:/WINDOWS/Fonts/simhei.ttf";//windows里的字体资源路径

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

          PdfDocument pdfDoc = new PdfDocument(writer);

          Document document = new Document(pdfDoc);

          //document.setFont(pfont);
          //document.open();

          document.add(new Paragraph("Some content here").setFont(pfont).setFontColor(ColorConstants.RED));

          //Set attributes here
          //document.("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.");
          Table table = new Table(3,true); // 3 columns.
          //table.setHeight(100); //Width 100%
          //table.setHeight(10f); //Space before table
          //table.setSpacingAfter(10f); //Space after table


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

          Cell cell1 = new Cell().add(new Paragraph("深圳市").setFont(pfont));
          cell1.setBorder(new SolidBorder(ColorConstants.BLACK, 1));
          cell1.setPaddingLeft(10);
          cell1.setHorizontalAlignment(HorizontalAlignment.CENTER);
          cell1.setVerticalAlignment(VerticalAlignment.MIDDLE);

          Cell cell2 = new Cell().add(new Paragraph("南山區").setFont(pfont).setFontColor(ColorConstants.GREEN));
          cell2.setBorder(new SolidBorder(ColorConstants.BLACK, 1));
          cell2.setPaddingLeft(10);
          cell2.setHorizontalAlignment(HorizontalAlignment.LEFT);
          cell2.setVerticalAlignment(VerticalAlignment.MIDDLE);
           //.setVerticalAlignment(VerticalAlignment.MIDDLE)
          Cell cell3 = new Cell().add(new Paragraph("科技園").setFont(pfont));
          cell3.setBackgroundColor(ColorConstants.RED);
          cell3.setPaddingLeft(10);
          cell3.setHorizontalAlignment(HorizontalAlignment.CENTER);
          cell3.setVerticalAlignment(VerticalAlignment.MIDDLE);


          table.addCell(cell1);
          table.addCell(cell2);
          table.addCell(cell3);
         // table.complete();
          document.add(table);

          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);
          //2

          Table tableData = new Table(5, true);
          tableData.setBorder(new SolidBorder(ColorConstants.BLACK, 1));
          tableData.setFont(pfont);
          Cell headerProductId = new Cell(1, 1).setTextAlignment(TextAlignment.LEFT).add(new Paragraph("ID"));
          Cell headerProduct = new Cell(1, 1).setTextAlignment(TextAlignment.LEFT).add(new Paragraph("產品名稱"));
          Cell headerProductPrice = new Cell(1, 1).setTextAlignment(TextAlignment.LEFT).add(new Paragraph("價格"));
          Cell headerProductQty = new Cell(1, 1).setTextAlignment(TextAlignment.LEFT).add(new Paragraph("數量"));
          Cell headerTotal = new Cell(1, 1).setTextAlignment(TextAlignment.LEFT).add(new Paragraph("合計"));

          tableData.addCell(headerProductId);
          tableData.addCell(headerProduct);
          tableData.addCell(headerProductPrice);
          tableData.addCell(headerProductQty);
          tableData.addCell(headerTotal);

          double grandTotalVal = 0;
          for(Orders c:orders)
          {
              Cell productid = new Cell(1, 1).setTextAlignment(TextAlignment.LEFT).add(new Paragraph(String.valueOf(c.getProductId())));
              Cell product = new Cell(1, 1).setTextAlignment(TextAlignment.LEFT).add(new Paragraph(c.getProduct()));
              Cell price = new Cell(1, 1).setTextAlignment(TextAlignment.LEFT).add(new Paragraph(String.valueOf(c.getPrice())));
              Cell qty = new Cell(1, 1).setTextAlignment(TextAlignment.LEFT).add(new Paragraph(String.valueOf(c.getQty())));
              var value = c.getPrice() * c.getQty();
              Cell total = new Cell(1, 1).setTextAlignment(TextAlignment.LEFT).add(new Paragraph(String.valueOf(value)));

              grandTotalVal += value;
              tableData.addCell(productid);
              tableData.addCell(product);
              tableData.addCell(price);
              tableData.addCell(qty);
              tableData.addCell(total);
          }

          Cell grandTotalHeader = new Cell(1, 4).setTextAlignment(TextAlignment.RIGHT).add(new Paragraph("合計: ")).setBorderBottom(new SolidBorder(ColorConstants.BLACK, 1));
          Cell grandTotal = new Cell(1, 1).setTextAlignment(TextAlignment.LEFT).add(new Paragraph(" " + String.valueOf(grandTotalVal))).setBorderBottom(new SolidBorder(ColorConstants.BLACK, 1));
          grandTotal.setBorderBottom(new SolidBorder(ColorConstants.BLACK, 1));
          tableData.addCell(grandTotalHeader);
          tableData.addCell(grandTotal);

          //tableData.complete();
          document.add(tableData);



          Table tablebottom = new Table(4,true);
          //tablebottom.setBorder(new SolidBorder(ColorConstants.BLACK, 3));
          tablebottom.setHorizontalAlignment(HorizontalAlignment.CENTER);
          tablebottom.addCell(new Cell().add(new Paragraph("產品ID").setFont(pfont)).setBorderTop(new SolidBorder(ColorConstants.BLACK, 3)));
          tablebottom.addCell(new Cell().add(new Paragraph("名稱").setFont(pfont)).setBorderTop(new SolidBorder(ColorConstants.BLACK, 3)));
          tablebottom.addCell(new Cell().add(new Paragraph("書量").setFont(pfont)).setBorderTop(new SolidBorder(ColorConstants.BLACK, 3)));
          tablebottom.addCell(new Cell().add(new Paragraph("價格").setFont(pfont)).setBorderTop(new SolidBorder(ColorConstants.BLACK, 3)));
          //table.setHeaderRows(1);
          //Cell[] cells = table.getCell(2,3);
          //for (int j=0;j<cells.length;j++){
              //cells[j].setBackgroundColor(ColorConstants.BLACK);
          //}
          for (Orders s:orders){
              Cell cel1= new Cell().add(new Paragraph(String.valueOf(s.getProductId()))).setBorder(new SolidBorder(ColorConstants.BLACK, 3));
              cel1.setTextAlignment(TextAlignment.CENTER);
              tablebottom.addCell(cel1);
              Cell cel2=new Cell().add(new Paragraph(s.getProduct()).setFont(pfont)).setBorder(new SolidBorder(ColorConstants.BLACK, 3));
              cel2.setTextAlignment(TextAlignment.CENTER);
              tablebottom.addCell(cel2);
              Cell cel3=new Cell().add(new Paragraph(String.valueOf(s.getQty()))).setBorder(new SolidBorder(ColorConstants.BLACK, 3));
              cel3.setTextAlignment(TextAlignment.CENTER);
              tablebottom.addCell(cel3);
              Cell cel4=new Cell().add(new Paragraph(String.valueOf(s.getPrice()))).setBorder(new SolidBorder(ColorConstants.BLACK, 3));
              cel4.setTextAlignment(TextAlignment.CENTER);
              tablebottom.addCell(cel4);

        }

          Cell cel1= new Cell().add(new Paragraph("3").setBorderBottom(new SolidBorder(ColorConstants.BLACK, 3)));
          cel1.setTextAlignment(TextAlignment.CENTER);
          tablebottom.addCell(cel1);
          Cell cel2=new Cell().add(new Paragraph("涂聚文").setFont(pfont).setBorderBottom(new SolidBorder(ColorConstants.BLACK, 3)).setBorderLeft(new SolidBorder(ColorConstants.BLACK, 3)));
          cel2.setTextAlignment(TextAlignment.CENTER);
          tablebottom.addCell(cel2);
          Cell cel3=new Cell().add(new Paragraph("333").setBorderBottom(new SolidBorder(ColorConstants.BLACK, 3)).setBorderLeft(new SolidBorder(ColorConstants.BLACK, 3)));
          cel3.setTextAlignment(TextAlignment.CENTER);
          tablebottom.addCell(cel3);
          Cell cel4=new Cell().add(new Paragraph("3333").setBorderBottom(new SolidBorder(ColorConstants.BLACK, 3)).setBorderLeft(new SolidBorder(ColorConstants.BLACK, 3)));
          cel4.setTextAlignment(TextAlignment.CENTER);
          tablebottom.addCell(cel4);

          document.add(tablebottom);

          ImageData imageData = ImageDataFactory.create("geovindu.jpg");
          Image image1 = new Image(imageData);
          //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();
      }

  }


}

调用:

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


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

相关文章:

  • 数据可视化复习2-绘制折线图+条形图(叠加条形图,并列条形图,水平条形图)+ 饼状图 + 直方图
  • 冒泡排序(Java)
  • 【大数据学习 | Spark-Core】Spark提交及运行流程
  • Springboot项目添加拦截器
  • 【FPGA-MicroBlaze】串口收发以及相关函数讲解
  • 解决Dcat Admin laravel框架登录报错问题,(blocked:mixed-content)
  • 初始Python篇(7)—— 正则表达式
  • 【Y20030005】Java+JSP+MySQL+Servlet的网络购物商城的设计与实现
  • RK3588适配MTK7921 USB接口WiFi驱动开发
  • mini-lsm通关笔记Week2Day5
  • 扩散模型中IGSO(3)分布PDF的近似表示
  • 鸿蒙学习高效开发与测试-集成开发环境(4)
  • 网络安全,文明上网(4)掌握网络安全技术
  • 代码随想录算法训练营第五十三天|Day53 图论
  • AIVA 技术浅析(四):捕捉音乐作品中的长期依赖关系
  • C#构建一个简单的循环神经网络,模拟对话
  • 【代码pycharm】动手学深度学习v2-07 自动求导
  • C语言-详细讲解-P1217 [USACO1.5] 回文质数 Prime Palindromes
  • 【C++】list模拟实现(详解)
  • css:感觉稍微高级一点的布局
  • SpringBoot社团管理:安全与维护
  • 【系统架构设计师】真题论文: 论软件需求管理(包括解题思路和素材)
  • Redis 常用数据类型插入性能对比:循环插入 vs. 批量插入
  • 自主导航:机器人如何在复杂环境中找到自己的路?
  • 小程序免备案:快速部署与优化的全攻略
  • Java 查询最大最小值 详解