iText是用于生成PDF文檔的一個java類庫。通過iText不僅可以生成PDF文檔,而且可以將Html文件轉(zhuǎn)化為PDF文件。
導(dǎo)入依賴
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.13</version>
</dependency>
生成PDF文件
//創(chuàng)建文本對象
Document document = new Document(PageSize.A4);
File attachPdfFile = new File(filePath);
attachPdfFile.createNewFile();
//PdfWriter是iText編輯PDF文檔的編輯器
// 為該Document創(chuàng)建一個Writer實例
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(attachPdfFile));
//打開document
document.open();
//插入段落文字
Paragraph textgraph = new Paragraph(text);
textgraph.setAlignment(Element.ALIGN_CENTER);
textgraph.setSpacingBefore(40f);
document.add(textgraph);
//關(guān)閉 document
document.close();
合并PDF文件
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputPath));
//打開docuemnt
document.open();
for (String pdfPath : pdfList) {
PdfReader reader = new PdfReader(pdfPath);
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
PdfImportedPage page = writer.getImportedPage(reader, i);
Image image = Image.getInstance(page);
image.setAlignment(Image.ALIGN_CENTER);
image.scalePercent(80); //依照比例縮放
document.add(image);
document.newPage();
}
}
//關(guān)閉document
document.close();
HTML轉(zhuǎn)PDF文件
// 為該Document創(chuàng)建一個Writer實例
PdfWriter pdfwriter = PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
pdfwriter.setViewerPreferences(PdfWriter.HideToolbar);
// 打開document
document.open();
XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
fontImp.register(fontFilePath);
byte b[] = content.getBytes(StandardCharsets.UTF_8); //這里是必須要設(shè)置編碼的,不然導(dǎo)出中文就會亂碼。
ByteArrayInputStream bais = new ByteArrayInputStream(b);//將字節(jié)數(shù)組包裝到流中
XMLWorkerHelper.getInstance().parseXHtml(pdfwriter, document, bais, Charset.forName("UTF-8"), fontImp);
bais.close();
//關(guān)閉document
document.close();
Document:文檔對象
構(gòu)造方法:
Document(Rectangle pageSize, float marginLeft, float marginRight, float marginTop, float marginBottom)
指定PDF的頁面大小,頁邊距。
默認 Document()為:A4,36,36,36,36
屬性信息:
//為pdf添加屬性信息
document.addAuthor("作者");
document.addTitle("標題");
document.addSubject("主題");
document.addKeywords("關(guān)鍵字");
document.addCreator("創(chuàng)建者");
添加文字段落:
//創(chuàng)建一個文字段落
Paragraph graph = new Paragraph(text);
//把段落加入到文檔中
document.add(graph);
添加空頁面:
//添加新的一頁
document.newPage();
document.add(new Paragraph(text));
是否顯示空白頁:
//顯示空內(nèi)容的頁
writer.setPageEmpty(false);
設(shè)置頁面邊距
//頁邊空白
document.setMargins(10, 20, 30, 40);
Rectangle:頁面對象
構(gòu)造方法:
Rectangle(float llx, float lly, float urx, float ury)
llx 為Left ,lly 為Bottom, urx 為Right,ury 為Top
指定頁面屬性:
// 頁面的屬性
// 頁面大小
// A4,PageSize封裝了大量常用的Rectangle數(shù)據(jù)
Rectangle tRectangle = PageSize.A4;
// 長寬
Rectangle tRectangle = new Rectangle(800, 600);
// 等于上面
Rectangle tRectangle = new Rectangle(0, 0, 800, 600);
// 橫向
tRectangle = tRectangle.rotate();
// 其它頁面屬性,不能和PageSize封裝的靜態(tài)一起使用
// 頁面背景色
tRectangle.setBackgroundColor(BaseColor.ORANGE);
// 邊框
tRectangle.setBorder(1220);
// 邊框顏色
tRectangle.setBorderColor(BaseColor.BLUE);
// 邊框?qū)挾?tRectangle.setBorderWidth(15.2f);
//創(chuàng)建文本對象
Document document = new Document(tRectangle);
也可以直接使用PageSize來獲取常用的Rectangle頁面對象
//默認PageSize.A4, 36, 36, 36, 36
Document document = new Document();
//A4,等效于上面
Document document = new Document(PageSize.A4);
//橫向A4
Document document = new Document(PageSize.A4.rotate());
//A4,頁邊距50
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
Font:字體對象
- BaseFont:確認支持中文
- Font:字體的設(shè)置,如顏色,字體,大小等
Font fontChinese = null;
try {
// 不同字體(這里定義為同一種字體:包含不同字號、不同style)
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
fontChinese = new Font(bfChinese, 18, Font.BOLD);
} catch (Exception e) {
e.printStackTrace();
}
Paragraph:段落對象
Paragraph tParagraph = new Paragraph(text, getChineseFont());
tParagraph.setAlignment(Element.ALIGN_JUSTIFIED);// 對齊方式
tParagraph.setIndentationLeft(12);// 左縮進
tParagraph.setIndentationRight(12);// 右縮進
tParagraph.setFirstLineIndent(24);// 首行縮進
tParagraph.setLeading(20f);// 行間距
tParagraph.setSpacingBefore(5f);// 設(shè)置段落上空白
tParagraph.setSpacingAfter(10f);// 設(shè)置段落下空白
document.add(tParagraph);
Image:圖像對象
Image繼承自Rectangle
初始化方式:
Image img = Image.getInstance(imagePath)
向PDF中插入圖片
// 圖片Image對象
Image img = Image.getInstance("source/imag/bage.png");
img.setAlignment(Image.LEFT); //圖片對齊方式
img.setBorder(Image.BOX); //邊框類型
img.setBorderWidth(10); //邊框?qū)挾?img.setBorderColor(BaseColor.WHITE); //邊框顏色
img.scaleToFit(1000, 72); // 大小
img.setRotationDegrees(-30); // 旋轉(zhuǎn)
img.setAbsolutePosition(0, 0); //設(shè)置圖片絕對位置
document.add(img);
Anchor:錨點、超鏈接
超鏈接:
// 超鏈接
Paragraph graph = new Paragraph();
Anchor dest = new Anchor("超鏈接", font);
dest.setReference("http://www.baidu.com"); //超鏈接
graph.add(dest);
document.add(graph);
錨點:
// 錨點
Paragraph dstgraph = new Paragraph();
Anchor dest = new Anchor("我是錨點A", font);
dest.setName("TOM"); //設(shè)置錨點A的名字
dstgraph.add(dest);
document.add(dstgraph);
Paragraph srcgraph = new Paragraph();
Anchor src = new Anchor("我是錨點B,鏈接到錨點A", font);
src.setReference("#TOM"); //取到錨點A
srcgraph.add(src);
document.add(srcgraph);
PdfContentByte:層對象
PDF有四層結(jié)構(gòu),一、四層可操作;二、三層Itext內(nèi)部處理。
可以通過PdfContentByte 實現(xiàn)添加水印、背景、添加內(nèi)容到絕對位置、合并PDF等
操作方式:
PdfWriter 對象:
第 1 層操作:PdfWriter. getDirectContent(),//默認當前頁
第 2 層操作:getDirectContentUnder()。
PdfStamper 對象:
第 1 層操作: PdfStamper. getUnderContent(1),//可以加頁數(shù)
第 2 層操作: PdfStamper .getOverContent(1)。
添加文字水?。?/h4>
PdfStamper方式:
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(outPdfPath)));
PdfReader reader = new PdfReader(inPdfPath);
PdfStamper stamper = new PdfStamper(reader, bos);
int total = reader.getNumberOfPages();
PdfContentByte content;
//參數(shù):字體參數(shù),字體編碼格式,是否將字體信息嵌入到pdf中(一般不需要嵌入),字體大小
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
//設(shè)置水印透明度
PdfGState gs = new PdfGState();
// 設(shè)置填充字體不透明度為0.4f
gs.setFillOpacity(0.45f);
for (int i = 1; i <= total; i++) {
//content = stamper.getOverContent(i); //在內(nèi)容上方加水印
content = stamper.getUnderContent(i); //在內(nèi)容下方加水印
//設(shè)置水印透明度
content.setGState(gs);
//開始寫入
content.beginText();
//水印顏色
content.setColorFill(Color.LIGHT_GRAY);
//設(shè)置字體和大小
content.setFontAndSize(bf, 50);
//設(shè)置文字輸出位置
content.setTextMatrix(70, 200);
// 設(shè)置水印對齊方式 水印內(nèi)容 X坐標 Y坐標 旋轉(zhuǎn)角度
content.showTextAligned(Element.ALIGN_CENTER, waterMarkText, 300, 350, 50);
//結(jié)束寫入
content.endText();
}
stamper.close();
showTextAligned?參數(shù)分別是:文字對齊方式,位置內(nèi)容,輸出水印X軸位置,Y軸位置,旋轉(zhuǎn)角度。
PdfWriter方式:
PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(pdfFilePath));
// 打開文檔
document.open();
// 獲取當前頁的第二層
PdfContentByte content = pdfWriter.getDirectContentUnder();
// 開始寫入
content.beginText();
// 設(shè)置水印透明度
PdfGState gs = new PdfGState();
// 設(shè)置填充字體不透明度為0.4f
gs.setFillOpacity(0.4f);
//參數(shù):字體參數(shù),字體編碼格式,是否將字體信息嵌入到pdf中(一般不需要嵌入),字體大小
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
try {
// 設(shè)置水印字體及大小
content.setFontAndSize(bf, 50);
// 設(shè)置透明度
content.setGState(gs);
// 設(shè)置水印對齊方式 水印內(nèi)容 X坐標 Y坐標 旋轉(zhuǎn)角度
content.showTextAligned(Element.ALIGN_RIGHT, waterMarkText, 300, 350, 50);
// 設(shè)置水印顏色
content.setColorFill(BaseColor.GRAY);
//結(jié)束設(shè)置
content.endText();
content.stroke();
} catch (IOException e) {
e.printStackTrace();
}
// 加入文檔內(nèi)容
document.add(new Paragraph("hello world"));
// 關(guān)閉文檔
document.close();
pdfWriter.close();
添加圖片水?。?/h4>
// 加入水印
PdfContentByte content = pdfWriter.getDirectContentUnder();
// 開始設(shè)置水印
content.beginText();
// 設(shè)置水印透明度
PdfGState gs = new PdfGState();
// 設(shè)置筆觸字體不透明度為0.4f
gs.setStrokeOpacity(0.4f);
Image image = Image.getInstance(imageFilePath);
// 設(shè)置坐標 絕對位置 X Y
image.setAbsolutePosition(200, 300);
// 設(shè)置旋轉(zhuǎn)弧度
image.setRotation(30); // 旋轉(zhuǎn) 弧度
// 設(shè)置旋轉(zhuǎn)角度
image.setRotationDegrees(45); // 旋轉(zhuǎn) 角度
// 設(shè)置等比縮放
image.scalePercent(90); // 依照比例縮放
// image.scaleAbsolute(200,100); //自定義大小
// 設(shè)置透明度
content.setGState(gs);
// 添加水印圖片
content.addImage(image);
// 結(jié)束設(shè)置
content.endText();
content.stroke();
常見錯誤:???????
// 加入水印
PdfContentByte content = pdfWriter.getDirectContentUnder();
// 開始設(shè)置水印
content.beginText();
// 設(shè)置水印透明度
PdfGState gs = new PdfGState();
// 設(shè)置筆觸字體不透明度為0.4f
gs.setStrokeOpacity(0.4f);
Image image = Image.getInstance(imageFilePath);
// 設(shè)置坐標 絕對位置 X Y
image.setAbsolutePosition(200, 300);
// 設(shè)置旋轉(zhuǎn)弧度
image.setRotation(30); // 旋轉(zhuǎn) 弧度
// 設(shè)置旋轉(zhuǎn)角度
image.setRotationDegrees(45); // 旋轉(zhuǎn) 角度
// 設(shè)置等比縮放
image.scalePercent(90); // 依照比例縮放
// image.scaleAbsolute(200,100); //自定義大小
// 設(shè)置透明度
content.setGState(gs);
// 添加水印圖片
content.addImage(image);
// 結(jié)束設(shè)置
content.endText();
content.stroke();
1、使用PdfReader讀取Pdf文件時報錯:
java.lang.ClassNotFoundException: org.bouncycastle.crypto.engines.AESFastEng
報錯原因:pdf文件被用戶加密了。文章來源:http://www.zghlxwxcb.cn/news/detail-803960.html
解決辦法:引入org.bouncycastle依賴
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.70</version>
</dependency>
2、使用PdfReader讀取Pdf文件時報錯:
PdfReader not opened with owner password
報錯原因:pdf文件被用戶加密了。
解決辦法:在創(chuàng)建pdfReader實例后,加一行代碼:文章來源地址http://www.zghlxwxcb.cn/news/detail-803960.html
PdfReader.unethicalreading = true;
到了這里,關(guān)于Java使用itextpdf生成PDF文件的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!