日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

itext7相关使用

發布時間:2023/12/14 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 itext7相关使用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

itext7相關使用

  • 1 itext7的簡介
  • 2 itext7的使用
      • 1 添加相關maven坐標
      • 2 itext7相關語法說明
        • 1 PDF生成案例
        • 2 圖片相關語法
        • 3 添加空白頁
        • 4 Div和Paragraph
        • 5 換行/空格/換頁
        • 6 Html轉換為Pdf
        • 7 關于PDF上簽章功能

最近有使用到itext7相關技術,生成pdf文件,添加電子簽章等功能.

1 itext7的簡介

iText 7是基于iText 5的一款工具. 其中所有主類和接口的完整版本,都更合乎邏輯,盡可能保持與iText 5的兼容, 一個全新的布局模塊,它超越了iText 5,優化添加了很多高級布局功能.

itext7中的語法, 其中一些命名等和前端的語法相似. 如其中的div,table等語法糖.

2 itext7的使用

1 添加相關maven坐標

<!-- itext7 全家桶 --><dependency><groupId>com.itextpdf</groupId><artifactId>itext7-core</artifactId><version>7.1.12</version><type>pom</type></dependency><!--itext7 html轉pdf用到的包--><dependency><groupId>com.itextpdf</groupId><artifactId>html2pdf</artifactId><version>3.0.0</version></dependency>

2 itext7相關語法說明

1 PDF生成案例

public class PdfDemo { // 生產的pdf文件路徑public static final String DEST = "D:\\demo.pdf";// 字體public static final String FONT = "ttf/方正小篆體.ttf";public Document getDocument(){ PdfDocument pdfDocument;Document document;PdfFont font ;try{pdfDocument = new PdfDocument(new PdfWriter(DEST));// 項目指定字體, 通過類加載項目字體資源font = font = PdfFontFactory.createFont(IOUtils.toByteArray(PdfDemo.class.getClassLoader().getResourceAsStream(FONT)), PdfEncodings.IDENTITY_H, false);;document = new Document(pdfDocument)document.setFont(font);return document;}catch(Exception e){e.printStackTrace();}} }

從案例可以, 生成Document對象的步驟.接下來,一步一步看Document對象創建的過程

com.itextpdf.layout.Document類部分源碼:

/*** Document is the default root element when creating a self-sufficient PDF. It* mainly operates high-level operations e.g. setting page size and rotation,* adding elements, and writing text at specific coordinates. It has no* knowledge of the actual PDF concepts and syntax.* <p>* A {@link Document}'s rendering behavior can be modified by extending* {@link DocumentRenderer} and setting an instance of this newly created with* {@link #setRenderer(com.itextpdf.layout.renderer.DocumentRenderer) }.*/ // Document文檔是創建自定義PDF時的默認根元素 // 它主要操作高級操作,例如設置頁面大小和旋轉,添加元素,并在特定坐標處寫入文本 public class Document extends RootElement<Document> {/*** Creates a document from a {@link PdfDocument}. Initializes the first page* with the {@link PdfDocument}'s current default {@link PageSize}.** @param pdfDoc the in-memory representation of the PDF document*/// 常用構造方法 使用PdfDocument對象public Document(PdfDocument pdfDoc) {this(pdfDoc, pdfDoc.getDefaultPageSize());}@Overridepublic Document add(IBlockElement element) {checkClosingStatus();super.add(element);if (element instanceof ILargeElement) {((ILargeElement) element).setDocument(this);((ILargeElement) element).flushContent();}return this;}/*** Sets the font of this Element.* <p>* This property overrides the value set by {@link #setFontFamily}. Font is set either via exact {@link PdfFont}* instance or via font-family name that should correspond to the font in {@link FontProvider}, but not both.* @param font a {@link PdfFont font}* @return this Element.*/// 設置元素的字體public T setFont(PdfFont font) {setProperty(Property.FONT, font);return (T) (Object) this;}}

com.itextpdf.kernel.pdf.PdfDocument類部分源碼:

/*** Main enter point to work with PDF document.*/ // 使用PDF文檔的主輸入點 public class PdfDocument implements IEventDispatcher, Closeable, Serializable {/*** Open PDF document in writing mode.* Document has no pages when initialized.** @param writer PDF writer*/// 以編寫模式打開PDF文檔 ,文檔初始化時沒有頁面 public PdfDocument(PdfWriter writer) {this(writer, new DocumentProperties());}}

com.itextpdf.kernel.pdf.PdfWriter類部分源碼:

/*** Create a PdfWriter writing to the passed filename and with default writer properties.** @param filename filename of the resulting pdf.* @throws FileNotFoundException*/// 創建一個PdfWriter,將其寫入傳遞的文件名并具有默認的writer屬性public PdfWriter(String filename) throws FileNotFoundException {this(filename, new WriterProperties());}

2 圖片相關語法

其中主要是創建com.itextpdf.io.image.ImageData對象來獲取圖片源,通過其工廠類com.itextpdf.io.image.ImageDataFactory來創建對象.

// 得到需要插入的圖片 常使用兩種方式獲取: 即 url 和 filenameImageData imageData = ImageDataFactory.create("C:\\Pdf圖片.png");// 得到填充PDF的Image對象, 可以設置圖片的各種參數Image image = new Image(imageData)// 設置寬高擴大縮小image.scale(1, 1.05f);// 將圖像縮放到絕對大小image.scaleAbsolute(80, 80);// 設置邊距image.setMargins(-50, -60, -60, -60);

ImageDataFactory工廠類部分源碼:

/*** Create an ImageData instance representing the image from the file located at the specified url.* @param url location of the image* @return The created ImageData object.*/public static ImageData create(URL url) {return create(url, false);}/*** Create an ImageData instance representing the image from the specified file.* @param filename filename of the file containing the image* @param recoverImage whether to recover from a image error (for TIFF-images)* @return The created ImageData object.* @throws MalformedURLException*/public static ImageData create(String filename, boolean recoverImage) throws MalformedURLException {return create(UrlUtil.toURL(filename), recoverImage);}/*** Create an ImageData instance representing the image from the specified file.* @param filename filename of the file containing the image* @return The created ImageData object.* @throws MalformedURLException*/public static ImageData create(String filename) throws MalformedURLException {return create(filename, false);}

Image類部分源碼:

/*** Creates an {@link Image} from an image resource, read in from a file* with the iText I/O module.** @param img an internal representation of the {@link com.itextpdf.io.image.ImageData image resource}*/public Image(ImageData img) {this(new PdfImageXObject(checkImageType(img)));setProperty(Property.FLUSH_ON_DRAW, true);}/*** Scale the image to an absolute size. This method will <em>not</em>* preserve the width-height ratio of the image.** @param fitWidth the new absolute width of the image* @param fitHeight the new absolute height of the image* @return this element*/public Image scaleAbsolute(float fitWidth, float fitHeight) {float horizontalScaling = fitWidth / xObject.getWidth();float verticalScaling = fitHeight / xObject.getHeight();return scale(horizontalScaling, verticalScaling);}/*** Sets the margins around the image to a series of new widths.** @param marginTop the new margin top width* @param marginRight the new margin right width* @param marginBottom the new margin bottom width* @param marginLeft the new margin left width* @return this image*/public Image setMargins(float marginTop, float marginRight, float marginBottom, float marginLeft) {return setMarginTop(marginTop).setMarginRight(marginRight).setMarginBottom(marginBottom).setMarginLeft(marginLeft);}/*** Scale the image relative to its default size.** @param horizontalScaling the horizontal scaling coefficient. default value 1 = 100%* @param verticalScaling the vertical scaling coefficient. default value 1 = 100%* @return this element*/public Image scale(float horizontalScaling, float verticalScaling) {setProperty(Property.HORIZONTAL_SCALING, horizontalScaling);setProperty(Property.VERTICAL_SCALING, verticalScaling);return this;}

3 添加空白頁

添加第2頁為空白頁,立即刷新后再繼續添加

pdfDocument.addNewPage(2).flush();

4 Div和Paragraph

// 塊狀Div div = new Div();// 設置寬度div.setWidth(UnitValue.createPercentValue(100));// 設置高度div.setHeight(UnitValue.createPercentValue(100));// 設置此元素的水平對齊方式div.setHorizontalAlignment(HorizontalAlignment.CENTER);// 添加段落Paragraph paragraph = new Paragraph("PDF內容");// 設置此元素的水平對齊方式paragraph.setHorizontalAlignment(HorizontalAlignment.CENTER);// 設置此元素的最寬長度paragraph.setMaxWidth(UnitValue.createPercentValue(75));// 設置元素的上邊距寬度paragraph.setMarginTop(180f);// 定義文本元素的所有字符之間的自定義間距paragraph.setCharacterSpacing(0.4f);// 設置對齊方式paragraph.setTextAlignment(TextAlignment.CENTER);// 設置段落前留多少空paragraph.setFirstLineIndent(24);// 表格Table table = new Table(8);table.addHeaderCell("添加頭部單元格");table.addCell("普通單元格");// 設置單元格對齊方式table.addCell(new Cell().setTextAlignment(TextAlignment.CENTER));// 寬度和頁面一致table.useAllAvailableWidth();// 新起一行table.startNewRow();// 添加到文檔document.add(new Div().add(table));document.add(div);document.add(paragraph);

從Document的add方法可知, 此處添加的IBlockElement對象.

IBlockElement源碼:

public interface IBlockElement extends IElement { }

IBlockElement接口的唯一抽象子類BlockElement 而BlockElement的子類包括:

  • Cell 單元格元素,常在Table中使用

  • Div 塊狀元素, 作為一個整體,如可添加一個Table表格放進去,這個表格就是一個整體,表格數據量很大,涉及到分頁,會自動向后下一頁分頁.

    • ListItem 列表項
  • LineSeparator 行分隔符

  • List 列表

  • Paragraph 段落,普通的一段文字

  • Table 表格

5 換行/空格/換頁

  • 換行使用\n
  • tab效果使用\u00a0符號, 一般連著使用8個.
  • 使用Tab和TabStop類來控制縮進
// 空格paragraph.add(new Text("\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0第一行縮進")); paragraph.add(new Tab());paragraph.addTabStops(new TabStop(20, TabAlignment.LEFT));// 換頁document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));

6 Html轉換為Pdf

ConverterProperties proper = new ConverterProperties();//字體設置,解決中文不顯示問題FontSet fontSet = new FontSet();// 加載自定義字體fontSet.addFont(PdfDemo.class.getClassLoader().getResource("ttf/SourceHanSansCN-Regular.ttf").getPath(), PdfEncodings.IDENTITY_H);FontProvider fontProvider = new FontProvider(fontSet);proper.setFontProvider(fontProvider);String content = "html內容";// 使用jar包提供的方法轉換成IElement對象, 而IElement對象正是所有填充對象的最上層接口, 可以轉換為 Div ,Paragraph對象填充到PDFList<IElement> elements = HtmlConverter.convertToElements(content, proper);// 定義填充PDF塊Div div = new Div();// 遍歷元素,封裝數據for (IElement iElement : elements) {if (iElement instanceof Div) {div.add((Div) iElement);} else if (iElement instanceof Paragraph) {div.add((Paragraph) iElement);}}document.add(div);

7 關于PDF上簽章功能

方法一

通過保存簽章圖片,把圖片生成Image對象,設置好對應的坐標位置,添加到document中.

方法二

通過生成電子簽章,直接將Pdf文件轉化成字節流,添加簽章的關鍵字,位置坐標大小等屬性,簽章服務器將生成后的PDF轉換成字節流傳回,本地獲取成為PDF文件保存即可.

參考資料:

https://blog.csdn.net/tzxylao/article/details/106486009

https://kb.itextpdf.com/home/it7kb/ebooks/itext-7-building-blocks

https://blog.csdn.net/lxwfly/article/details/106895695

總結

以上是生活随笔為你收集整理的itext7相关使用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。