国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Java使用itextpdf生成PDF文件

這篇具有很好參考價值的文章主要介紹了Java使用itextpdf生成PDF文件。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

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();

常見錯誤:???????

1、使用PdfReader讀取Pdf文件時報錯:

java.lang.ClassNotFoundException: org.bouncycastle.crypto.engines.AESFastEng

報錯原因:pdf文件被用戶加密了。

解決辦法:引入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)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔相關(guān)法律責任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • Java導(dǎo)出PDF(itextpdf)-通俗易懂

    Java導(dǎo)出PDF(itextpdf)-通俗易懂

    在java開發(fā)的過程中會遇到太多太多文檔pdf導(dǎo)出,excle導(dǎo)出等業(yè)務(wù)場景,時隔三個月或半年來一次每一次遇到這樣的業(yè)務(wù)場景對我都是非常痛苦的過程,本文旨在記錄工具類使用方法和技術(shù)分享。 itextpdf是一個開源的Java庫,用于創(chuàng)建和操作PDF文檔。使用itextpdf,您可以創(chuàng)建新的

    2024年02月12日
    瀏覽(23)
  • (Java)word轉(zhuǎn)pdf(aspose),pdf加水印(itextpdf),并支持POI模板(包括checkbox)導(dǎo)出

    (Java)word轉(zhuǎn)pdf(aspose),pdf加水印(itextpdf),并支持POI模板(包括checkbox)導(dǎo)出

    目錄 1、引入jar包 2、pdf處理工具類 3、poi模板導(dǎo)出工具類 4、測試類 5、模板 6、最終效果? 1、引入jar包 ? 2、pdf處理工具類 ?3、poi模板導(dǎo)出工具類 ?4、測試類 5、模板 6、最終效果?

    2024年02月06日
    瀏覽(33)
  • itextpdf7 使用之 html轉(zhuǎn)pdf,生成目錄可跳轉(zhuǎn)、添加頁眉頁腳

    itextpdf7 使用之 html轉(zhuǎn)pdf,生成目錄可跳轉(zhuǎn)、添加頁眉頁腳

    最近有個需求,生成信用報告。 需求: 1、生成pdf有頁眉頁腳 2、生成目錄 3、目錄加錨點可跳轉(zhuǎn)。 難點: 1、生成的目錄不能實時讀取頁碼 2、目錄是后生成的,屬于兩份pdf拼接的,不能添加錨點跳轉(zhuǎn) 思路: 1、freemaker進行html頁面布局及動態(tài)變量替換 2、生成一份pdf文檔,用

    2024年02月20日
    瀏覽(18)
  • Java使用ftl模板文件生成Word,以及Word轉(zhuǎn)換圖片或Pdf工具類

    Java使用ftl模板文件生成Word,以及Word轉(zhuǎn)換圖片或Pdf工具類

    一、寫在前面 最近在項目中使用打印功能,發(fā)現(xiàn)這個功能我已經(jīng)寫過多次了,下面這個文章的發(fā)步日期在2020年,不得不感慨時間之快啊。 https://blog.csdn.net/weixin_43238452/article/details/109636200?spm=1001.2014.3001.5501 下面介紹一下應(yīng)用場景:這次項目依舊是springboot項目,使用ftl模版生

    2024年02月15日
    瀏覽(38)
  • java生成pdf文件

    pom添加依賴 util工具類 controller層,返回前端流數(shù)據(jù),前端自己下載文件

    2024年02月16日
    瀏覽(19)
  • Java doc等文件生成PDF、多個PDF合并

    之前寫過一遍文章是 圖片生成PDF。 今天繼續(xù)來對 doc等文件進行pdf合并以及多個pdf合并為一個pdf。 兄弟們,還是開箱即用。 依賴 示例代碼 依賴 示例代碼

    2024年02月10日
    瀏覽(22)
  • Java Excel轉(zhuǎn)PDF,支持xlsx和xls兩種格式, itextpdf【即取即用】

    本篇主要為工具方法整理,參考學(xué)習其他博主文章做了整理,方便使用。 1、本地轉(zhuǎn)換 導(dǎo)入依賴 創(chuàng)建工具方法 傳入輸入輸出流或文檔地址即可。 2、網(wǎng)絡(luò)下載 通過POI或者easyExcel生成或填充,再由后端轉(zhuǎn)換PDF響應(yīng)前端 思路 :將網(wǎng)絡(luò)下載拆分為本地轉(zhuǎn)換,再響應(yīng)前端即可。 現(xiàn)

    2024年02月04日
    瀏覽(28)
  • Java中如何生成PDF文件的縮略圖

    在Java中生成PDF文件的縮略圖可以使用Apache PDFBox庫。以下是一個簡單的示例代碼來實現(xiàn)這個功能: 在上面的代碼中,首先加載PDF文件并創(chuàng)建一個PDFRenderer對象。然后使用 renderImage 方法來渲染指定頁面的PDF文檔為一個BufferedImage對象。最后使用 writeImage 方法將BufferedImage對象保存

    2024年04月14日
    瀏覽(22)
  • Java根據(jù)word模板生成word文檔并轉(zhuǎn)成PDF文件

    Java根據(jù)word模板生成word文檔并轉(zhuǎn)成PDF文件

    定義完我們的模板之后,我們要將文檔保存為xml的格式 生成的xml格式看起來比較亂,沒有層次感, 所以需要格式化一下 格式化 基礎(chǔ)信息的定義 基礎(chǔ)信息的定義只要保證我們轉(zhuǎn)化成的xml文件中的${name}等格式?jīng)]錯誤即可 表格的定義 遍歷實現(xiàn),表格的數(shù)據(jù)填充 在xml文件中我們的

    2024年02月09日
    瀏覽(35)
  • 【教程】如何使用Java生成PDF文檔?

    在如今數(shù)字化時代,越來越多的人使用PDF文檔進行信息傳遞和共享。而使用Java生成PDF文檔也成為了一個非常重要的技能,因為Java作為一種通用的編程語言,可以在不同的操作系統(tǒng)和平臺上運行。下面,我們將為您介紹如何使用Java生成PDF文檔。 PDF文檔的生成通常包括兩個步驟

    2024年02月02日
    瀏覽(21)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包