日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

itext7相关使用

發(fā)布時(shí)間:2023/12/14 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 itext7相关使用 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

itext7相關(guān)使用

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

最近有使用到itext7相關(guān)技術(shù),生成pdf文件,添加電子簽章等功能.

1 itext7的簡(jiǎn)介

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

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

2 itext7的使用

1 添加相關(guān)maven坐標(biāo)

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

2 itext7相關(guān)語法說明

1 PDF生成案例

public class PdfDemo { // 生產(chǎn)的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));// 項(xiàng)目指定字體, 通過類加載項(xiàng)目字體資源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對(duì)象的步驟.接下來,一步一步看Document對(duì)象創(chuàng)建的過程

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文檔是創(chuàng)建自定義PDF時(shí)的默認(rèn)根元素 // 它主要操作高級(jí)操作,例如設(shè)置頁(yè)面大小和旋轉(zhuǎn),添加元素,并在特定坐標(biāo)處寫入文本 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*/// 常用構(gòu)造方法 使用PdfDocument對(duì)象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.*/// 設(shè)置元素的字體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文檔的主輸入點(diǎn) public class PdfDocument implements IEventDispatcher, Closeable, Serializable {/*** Open PDF document in writing mode.* Document has no pages when initialized.** @param writer PDF writer*/// 以編寫模式打開PDF文檔 ,文檔初始化時(shí)沒有頁(yè)面 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*/// 創(chuàng)建一個(gè)PdfWriter,將其寫入傳遞的文件名并具有默認(rèn)的writer屬性public PdfWriter(String filename) throws FileNotFoundException {this(filename, new WriterProperties());}

2 圖片相關(guān)語法

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

// 得到需要插入的圖片 常使用兩種方式獲取: 即 url 和 filenameImageData imageData = ImageDataFactory.create("C:\\Pdf圖片.png");// 得到填充PDF的Image對(duì)象, 可以設(shè)置圖片的各種參數(shù)Image image = new Image(imageData)// 設(shè)置寬高擴(kuò)大縮小image.scale(1, 1.05f);// 將圖像縮放到絕對(duì)大小image.scaleAbsolute(80, 80);// 設(shè)置邊距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 添加空白頁(yè)

添加第2頁(yè)為空白頁(yè),立即刷新后再繼續(xù)添加

pdfDocument.addNewPage(2).flush();

4 Div和Paragraph

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

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

IBlockElement源碼:

public interface IBlockElement extends IElement { }

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

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

  • Div 塊狀元素, 作為一個(gè)整體,如可添加一個(gè)Table表格放進(jìn)去,這個(gè)表格就是一個(gè)整體,表格數(shù)據(jù)量很大,涉及到分頁(yè),會(huì)自動(dòng)向后下一頁(yè)分頁(yè).

    • ListItem 列表項(xiàng)
  • LineSeparator 行分隔符

  • List 列表

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

  • Table 表格

5 換行/空格/換頁(yè)

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

6 Html轉(zhuǎn)換為Pdf

ConverterProperties proper = new ConverterProperties();//字體設(shè)置,解決中文不顯示問題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內(nèi)容";// 使用jar包提供的方法轉(zhuǎn)換成IElement對(duì)象, 而IElement對(duì)象正是所有填充對(duì)象的最上層接口, 可以轉(zhuǎn)換為 Div ,Paragraph對(duì)象填充到PDFList<IElement> elements = HtmlConverter.convertToElements(content, proper);// 定義填充PDF塊Div div = new Div();// 遍歷元素,封裝數(shù)據(jù)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 關(guān)于PDF上簽章功能

方法一

通過保存簽章圖片,把圖片生成Image對(duì)象,設(shè)置好對(duì)應(yīng)的坐標(biāo)位置,添加到document中.

方法二

通過生成電子簽章,直接將Pdf文件轉(zhuǎn)化成字節(jié)流,添加簽章的關(guān)鍵字,位置坐標(biāo)大小等屬性,簽章服務(wù)器將生成后的PDF轉(zhuǎn)換成字節(jié)流傳回,本地獲取成為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

總結(jié)

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

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。