Java使用itextpdf生成PDF文件并添加斜面水印并完成下载(图片导出pdf)
生活随笔
收集整理的這篇文章主要介紹了
Java使用itextpdf生成PDF文件并添加斜面水印并完成下载(图片导出pdf)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
提供自己的一些工具類
生成PDF文件所需的jar包
引入maven依賴
生成PDF
創建一個PDF字體樣式工具類
package test;import java.io.IOException;import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.BaseFont;public class PdfFontUtils {// 字體private static BaseFont baseFont = null;static{try {/*** 設置字體* * windows路徑字體* FONT_TYPE=C:/Windows/fonts/simsun.ttc* linux路徑字體 宋體 (如果沒有這個字體文件,就將windows的字體傳上去)* FONT_TYPE=/usr/share/fonts/win/simsun.ttc*///可以用配置文件讀取//獲取配置//PropertiesLoader pl = new PropertiesLoader("/config/config.properties"); //拼接文件web訪問路徑//String FONT_TYPE = pl.getProperty("FONT_TYPE"); //解決中文問題 幼圓baseFont = BaseFont.createFont("C:/Windows/fonts/simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//在linux解決中文問題 如果沒有語言包需要自己下載//baseFont = BaseFont.createFont("/usr/share/fonts/MSYH.TTC,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);} catch (DocumentException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}/*** 文檔超級 排版* @param type 1-標題 2-標題一 3-標題二 4-標題三 5-正文 6-左對齊*/public static Paragraph getFont(int type, String text){Font font = new Font(baseFont);if(1 == type){//1-標題font.setSize(16f);font.setStyle(Font.BOLD);} else if(2 == type){//2-標題一font.setSize(16f);font.setStyle(Font.BOLD);} else if(3 == type){//3-標題二font.setSize(14f);font.setStyle(Font.BOLD);} else if(4 == type){//4-標題三font.setSize(14f);} else if(5 == type){//5-正文font.setSize(10.5f);} else if(6 == type){//6-左對齊font.setSize(10.5f);} else {font.setSize(10.5f);//默認大小}//注: 字體必須和 文字一起newParagraph paragraph = new Paragraph(text, font);if(1 == type){paragraph.setAlignment(Paragraph.ALIGN_CENTER);//居中paragraph.setSpacingBefore(10f);//上間距paragraph.setSpacingAfter(10f);//下間距} else if(2 == type){//2-標題一paragraph.setAlignment(Element.ALIGN_JUSTIFIED); //默認paragraph.setSpacingBefore(2f);//上間距paragraph.setSpacingAfter(2f);//下間距} else if(3 == type){paragraph.setSpacingBefore(2f);//上間距paragraph.setSpacingAfter(1f);//下間距} else if(4 == type){//4-標題三//paragraph.setAlignment(Element.ALIGN_RIGHT);//右對齊 paragraph.setSpacingBefore(2f);//上間距paragraph.setSpacingAfter(2f);//下間距} else if(5 == type){paragraph.setAlignment(Element.ALIGN_JUSTIFIED); paragraph.setFirstLineIndent(24);//首行縮進paragraph.setSpacingBefore(1f);//上間距paragraph.setSpacingAfter(1f);//下間距} else if(6 == type){//左對齊paragraph.setAlignment(Element.ALIGN_LEFT); paragraph.setSpacingBefore(1f);//上間距paragraph.setSpacingAfter(1f);//下間距}//paragraph.setIndentationLeft(50);//整體縮進左邊//paragraph.setFirstLineIndent(40);//首行縮進return paragraph;} }創建pdf文件
import java.io.File; import java.io.FileOutputStream; import java.io.IOException;import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Phrase; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter;public class CreatePdfText {public static void main(String[] args) {System.out.println("===========start=============");try {Document doc = createPdf("F:\\test\\test.pdf");//生成 合同文件createFile(doc);doc.close();} catch (Exception e) {e.printStackTrace();}System.out.println("===========end=============");}/*** 創建一個pdf并打開* @param outpath pdf路徑*/public static Document createPdf(String outpath) throws DocumentException, IOException{//頁面大小//Rectangle rect = new Rectangle(PageSize.A4.rotate());//文檔橫方向Rectangle rect = new Rectangle(PageSize.A4);//文檔豎方向//如果沒有則創建File saveDir = new File(outpath);File dir = saveDir.getParentFile();if (!dir.exists()) {dir.mkdirs();}Document doc = new Document(rect);PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(outpath));//PDF版本(默認1.4)writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2);//文檔屬性doc.addTitle("Title@wpixel");doc.addAuthor("Author@wpixel");doc.addSubject("Subject@wpixel");doc.addKeywords("Keywords@wpixel");doc.addCreator("Creator@wpixel");//頁邊空白doc.setMargins(40, 40, 40, 40);//打開文檔doc.open();return doc;}public static void createFile(Document doc) throws DocumentException{doc.add(PdfFontUtils.getFont(1, "合作協議"));doc.add(PdfFontUtils.getFont(6, "甲方:"));doc.add(PdfFontUtils.getFont(6, "乙方:"));doc.add(PdfFontUtils.getFont(6, "時間:"));doc.add(PdfFontUtils.getFont(6, "地點:"));Paragraph text05 = PdfFontUtils.getFont(5, "《根據中華人民共和國合同法》的有關規定,經甲、乙雙方友好協商,本著長期平等合作.....吧啦吧啦吧啦吧啦吧啦吧啦吧啦吧啦");doc.add(text05);//一、合作方式及條件doc.add(PdfFontUtils.getFont(2, "一、合作方式及條件"));doc.add(PdfFontUtils.getFont(5, "1.雙方根據國家法律規定建立合作關系,雙方嚴格遵守和執行國家各項方針政策和有關法律、法規和條例規定。 "));doc.add(PdfFontUtils.getFont(5, "2.雙方嚴格按照《中華人民共和國招標投標法》及相關規定實施合作。 "));doc.add(PdfFontUtils.getFont(5, "3.雙方本著密切配合、分工協作、保證質量、按期完成的原則,共同做好工作。 "));//二、權利義務doc.add(PdfFontUtils.getFont(2, "二、權利義務"));doc.add(PdfFontUtils.getFont(5, "1.雙方根據國家法律規定建立合作關系,雙方嚴格遵守和執行國家各項方針政策和有關法律、法規和條例規定。 "));doc.add(PdfFontUtils.getFont(5, "2.雙方嚴格按照《中華人民共和國招標投標法》及相關規定實施合作。 "));doc.add(PdfFontUtils.getFont(5, "3.雙方本著密切配合、分工協作、保證質量、按期完成的原則,共同做好工作。 "));//三、其他doc.add(PdfFontUtils.getFont(2, "三、其他"));doc.add(PdfFontUtils.getFont(5, "1.雙方根據國家法律規定建立合作關系,雙方嚴格遵守和執行國家各項方針政策和有關法律、法規和條例規定。 "));doc.add(PdfFontUtils.getFont(5, "2.雙方嚴格按照《中華人民共和國招標投標法》及相關規定實施合作。 "));doc.add(PdfFontUtils.getFont(5, "3.自定義 "));PdfPTable table = new PdfPTable(2);table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);PdfPCell cell;cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "甲方:(蓋章)")));cell.setColspan(1);cell.setBorder(0);table.addCell(cell);cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "乙方:(蓋章)")));cell.setColspan(1);cell.setBorder(0);table.addCell(cell);cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "法定代表人或負責人簽章")));cell.setColspan(1);cell.setBorder(0);table.addCell(cell);cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "法定代表人或負責人簽章")));cell.setColspan(1);cell.setBorder(0);table.addCell(cell);cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "地址:")));cell.setColspan(1);cell.setBorder(0);table.addCell(cell);cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "地址:")));cell.setColspan(1);cell.setBorder(0);table.addCell(cell);cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "開戶銀行:")));cell.setColspan(1);cell.setBorder(0);table.addCell(cell);cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "開戶銀行:")));cell.setColspan(1);cell.setBorder(0);table.addCell(cell);cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "郵編:")));cell.setColspan(1);cell.setBorder(0);table.addCell(cell);cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "郵編:")));cell.setColspan(1);cell.setBorder(0);table.addCell(cell);cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "授權代理人:")));cell.setColspan(1);cell.setBorder(0);table.addCell(cell);cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "項目經理:")));cell.setColspan(1);cell.setBorder(0);table.addCell(cell);cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "電話:")));cell.setColspan(1);cell.setBorder(0);table.addCell(cell);cell.setBorder(Rectangle.NO_BORDER);cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "電話:")));cell.setColspan(1);cell.setBorder(0);table.addCell(cell);doc.add(table);}}生成PDF并加斜水印
加入maven依賴
<!--itexrpdf解決中文水印不顯示--><dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version></dependency>Util還是使用的上方Util
public static void main(String[] args) {System.out.println("===========start=============");try {Document doc = createPdf("原PDF路徑");//生成 合同文件createFile(doc);doc.close();// 待加水印的文件PdfReader reader = new PdfReader("原PDF路徑");// 加完水印的文件PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("需要生成的水印PDF路徑"));int total = reader.getNumberOfPages() + 1;PdfContentByte content;// 設置透明度PdfGState gs = new PdfGState();gs.setFillOpacity(0.3f);// 設置字體 如果水印字體有中文,必須添加BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);// 循環對每頁插入水印for (int i = 1; i < total; i++){// 水印的起始content = stamper.getOverContent(i);content.setGState(gs);content.setFontAndSize(base, 32);// 開始content.beginText();// 設置顏色 默認為黑色content.setColorFill(BaseColor.BLACK);// 開始寫入水印 ,參數二為水印文字,三為x坐標,四為y坐標,五為角度content.showTextAligned(Element.ALIGN_MIDDLE, "什么哈哈哈哈哈", 50, 0, 45);content.showTextAligned(Element.ALIGN_MIDDLE, "什么哈哈哈哈哈", 50, 200, 45);content.showTextAligned(Element.ALIGN_MIDDLE, "什么哈哈哈哈哈", 50, 400, 45);content.showTextAligned(Element.ALIGN_MIDDLE, "什么哈哈哈哈哈", 50, 600, 45);content.showTextAligned(Element.ALIGN_MIDDLE, "什么哈哈哈哈哈", 50, 800, 45);content.showTextAligned(Element.ALIGN_MIDDLE, "什么哈哈哈哈哈", 350, 0, 45);content.showTextAligned(Element.ALIGN_MIDDLE, "什么哈哈哈哈哈", 350, 200, 45);content.showTextAligned(Element.ALIGN_MIDDLE, "什么哈哈哈哈哈", 350, 400, 45);content.showTextAligned(Element.ALIGN_MIDDLE, "什么哈哈哈哈哈", 350, 600, 45);content.showTextAligned(Element.ALIGN_MIDDLE, "什么哈哈哈哈哈", 350, 800, 45);content.endText();}stamper.close();reader.close();} catch (Exception e) {e.printStackTrace();}System.out.println("===========end=============");}/*** 創建一個pdf并打開* @param path pdf路徑*/public static Document createPdf(String path) throws DocumentException, IOException {//頁面大小//Rectangle rect = new Rectangle(PageSize.A4.rotate());//文檔橫方向Rectangle rect = new Rectangle(PageSize.A4);//文檔豎方向//如果沒有則創建File saveDir = new File(path);File dir = saveDir.getParentFile();if (!dir.exists()) {dir.mkdirs();}Document doc = new Document(rect);PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(path));//PDF版本(默認1.4)writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2);//文檔屬性doc.addTitle("Title@wpixel");doc.addAuthor("Author@wpixel");doc.addSubject("Subject@wpixel");doc.addKeywords("Keywords@wpixel");doc.addCreator("Creator@wpixel");//頁邊空白doc.setMargins(40, 40, 40, 40);//打開文檔doc.open();return doc;}public static void createFile(Document doc) throws DocumentException{Calendar calendar = Calendar.getInstance();int year = calendar.get(Calendar.YEAR);int month = calendar.get(Calendar.MONTH) + 1;int day = calendar.get(Calendar.DATE);doc.add(PdfFontUtils.getFont(4, " "));doc.add(PdfFontUtils.getFont(1, "××××××調查表"));doc.add(PdfFontUtils.getFont(2, "("+year+"年度)"));doc.add(PdfFontUtils.getFont(3, "×××全稱(蓋章):"+"哈哈哈哈哈哈哈哈哈"));doc.add(PdfFontUtils.getFont(3, "填報時間: "+year+" 年 "+month+" 月 "+day+" 日"));doc.add(PdfFontUtils.getFont(4, "××××××××××"));}生成前效果為
生成后效果為
下載
完成水印后,直接添加
//下載pdf//downloadName 是下載后文件名稱用來中文處理//pdfCreate+waterName 是下載的路徑if (request.getHeader("User-Agent").toUpperCase().contains("MSIE") ||request.getHeader("User-Agent").toUpperCase().contains("TRIDENT")|| request.getHeader("User-Agent").toUpperCase().contains("EDGE")) {downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8");} else {//非IE瀏覽器的處理:downloadName = new String(downloadName.getBytes("UTF-8"), "ISO-8859-1");}response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + downloadName + "\"");FileInputStream fileInputStream = null;fileInputStream = new FileInputStream(pdfCreate+waterName);IoUtil.copy(fileInputStream , response.getOutputStream());fileInputStream.close();圖片導出pdf
工具類
import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Image; import com.itextpdf.text.PageSize; import com.itextpdf.text.pdf.PdfWriter; import com.minyeling.xxx.controller.ImageTransformPDF; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList;/*** 使用時,需要修改 ImageTransformPDF()函數中的輸入圖片和輸出pdf*/ public class PdfUtils {//為終極函數做鋪墊public static File Pdf(ArrayList<String> imageUrllist, String mOutputPdfFileName) {Document doc = new Document(PageSize.A4, 0, 0, 0, 0); //new一個pdf文檔try {PdfWriter.getInstance(doc, new FileOutputStream(mOutputPdfFileName)); //pdf寫入doc.open();//打開文檔for (int i = 0; i < imageUrllist.size(); i++) { //循環圖片List,將圖片加入到pdf中doc.newPage(); //在pdf創建一頁Image png1 = Image.getInstance(imageUrllist.get(i)); //通過文件路徑獲取imagefloat heigth = png1.getHeight();float width = png1.getWidth();int percent = getPercent2(heigth, width);png1.setAlignment(Image.MIDDLE);png1.scalePercent(percent + 3);// 表示是原來圖像的比例;doc.add(png1);}doc.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (DocumentException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}File mOutputPdfFile = new File(mOutputPdfFileName); //輸出流if (!mOutputPdfFile.exists()) {mOutputPdfFile.deleteOnExit();return null;}return mOutputPdfFile; //反回文件輸出流}public static int getPercent(float h, float w) {int p = 0;float p2 = 0.0f;if (h > w) {p2 = 297 / h * 100;} else {p2 = 210 / w * 100;}p = Math.round(p2);return p;}public static int getPercent2(float h, float w) {int p = 0;float p2 = 0.0f;p2 = 530 / w * 100;p = Math.round(p2);return p;}/*** @Description: 通過圖片路徑及生成pdf路徑,將圖片轉成pdf*/public static void imgOfPdf(String filepath, String imgUrl) {try {ArrayList<String> imageUrllist = new ArrayList<String>(); //圖片list集合String[] imgUrls = imgUrl.split(",");for (int i=0; i<imgUrls.length; i++) {imageUrllist.add(imgUrls[i]);}String pdfUrl = filepath; //輸出pdf文件路徑File file = this.Pdf(imageUrllist, pdfUrl);//生成pdffile.createNewFile();} catch (IOException e) {e.printStackTrace();}} }使用方法
public static void ImageTransformPDF(){PdfUtils.imgOfPdf("輸出pdf的路徑和文件名(帶后綴)", "需要轉化成pdf的文件的路徑");}PDF分頁
操作docment對象
doc.newPage();PDF合并單元格
cell = new PdfPCell();//合并這個cell的第一行開始的兩列 setRowspan是合并行,setColspan是合并列cell.setRowspan(1);cell.setColspan(2);table.addCell(cell);單元格文字水平居中、垂直居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中 cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中設置單元格高度
cell.setFixedHeight(40f);總結
以上是生活随笔為你收集整理的Java使用itextpdf生成PDF文件并添加斜面水印并完成下载(图片导出pdf)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 春节过后,外贸人如何快速抓住采购旺季,高
- 下一篇: MQTT Java 客户端