Java使用itextpdf生成PDF文件并添加斜面水印并完成下载(图片导出pdf)
生活随笔
收集整理的這篇文章主要介紹了
Java使用itextpdf生成PDF文件并添加斜面水印并完成下载(图片导出pdf)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
提供自己的一些工具類(lèi)
生成PDF文件所需的jar包
引入maven依賴(lài)
生成PDF
創(chuàng)建一個(gè)PDF字體樣式工具類(lèi)
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 {/*** 設(shè)置字體* * windows路徑字體* FONT_TYPE=C:/Windows/fonts/simsun.ttc* linux路徑字體 宋體 (如果沒(méi)有這個(gè)字體文件,就將windows的字體傳上去)* FONT_TYPE=/usr/share/fonts/win/simsun.ttc*///可以用配置文件讀取//獲取配置//PropertiesLoader pl = new PropertiesLoader("/config/config.properties"); //拼接文件web訪問(wèn)路徑//String FONT_TYPE = pl.getProperty("FONT_TYPE"); //解決中文問(wèn)題 幼圓baseFont = BaseFont.createFont("C:/Windows/fonts/simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//在linux解決中文問(wèn)題 如果沒(méi)有語(yǔ)言包需要自己下載//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();}}/*** 文檔超級(jí) 排版* @param type 1-標(biāo)題 2-標(biāo)題一 3-標(biāo)題二 4-標(biāo)題三 5-正文 6-左對(duì)齊*/public static Paragraph getFont(int type, String text){Font font = new Font(baseFont);if(1 == type){//1-標(biāo)題font.setSize(16f);font.setStyle(Font.BOLD);} else if(2 == type){//2-標(biāo)題一font.setSize(16f);font.setStyle(Font.BOLD);} else if(3 == type){//3-標(biāo)題二font.setSize(14f);font.setStyle(Font.BOLD);} else if(4 == type){//4-標(biāo)題三font.setSize(14f);} else if(5 == type){//5-正文font.setSize(10.5f);} else if(6 == type){//6-左對(duì)齊font.setSize(10.5f);} else {font.setSize(10.5f);//默認(rèn)大小}//注: 字體必須和 文字一起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-標(biāo)題一paragraph.setAlignment(Element.ALIGN_JUSTIFIED); //默認(rèn)paragraph.setSpacingBefore(2f);//上間距paragraph.setSpacingAfter(2f);//下間距} else if(3 == type){paragraph.setSpacingBefore(2f);//上間距paragraph.setSpacingAfter(1f);//下間距} else if(4 == type){//4-標(biāo)題三//paragraph.setAlignment(Element.ALIGN_RIGHT);//右對(duì)齊 paragraph.setSpacingBefore(2f);//上間距paragraph.setSpacingAfter(2f);//下間距} else if(5 == type){paragraph.setAlignment(Element.ALIGN_JUSTIFIED); paragraph.setFirstLineIndent(24);//首行縮進(jìn)paragraph.setSpacingBefore(1f);//上間距paragraph.setSpacingAfter(1f);//下間距} else if(6 == type){//左對(duì)齊paragraph.setAlignment(Element.ALIGN_LEFT); paragraph.setSpacingBefore(1f);//上間距paragraph.setSpacingAfter(1f);//下間距}//paragraph.setIndentationLeft(50);//整體縮進(jìn)左邊//paragraph.setFirstLineIndent(40);//首行縮進(jìn)return paragraph;} }創(chuàng)建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=============");}/*** 創(chuàng)建一個(gè)pdf并打開(kāi)* @param outpath pdf路徑*/public static Document createPdf(String outpath) throws DocumentException, IOException{//頁(yè)面大小//Rectangle rect = new Rectangle(PageSize.A4.rotate());//文檔橫方向Rectangle rect = new Rectangle(PageSize.A4);//文檔豎方向//如果沒(méi)有則創(chuàng)建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版本(默認(rèn)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");//頁(yè)邊空白doc.setMargins(40, 40, 40, 40);//打開(kāi)文檔doc.open();return doc;}public static void createFile(Document doc) throws DocumentException{doc.add(PdfFontUtils.getFont(1, "合作協(xié)議"));doc.add(PdfFontUtils.getFont(6, "甲方:"));doc.add(PdfFontUtils.getFont(6, "乙方:"));doc.add(PdfFontUtils.getFont(6, "時(shí)間:"));doc.add(PdfFontUtils.getFont(6, "地點(diǎn):"));Paragraph text05 = PdfFontUtils.getFont(5, "《根據(jù)中華人民共和國(guó)合同法》的有關(guān)規(guī)定,經(jīng)甲、乙雙方友好協(xié)商,本著長(zhǎng)期平等合作.....吧啦吧啦吧啦吧啦吧啦吧啦吧啦吧啦");doc.add(text05);//一、合作方式及條件doc.add(PdfFontUtils.getFont(2, "一、合作方式及條件"));doc.add(PdfFontUtils.getFont(5, "1.雙方根據(jù)國(guó)家法律規(guī)定建立合作關(guān)系,雙方嚴(yán)格遵守和執(zhí)行國(guó)家各項(xiàng)方針政策和有關(guān)法律、法規(guī)和條例規(guī)定。 "));doc.add(PdfFontUtils.getFont(5, "2.雙方嚴(yán)格按照《中華人民共和國(guó)招標(biāo)投標(biāo)法》及相關(guān)規(guī)定實(shí)施合作。 "));doc.add(PdfFontUtils.getFont(5, "3.雙方本著密切配合、分工協(xié)作、保證質(zhì)量、按期完成的原則,共同做好工作。 "));//二、權(quán)利義務(wù)doc.add(PdfFontUtils.getFont(2, "二、權(quán)利義務(wù)"));doc.add(PdfFontUtils.getFont(5, "1.雙方根據(jù)國(guó)家法律規(guī)定建立合作關(guān)系,雙方嚴(yán)格遵守和執(zhí)行國(guó)家各項(xiàng)方針政策和有關(guān)法律、法規(guī)和條例規(guī)定。 "));doc.add(PdfFontUtils.getFont(5, "2.雙方嚴(yán)格按照《中華人民共和國(guó)招標(biāo)投標(biāo)法》及相關(guān)規(guī)定實(shí)施合作。 "));doc.add(PdfFontUtils.getFont(5, "3.雙方本著密切配合、分工協(xié)作、保證質(zhì)量、按期完成的原則,共同做好工作。 "));//三、其他doc.add(PdfFontUtils.getFont(2, "三、其他"));doc.add(PdfFontUtils.getFont(5, "1.雙方根據(jù)國(guó)家法律規(guī)定建立合作關(guān)系,雙方嚴(yán)格遵守和執(zhí)行國(guó)家各項(xiàng)方針政策和有關(guān)法律、法規(guī)和條例規(guī)定。 "));doc.add(PdfFontUtils.getFont(5, "2.雙方嚴(yán)格按照《中華人民共和國(guó)招標(biāo)投標(biāo)法》及相關(guān)規(guī)定實(shí)施合作。 "));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, "法定代表人或負(fù)責(zé)人簽章")));cell.setColspan(1);cell.setBorder(0);table.addCell(cell);cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "法定代表人或負(fù)責(zé)人簽章")));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, "開(kāi)戶銀行:")));cell.setColspan(1);cell.setBorder(0);table.addCell(cell);cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "開(kāi)戶銀行:")));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, "授權(quán)代理人:")));cell.setColspan(1);cell.setBorder(0);table.addCell(cell);cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "項(xiàng)目經(jīng)理:")));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依賴(lài)
<!--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;// 設(shè)置透明度PdfGState gs = new PdfGState();gs.setFillOpacity(0.3f);// 設(shè)置字體 如果水印字體有中文,必須添加BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);// 循環(huán)對(duì)每頁(yè)插入水印for (int i = 1; i < total; i++){// 水印的起始content = stamper.getOverContent(i);content.setGState(gs);content.setFontAndSize(base, 32);// 開(kāi)始content.beginText();// 設(shè)置顏色 默認(rèn)為黑色content.setColorFill(BaseColor.BLACK);// 開(kāi)始寫(xiě)入水印 ,參數(shù)二為水印文字,三為x坐標(biāo),四為y坐標(biāo),五為角度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=============");}/*** 創(chuàng)建一個(gè)pdf并打開(kāi)* @param path pdf路徑*/public static Document createPdf(String path) throws DocumentException, IOException {//頁(yè)面大小//Rectangle rect = new Rectangle(PageSize.A4.rotate());//文檔橫方向Rectangle rect = new Rectangle(PageSize.A4);//文檔豎方向//如果沒(méi)有則創(chuàng)建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版本(默認(rèn)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");//頁(yè)邊空白doc.setMargins(40, 40, 40, 40);//打開(kāi)文檔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, "××××××調(diào)查表"));doc.add(PdfFontUtils.getFont(2, "("+year+"年度)"));doc.add(PdfFontUtils.getFont(3, "×××全稱(chēng)(蓋章):"+"哈哈哈哈哈哈哈哈哈"));doc.add(PdfFontUtils.getFont(3, "填報(bào)時(shí)間: "+year+" 年 "+month+" 月 "+day+" 日"));doc.add(PdfFontUtils.getFont(4, "××××××××××"));}生成前效果為
生成后效果為
下載
完成水印后,直接添加
//下載pdf//downloadName 是下載后文件名稱(chēng)用來(lái)中文處理//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();圖片導(dǎo)出pdf
工具類(lèi)
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;/*** 使用時(shí),需要修改 ImageTransformPDF()函數(shù)中的輸入圖片和輸出pdf*/ public class PdfUtils {//為終極函數(shù)做鋪墊public static File Pdf(ArrayList<String> imageUrllist, String mOutputPdfFileName) {Document doc = new Document(PageSize.A4, 0, 0, 0, 0); //new一個(gè)pdf文檔try {PdfWriter.getInstance(doc, new FileOutputStream(mOutputPdfFileName)); //pdf寫(xiě)入doc.open();//打開(kāi)文檔for (int i = 0; i < imageUrllist.size(); i++) { //循環(huán)圖片List,將圖片加入到pdf中doc.newPage(); //在pdf創(chuàng)建一頁(yè)Image png1 = Image.getInstance(imageUrllist.get(i)); //通過(guò)文件路徑獲取imagefloat heigth = png1.getHeight();float width = png1.getWidth();int percent = getPercent2(heigth, width);png1.setAlignment(Image.MIDDLE);png1.scalePercent(percent + 3);// 表示是原來(lái)圖像的比例;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: 通過(guò)圖片路徑及生成pdf路徑,將圖片轉(zhuǎn)成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的路徑和文件名(帶后綴)", "需要轉(zhuǎn)化成pdf的文件的路徑");}PDF分頁(yè)
操作docment對(duì)象
doc.newPage();PDF合并單元格
cell = new PdfPCell();//合并這個(gè)cell的第一行開(kāi)始的兩列 setRowspan是合并行,setColspan是合并列cell.setRowspan(1);cell.setColspan(2);table.addCell(cell);單元格文字水平居中、垂直居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中 cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中設(shè)置單元格高度
cell.setFixedHeight(40f);總結(jié)
以上是生活随笔為你收集整理的Java使用itextpdf生成PDF文件并添加斜面水印并完成下载(图片导出pdf)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 春节过后,外贸人如何快速抓住采购旺季,高
- 下一篇: MQTT Java 客户端