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

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 objectString dest = "coloredBorders.pdf";//PdfFont pfont=null;PdfWriter writer = new PdfWriter(dest);// Creating a PdfDocument objectPdfDocument pdfDoc = new PdfDocument(writer);// Creating a Document objectDocument 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 tablefloat[] pointColumnWidths = {200F, 200F};Table table = new Table(pointColumnWidths);// Adding row 1 to the tableCell c1 = new Cell();// Adding the contents of the cellc1.add(new Paragraph("Name").setFont(pfont));// Setting the back ground color of the cellc1.setBackgroundColor(ColorConstants.DARK_GRAY);// Instantiating the Border classBorder b1 = new DashedBorder(ColorConstants.RED, 3);// Setting the border of the cellc1.setBorder(b1);// Setting the text alignmentc1.setTextAlignment(TextAlignment.CENTER);// Adding the cell to the tabletable.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 tableCell 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 tableCell 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 documentdoc.add(table);// Closing the documentdoc.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 recognizedString 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);//2Table 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 imageimage1.scaleAbsolute(100, 100);//Add to documentdocument.add(image1);document.close();writer.close();} catch (Exception e){e.printStackTrace();}}}

调用:

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

http://www.lryc.cn/news/491642.html

相关文章:

  • 如何用通义灵码快速绘制流程图?
  • vue 预览pdf 【@sunsetglow/vue-pdf-viewer】开箱即用,无需开发
  • Java NIO 核心知识总结
  • 疑难Tips:NextCloud域名访问登录时卡住,显示违反内容安全策略
  • C 语言学习-06【指针】
  • 如何快速将Excel数据导入到SQL Server数据库
  • 【人工智能】Python在机器学习与人工智能中的应用
  • 使用八爪鱼爬虫抓取汽车网站数据,分析舆情数据
  • 什么是事务?事务有哪些特性?
  • 玩转合宙Luat教程 基础篇④——程序基础(库、线程、定时器和订阅/发布)
  • 24.<Spring博客系统①(数据库+公共代码+持久层+显示博客列表+博客详情)>
  • webp 网页如何录屏?
  • 丹摩征文活动|实现Llama3.1大模型的本地部署
  • Spring Boot 2 和 Spring Boot 3 中使用 Spring Security 的区别
  • 【数据结构与算法】 LeetCode:回溯
  • SpringBoot线程池的使用
  • Neural Magic 发布 LLM Compressor:提升大模型推理效率的新工具
  • HttpServletRequest req和前端的关系,req.getParameter详细解释,req.getParameter和前端的关系
  • React-useEffect的使用
  • MySQL数据库与Informix:能否创建同名表?
  • 爬虫实战:采集知乎XXX话题数据
  • 大数据新视界 -- Hive 数据桶原理:均匀分布数据的智慧(上)(9/ 30)
  • 【小白学机器学习33】 大数定律python的 pandas.Dataframe 和 pandas.Series基础内容
  • 【shodan】(五)网段利用
  • LeetCode739. 每日温度(2024冬季每日一题 15)
  • Node.js的http模块:创建HTTP服务器、客户端示例
  • 加菲工具 - 好用免费的在线工具集合
  • .NET9 - 新功能体验(二)
  • map和redis关系
  • 《数据结构》学习系列——图(中)