Java操作pdf的工具類itext的處理方法
一、什么是iText?
在企業(yè)的信息系統(tǒng)中,報(bào)表處理一直占比較重要的作用,iText是一種生成PDF報(bào)表的Java組件。通過在服務(wù)器端使用Jsp或JavaBean生成PDF報(bào)表,客戶端采用超鏈接顯示或下載得到生成的報(bào)表,這樣就很好的解決了B/S系統(tǒng)的報(bào)表處理問題。
二、引入jar
1、項(xiàng)目要使用iText,必須引入jar包
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.6</version> </dependency>
2、輸出中文,還要引入下面itext-asian.jar包
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>3、設(shè)置pdf文件密碼,還要引入下面bcprov-jdk15on.jar包
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.47</version>
</dependency>三、iText常用類
com.itextpdf.text.Document:這是iText庫中最常用的類,它代表了一個(gè) pdf 實(shí)例。如果你需要從零開始生成一個(gè)pdf文件,你需要使用這個(gè)Document類。首先創(chuàng)建該實(shí)例,然后打開它,并添加內(nèi)容,最后關(guān)閉該實(shí)例,即可生成一個(gè)pdf文件。com.itextpdf.text.Paragraph:表示一個(gè)縮進(jìn)的文本段落,在段落中,你可以設(shè)置對(duì)齊方式,縮進(jìn),段落前后間隔等com.itextpdf.text.Chapter:表示 pdf 的一個(gè)章節(jié),他通過一個(gè)Paragraph類型的標(biāo)題和整形章數(shù)創(chuàng)建com.itextpdf.text.Font:這個(gè)類包含了所有規(guī)范好的字體,包括family of font,大小,樣式和顏色,所有這些字體都被聲明為靜態(tài)常量com.itextpdf.text.List:表示一個(gè)列表;com.itextpdf.text.Anchor:表示一個(gè)錨,類似于HTML頁面的鏈接。com.itextpdf.text.pdf.PdfWriter:當(dāng)這個(gè)PdfWriter被添加到PdfDocument后,所有添加到Document的內(nèi)容將會(huì)寫入到與文件或網(wǎng)絡(luò)關(guān)聯(lián)的輸出流中。com.itextpdf.text.pdf.PdfReader:用于讀取 pdf 文件;
四、生成PDF步驟
1、創(chuàng)建文檔
Document document = new Document();
2、通過書寫器將文檔寫入磁盤
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FILE_DIR + "createPDFWithColor.pdf"));
3、打開文檔
document.open();
4、向文檔中添加內(nèi)容
document.add(new Paragraph("i love CSDN"));5、關(guān)閉文檔
document.close();
五、Java操作pdf的工具類itext
package com.neusoft.guor.itext;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfAction;
import com.itextpdf.text.pdf.PdfAnnotation;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfOutline;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfString;
import com.itextpdf.text.pdf.PdfTransition;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.DottedLineSeparator;
import com.itextpdf.text.pdf.draw.LineSeparator;
import com.itextpdf.text.pdf.draw.VerticalPositionMark;
/**
* itext PDF操作
*/
public class PDFInit {
public static final String FILE_DIR = "E:\\guor\\itext\\";
public static final String const_JPG_JAVA = FILE_DIR + "java.jpg";
public static final String const_JPG_NGINX = FILE_DIR + "nginx.jpg";
private static final String const_NEZHA = "哪吒編程";
private static final String const_NEZHA_PROGRAM = "獲取Java學(xué)習(xí)資料請(qǐng)關(guān)注公眾號(hào):哪吒編程";
private static final String const_BIBIDONG = "比比東";
private static final String const_YUNYUN = "云韻";
private static final String const_BAIDU = "百度一下 你就知道";
private static final String const_BAIDU_URL = "https://www.baidu.com";
private static final String const_PAGE_FIRST = "第一頁";
private static final String const_PAGE_SECOND = "第二頁";
private static final String const_PAGE_THIRD = "第三頁";
private static final String const_PAGE_FOUR = "第四頁";
private static final String const_PAGE_FIVE = "第五頁";
private static final String const_TITLE_FIRST = "一級(jí)標(biāo)題";
private static final String const_TITLE_SECOND = "二級(jí)標(biāo)題";
private static final String const_CONTENT = "內(nèi)容";
// 普通中文字體
public static Font static_FONT_CHINESE = null;
// 超鏈字體
public static Font static_FONT_LINK = null;
private static void pdfFontInit() throws IOException, DocumentException {
// 微軟雅黑
BaseFont chinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
// 普通中文字體
static_FONT_CHINESE = new Font(chinese, 12, Font.NORMAL);// Font.BOLD為加粗
// 超鏈字體
static_FONT_LINK = new Font(chinese, 12, Font.NORMAL, BaseColor.BLUE);
}
public static Document document;
public static void main(String[] args) throws Exception {
pdfFontInit();
//createPDF();// 生成一個(gè) PDF 文件
//createPDFWithColor();// 設(shè)置PDF的頁面大小和背景顏色
//createPDFWithPassWord();// 創(chuàng)建帶密碼的PDF
//createPDFWithNewPages();// 為PDF添加頁
//createPDFWithWaterMark();// 為PDF文件添加水印,背景圖
//createPDFWithContent();//插入塊Chunk, 內(nèi)容Phrase, 段落Paragraph, List
//createPDFWithExtraContent();//插入Anchor, Image, Chapter, Section
//draw();//畫圖
//createPDFWithAlignment();//設(shè)置段落
//createPDFToDeletePage();//刪除 page
//insertPage();// 插入 page
//splitPDF();//分割 page
//mergePDF();// 合并 PDF 文件
//sortpage();// 排序page
//setHeaderFooter();// 頁眉,頁腳
//addColumnText();// 左右文字
//setView();// 文檔視圖
//pdfToZip();// 壓縮PDF到Zip
addAnnotation();// 注釋
/**
* 創(chuàng)建一個(gè) PDF 文件,并添加文本
*/
public static void createPDF() throws IOException, DocumentException {
// 實(shí)例化 document
document = new Document();
// 生成文件
String path = FILE_DIR + "createPDF.pdf";
File file = new File(path);
if(!file.exists()){
file.createNewFile();
}
PdfWriter.getInstance(document, new FileOutputStream(FILE_DIR + "createPDF.pdf"));
// 打開 document
document.open();
// 添加文本 此處無法寫入中文 TODO
document.add(new Paragraph(const_NEZHA));
document.add(new Paragraph(const_NEZHA, static_FONT_CHINESE));
// 關(guān)閉 document
document.close();
* 創(chuàng)建PDF文件,修改文件的屬性
public static void createPDFWithColor() throws FileNotFoundException, DocumentException {
// 頁面大小
Rectangle rect = new Rectangle(PageSize.A5.rotate());
// 頁面背景色
rect.setBackgroundColor(BaseColor.YELLOW);
document = new Document(rect);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FILE_DIR + "createPDFWithColor.pdf"));
// PDF版本(默認(rèn)1.4)
writer.setPdfVersion(PdfWriter.VERSION_1_6);
// 文檔屬性
document.addAuthor(const_NEZHA);
document.addTitle("我的第一個(gè)pdf");
// 頁邊空白
document.setMargins(10, 10, 10, 10);
// 打開
// 關(guān)閉
* 創(chuàng)建帶密碼的PDF
public static void createPDFWithPassWord() throws FileNotFoundException, DocumentException {
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FILE_DIR + "createPDFWithPassWord.pdf"));
// userPassword打開密碼:"123"
// ownerPassword編輯密碼: "123456"
writer.setEncryption("123".getBytes(), "123456".getBytes(), PdfWriter.ALLOW_SCREENREADERS, PdfWriter.STANDARD_ENCRYPTION_128);
* 為PDF添加頁
public static void createPDFWithNewPages() throws FileNotFoundException, DocumentException {
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FILE_DIR + "createPDFAddNewPages.pdf"));
document.add(new Paragraph(const_PAGE_FIRST, static_FONT_CHINESE));
document.newPage();
document.add(new Paragraph(const_PAGE_SECOND, static_FONT_CHINESE));
writer.setPageEmpty(true);
document.add(new Paragraph(const_PAGE_THIRD, static_FONT_CHINESE));
* 為PDF文件添加水印,背景圖
public static void createPDFWithWaterMark() throws IOException, DocumentException {
FileOutputStream out = new FileOutputStream(FILE_DIR + "createPDFWithWaterMark.pdf");
PdfWriter.getInstance(document, out);
// 圖片水印
PdfReader reader = new PdfReader(FILE_DIR + "createPDFWithWaterMark.pdf");
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR + "createPDFWithWaterMark2.pdf"));
Image img = Image.getInstance(const_JPG_JAVA);
img.setAbsolutePosition(200, 200);
PdfContentByte under = stamp.getUnderContent(1);
under.addImage(img);
// 文字水印
PdfContentByte over = stamp.getOverContent(2);
// 加載字庫來完成對(duì)字體的創(chuàng)建
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
over.beginText();
// 設(shè)置顏色 默認(rèn)為藍(lán)色
over.setColorFill(BaseColor.RED);
// 設(shè)置字體字號(hào)
over.setFontAndSize(bf, 50);
// 設(shè)置起始位置
over.setTextMatrix(30, 30);
// 開始寫入水印 左-下-傾斜度
over.showTextAligned(Element.ALIGN_LEFT, "nezha", 245, 400, 30);
over.endText();
// 背景圖
Image img2 = Image.getInstance(const_JPG_NGINX);
img2.setAbsolutePosition(0, 0);
PdfContentByte under2 = stamp.getUnderContent(3);
under2.addImage(img2);
stamp.close();
reader.close();
* 插入Chunk, Phrase, Paragraph, List
* Chunk : 塊,PDF文檔中描述的最小原子元素
* Phrase : 短語,Chunk的集合
* Paragraph : 段落,一個(gè)有序的Phrase集合
public static void createPDFWithContent() throws DocumentException, FileNotFoundException {
FileOutputStream out = new FileOutputStream(FILE_DIR + "createPDFWithContent.pdf");
// 添加塊
document.add(new Chunk(const_NEZHA, static_FONT_CHINESE));
Font font = new Font(Font.FontFamily.HELVETICA, 8, Font.BOLD, BaseColor.WHITE);
Chunk id = new Chunk("springboot", font);
id.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
id.setTextRise(7);
document.add(id);
Font font2 = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);
Chunk id2 = new Chunk("springcloud", font2);
id2.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
id2.setTextRise(3);
id2.setUnderline(0.2f, -2f);
document.add(id2);
document.add(Chunk.NEWLINE);
// 添加一頁,添加短語
document.add(new Phrase("Phrase page"));
// 添加短語
Phrase director = new Phrase();
Chunk name = new Chunk(const_BIBIDONG, static_FONT_CHINESE);
// 添加下劃線(thickness:下劃線的粗細(xì),yPosition:下劃線離字的距離)
name.setUnderline(0.5f, -1f);
director.add(name);
director.add(new Chunk(","));
director.add(new Chunk(" "));
director.add(new Chunk(const_YUNYUN, static_FONT_CHINESE));
director.setLeading(24);
document.add(director);
// 添加一頁
Phrase director2 = new Phrase();
Chunk name2 = new Chunk(const_BIBIDONG, static_FONT_CHINESE);
name2.setUnderline(0.2f, -2f);
director2.add(name2);
director2.add(new Chunk(","));
director2.add(new Chunk(" "));
director2.add(new Chunk(const_YUNYUN, static_FONT_CHINESE));
director2.setLeading(24);
document.add(director2);
// 添加段落
document.add(new Paragraph("Paragraph page"));
Paragraph info = new Paragraph();
info.add(new Chunk(const_NEZHA));
info.add(new Chunk(const_BIBIDONG));
info.add(Chunk.NEWLINE);
info.add(new Phrase(const_NEZHA));
document.add(info);
// 通過循環(huán)添加段落信息
List list = new List(List.ORDERED);
for (int i = 0; i < 5; i++) {
ListItem item = new ListItem(String.format("%s: %d "+const_NEZHA, const_YUNYUN + (i + 1), (i + 1) * 100), new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE));
List girllist = new List(List.ORDERED, List.ALPHABETICAL);
girllist.setLowercase(List.LOWERCASE);
for (int j = 0; j < 3; j++) {
ListItem girlitem = new ListItem("girls" + (j + 1));
List rolelist = new List(List.UNORDERED);
for (int k = 0; k < 2; k++) {
rolelist.add(String.format("%s, %s", const_NEZHA + (k + 1), const_BIBIDONG + (k + 1)));
}
girlitem.add(rolelist);
girllist.add(girlitem);
}
item.add(girllist);
list.add(item);
document.add(list);
* 插入錨Anchor, Image, 章節(jié)Chapter, 子列表Section
public static void createPDFWithExtraContent() throws DocumentException, MalformedURLException, IOException {
FileOutputStream out = new FileOutputStream(FILE_DIR + "createPDFWithExtraContent.pdf");
String content = "you can get anything from : ";
Paragraph paragraph = new Paragraph(content);
// 創(chuàng)建一個(gè)鏈接到外部網(wǎng)站的新錨點(diǎn)
// 并將此錨點(diǎn)添加到段落中。
Anchor anchor = new Anchor(const_BAIDU, static_FONT_LINK);
anchor.setReference(const_BAIDU_URL);
paragraph.add(anchor);
document.add(paragraph);
// Image對(duì)象
Image img = Image.getInstance(const_JPG_NGINX);
img.setAlignment(Image.LEFT | Image.TEXTWRAP);
img.setBorder(Image.BOX);
img.setBorderWidth(10);
img.setBorderColor(BaseColor.WHITE);
img.scaleToFit(800, 50);// 大小
img.setRotationDegrees(-50);// 旋轉(zhuǎn)
document.add(img);
// 章節(jié)Chapter -- 目錄
Paragraph title = new Paragraph(const_TITLE_FIRST,static_FONT_CHINESE);
// 標(biāo)題和序號(hào)
Chapter chapter = new Chapter(title, 1);
// 子列表Section
title = new Paragraph(const_TITLE_SECOND,static_FONT_CHINESE);
Section section = chapter.addSection(title);
section.setBookmarkTitle(const_NEZHA);
section.setIndentation(10);
section.setBookmarkOpen(false);
section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);
Section subsection1 = section.addSection(new Paragraph(const_CONTENT,static_FONT_CHINESE));
subsection1.setIndentationLeft(10);
subsection1.setNumberDepth(1);
document.add(chapter);
* 畫圖
public static void draw() throws Exception {
FileOutputStream out = new FileOutputStream(FILE_DIR + "draw.pdf");
// 左右箭頭
document.add(new VerticalPositionMark() {
public void draw(PdfContentByte canvas, float llx, float lly, float urx, float ury, float y) {
canvas.beginText();
BaseFont bf = null;
try {
bf = BaseFont.createFont(BaseFont.ZAPFDINGBATS, "", BaseFont.EMBEDDED);
} catch (Exception e) {
e.printStackTrace();
canvas.setFontAndSize(bf, 12);
// LEFT
canvas.showTextAligned(Element.ALIGN_CENTER, String.valueOf((char) 220), llx - 10, y, 0);
// RIGHT
canvas.showTextAligned(Element.ALIGN_CENTER, String.valueOf((char) 220), urx + 10, y + 8, 180);
canvas.endText();
});
// 直線
Paragraph p1 = new Paragraph(const_NEZHA ,static_FONT_CHINESE);
p1.add(new Chunk(new LineSeparator()));
p1.add(const_BIBIDONG);
document.add(p1);
// 點(diǎn)線
Paragraph p2 = new Paragraph(const_NEZHA ,static_FONT_CHINESE);
p2.add(new Chunk(new DottedLineSeparator()));
p2.add(const_BIBIDONG);
document.add(p2);
// 下滑線
LineSeparator UNDERLINE = new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -2);
Paragraph p3 = new Paragraph(const_NEZHA_PROGRAM ,static_FONT_CHINESE);
p3.add(UNDERLINE);
document.add(p3);
* 設(shè)置段落
public static void createPDFWithAlignment() throws Exception {
FileOutputStream out = new FileOutputStream(FILE_DIR + "createPDFWithAlignment.pdf");
Paragraph p = new Paragraph("Never frown, even when you are sad, because you never know who is falling in love with your smile;" +
"You will see exactly what life is worth, when all the rest has gone;" +
"It is very simple to be happy, but it is very difficult to be simple.");
// 默認(rèn)
p.setAlignment(Element.ALIGN_JUSTIFIED);
document.add(p);
// 慢慢的向右移動(dòng)
p.setIndentationLeft(1 * 15f);
p.setIndentationRight((5 - 1) * 15f);
// 居右
p.setAlignment(Element.ALIGN_RIGHT);
p.setSpacingAfter(15f);
// 居左
p.setAlignment(Element.ALIGN_LEFT);
p.setSpacingBefore(15f);
// 居中
p.setAlignment(Element.ALIGN_CENTER);
* 刪除頁
public static void createPDFToDeletePage() throws Exception {
FileOutputStream out = new FileOutputStream(FILE_DIR + "createPDFToDeletePage.pdf");
PdfWriter writer = PdfWriter.getInstance(document, out);
PdfReader reader = new PdfReader(FILE_DIR + "createPDFToDeletePage.pdf");
reader.selectPages("1,3");
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR + "createPDFToDeletePage2.pdf"));
* 插入 page
public static void insertPage() throws Exception {
FileOutputStream out = new FileOutputStream(FILE_DIR + "insertPage.pdf");
PdfReader reader = new PdfReader(FILE_DIR + "insertPage.pdf");
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR + "insertPage2.pdf"));
stamp.insertPage(2, reader.getPageSize(1));
ColumnText ct = new ColumnText(null);
ct.addElement(new Paragraph(24, new Chunk("INSERT PAGE")));
ct.setCanvas(stamp.getOverContent(2));
ct.setSimpleColumn(36, 36, 559, 770);
* 分割 page
public static void splitPDF() throws Exception {
FileOutputStream out = new FileOutputStream(FILE_DIR + "splitPDF.pdf");
document.add(new Paragraph(const_PAGE_FOUR, static_FONT_CHINESE));
PdfReader reader = new PdfReader(FILE_DIR + "splitPDF.pdf");
Document dd = new Document();
PdfWriter writer = PdfWriter.getInstance(dd, new FileOutputStream(FILE_DIR + "splitPDF1.pdf"));
dd.open();
PdfContentByte cb = writer.getDirectContent();
dd.newPage();
cb.addTemplate(writer.getImportedPage(reader, 1), 0, 0);
cb.addTemplate(writer.getImportedPage(reader, 2), 0, 0);
dd.close();
writer.close();
Document dd2 = new Document();
PdfWriter writer2 = PdfWriter.getInstance(dd2, new FileOutputStream(FILE_DIR + "splitPDF2.pdf"));
dd2.open();
PdfContentByte cb2 = writer2.getDirectContent();
dd2.newPage();
cb2.addTemplate(writer2.getImportedPage(reader, 3), 0, 0);
cb2.addTemplate(writer2.getImportedPage(reader, 4), 0, 0);
dd2.close();
writer2.close();
* 合并 PDF 文件
public static void mergePDF() throws Exception {
PdfReader reader1 = new PdfReader(FILE_DIR + "splitPDF1.pdf");
PdfReader reader2 = new PdfReader(FILE_DIR + "splitPDF2.pdf");
FileOutputStream out = new FileOutputStream(FILE_DIR + "mergePDF.pdf");
Document document = new Document();
java.util.List<PdfReader> readers = new ArrayList<PdfReader>();
readers.add(reader1);
readers.add(reader2);
int pageOfCurrentReaderPDF = 0;
Iterator<PdfReader> iteratorPDFReader = readers.iterator();
while (iteratorPDFReader.hasNext()) {
PdfReader pdfReader = iteratorPDFReader.next();
// 在目標(biāo)中為每個(gè)源頁面創(chuàng)建一個(gè)新頁面
while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
document.newPage();
pageOfCurrentReaderPDF++;
PdfImportedPage page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
cb.addTemplate(page, 0, 0);
pageOfCurrentReaderPDF = 0;
out.flush();
out.close();
* 排序page
public static void sortpage() throws Exception {
FileOutputStream out = new FileOutputStream(FILE_DIR + "sortpage.pdf");
writer.setLinearPageMode();
document.add(new Paragraph(const_PAGE_FIVE, static_FONT_CHINESE));
int[] order = { 4, 3, 2, 1 };
writer.reorderPages(order);
* 頁眉頁腳
public static void setHeaderFooter() throws Exception {
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FILE_DIR + "setHeaderFooter.pdf"));
writer.setPageEvent(new PdfPageEventHelper() {
public void onEndPage(PdfWriter writer, Document document) {
PdfContentByte cb = writer.getDirectContent();
cb.saveState();
cb.beginText();
BaseFont bf = null;
try {
bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
} catch (Exception e) {
e.printStackTrace();
cb.setFontAndSize(bf, 10);
// Header
float x = document.top(-20);
// 左
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "H-Left", document.left(), x, 0);
// 中
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, writer.getPageNumber() + " page", (document.right() + document.left()) / 2, x, 0);
// 右
cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, "H-Right", document.right(), x, 0);
// Footer
float y = document.bottom(-20);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "F-Left", document.left(), y, 0);
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, writer.getPageNumber() + " page", (document.right() + document.left()) / 2, y, 0);
cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, "F-Right", document.right(), y, 0);
cb.endText();
cb.restoreState();
document.add(new Paragraph("1 page"));
document.add(new Paragraph("2 page"));
document.add(new Paragraph("3 page"));
document.add(new Paragraph("4 page"));
public static void addColumnText() throws Exception {
FileOutputStream out = new FileOutputStream(FILE_DIR + "addColumnText.pdf");
PdfContentByte canvas = writer.getDirectContent();
Phrase phrase1 = new Phrase(const_BIBIDONG + " is a beauty!left", static_FONT_CHINESE);
Phrase phrase2 = new Phrase(const_BIBIDONG + " is a beauty!right", static_FONT_CHINESE);
Phrase phrase3 = new Phrase(const_BIBIDONG + " is a beauty!center", static_FONT_CHINESE);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase1, 200, 700, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_RIGHT, phrase2, 200, 600, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase3, 200, 500, 0);
* 文檔視圖
public static void setView() throws Exception {
FileOutputStream out = new FileOutputStream(FILE_DIR + "setView.pdf");
writer.setPdfVersion(PdfWriter.VERSION_1_5);
writer.setViewerPreferences(PdfWriter.PageModeFullScreen);// 全屏
public void onStartPage(PdfWriter writer, Document document) {
writer.setTransition(new PdfTransition(PdfTransition.DISSOLVE, 3));
writer.setDuration(5);// 間隔時(shí)間
* 壓縮PDF到Zip
public static void pdfToZip() throws Exception {
ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(FILE_DIR + "pdfToZip.zip"));
for (int i = 1; i <= 3; i++) {
ZipEntry entry = new ZipEntry(const_NEZHA + i + ".pdf");
zip.putNextEntry(entry);
document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, zip);
writer.setCloseStream(false);
document.open();
document.add(new Paragraph(const_NEZHA + i, static_FONT_CHINESE));
document.close();
zip.closeEntry();
zip.close();
* 添加注釋
public static void addAnnotation() throws Exception {
FileOutputStream out = new FileOutputStream(FILE_DIR + "addAnnotation.pdf");
Document doc = new Document();
PdfWriter writer = PdfWriter.getInstance(doc, out);
doc.open();
doc.add(new Paragraph(const_PAGE_FIRST, static_FONT_CHINESE));
doc.add(new Annotation("title", "this is a annotation!"));
doc.newPage();
doc.add(new Paragraph(const_PAGE_SECOND, static_FONT_CHINESE));
Chunk chunk = new Chunk(const_NEZHA);
chunk.setAnnotation(PdfAnnotation.createText(writer, null, "Title", "this is a another annotation!", false, "Comment"));
doc.add(chunk);
// 添加附件
//doc.newPage();
//doc.add(new Paragraph(const_PAGE_THIRD, static_FONT_CHINESE));
//Chunk chunk2 = new Chunk(const_BIBIDONG, static_FONT_CHINESE);
//PdfAnnotation annotation = PdfAnnotation.createFileAttachment(writer, null, "Title", null, const_JPG_JAVA, const_JPG_NGINX);
//annotation.put(PdfName.NAME, new PdfString("Paperclip"));
//chunk2.setAnnotation(annotation);
//doc.add(chunk2);
doc.close();
}六、更多的Java代碼實(shí)例
【Java 代碼實(shí)例 1】java反射三種方法
…
【Java 代碼實(shí)例 4】javacompiler編譯多java文件
…
【Java 代碼實(shí)例 6】FileUtils、StringUtil、CollectionUtils、ArrayUtils(附代碼示例)
【Java 代碼實(shí)例 7】jsoup解析html
【Java 代碼實(shí)例 8】qrcode生成二維碼
【Java 代碼實(shí)例 9】Java通過Process執(zhí)行C# exe程序
…
到此這篇關(guān)于Java操作pdf的工具類itext的文章就介紹到這了,更多相關(guān)Java pdf的工具類itext內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用springmvc參數(shù)接收boolean類型參數(shù)的問題
這篇文章主要介紹了使用springmvc參數(shù)接收boolean類型參數(shù)的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
SSM項(xiàng)目中使用攔截器和過濾器的實(shí)現(xiàn)示例
這篇文章主要介紹了SSM項(xiàng)目中使用攔截器和過濾器的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04

