提供自己的一些工具类
生成PDF文件所需的jar包

引入maven依赖

     <!--itextpdf--><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.11</version></dependency>

生成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)相关推荐

  1. java pdf添加透明水印_如何在PDF文件中添加透明水印

    原标题:如何在PDF文件中添加透明水印 有些文件添加水印,但是又不想水印影响文件的使用有时候会设置透明水印,那么PDF怎么设置透明水印呢,应该有很多的小伙伴们都很好奇应该怎么做吧,接下来就为大家分享一 ...

  2. java pdf添加透明水印_如何使用PDF编辑工具在PDF文件中添加透明水印

    PDF 文件在修改编辑的时候会使用到 PDF 编辑工具,不管是工 作中还是生活中,都会使用到 PDF 文件,当我们需要给 PDF 文件添 加透明水印时,该怎么操作呢,是不是有很多的小伙伴也很好奇, 那 ...

  3. java操作PDF文件,可支持分页、合并、图片转PDF等

    java操作PDF,有一个很好用的工具--pdfbox.只需要引入依赖,即可使用. <dependency><groupId>org.apache.pdfbox</gro ...

  4. java用itextPDF生成PDF文件保存至本地并上传至ftp服务器

    标题java用itextPDF生成PDF文件保存至本地并上传至ftp服务器 所需jar :itext-asian-5.2.0.jar,itextpdf-5.5.5.jar,commons-net-3. ...

  5. python使用fpdf生成pdf文件并添加页眉和页脚

    python使用fpdf生成pdf文件并添加页眉和页脚 目录 python使用fpdf生成pdf文件并添加页眉和页脚 #加入页眉header示例

  6. python读取pdf文档书签 bookmark_用Python为PDF文件批量添加书签

    平时看一些大部头的技术书籍,大多数都是PDF版的,而且有一些书籍是影印扫描版的,几百上千页的书,没有任何书签,想要找到一个章节的位置非常费劲.那么就想,能不能搞一个工具,来自动地为这些大部头的PDF书 ...

  7. eclipse编译java项目class文件_动态编译 Java 代码以及生成 Jar 文件

    导读: 最近在看 Flink 源码的时候发现到一段实用的代码,该代码实现了 java 动态编译以及生成 jar 文件.将其进行改进后可以应用到我们的平台上,实现在平台页面上编写 java 代码语句,提 ...

  8. JAVA 根据模板生成doc文件

    JAVA 根据模板生成doc文件 需求 根据模板生成对应的doc文档,文档内容动态填充. 实现 1.将doc模板转换为ftl文件,放入项目中 1.1 首先将模板另存为xml文件 1.2 更改xml文件 ...

  9. PDF文件如何添加页面或插入其他PDF页面

    在处理PDF文件的时候如果要在文档中添加插入一个页面,或者是插入其他pdf文件页面的话该怎样操作?编辑PDF文件是否像office文档那样操作简单?下面就来讲下PDF文件怎么添加页面的. ​ 因为PD ...

  10. PDF文件如何添加签名

    PDF文件如何添加签名?在我们平常的工作中,许多文件都需要签名确认执行.如果有一份PDF文件需要签名,屏幕前的你知道应该如何操作吗?如果你并不了解PDF文件应该如何添加签名,那么没关系,继续往下阅读你 ...

最新文章

  1. 在 tensorflow 和numpy 中矩阵的加法
  2. win7组策略-计算机配置,win7系统组策略设置系统配置模块的操作方法
  3. (总结)HTTP常见错误返回代码
  4. python选择题题库百度文库_大学Python程序题题库
  5. 【Elasticsearch】Elasticsearch 集群健康值黄色 解决方案 或者 分片 未分配
  6. 《基于MFC的OpenGL编程》Part 8 Colors
  7. SQL Server中的窗口函数
  8. fastjson使用-- @JSONField使用(转)
  9. 华为/华三IS-IS多区域配置及其路由优化
  10. python中showinfo什么意思_在Python中Windows – 在startupinfo中使用wShowWindow的Popen不会影响显示...
  11. UBUNTU配置samba
  12. Python学习:Python分析中国人口(一)爬取数据
  13. stm32f4的数字摄像头接口(DCMI)使用
  14. List of music used by Apple Inc.
  15. 计算机科学基础word实验一,【实验2】熟悉WORD界面及其基本操作
  16. 计算机桌面图标有箭头,解决方案:如果计算机桌面图标上有箭头,该怎么办?如何删除计算机桌面图片[图形]上的箭头...
  17. 【杂记】全栈开发中碰到的一些问题及解决方法
  18. 靶机渗透----bulldog2
  19. 简单登录功能(一)token的使用
  20. element-ui table表格 增加合计行 和 表格列固定之后 滚动条无法滚动

热门文章

  1. java word搜索_java 实现word 文档的在线编辑. 以及全文关键字搜索和高亮显示
  2. 提供三份程序员简历模板
  3. libiconv的介绍
  4. 《深入理解JVM虚拟机》读书笔记(一)
  5. python二次开发ug_CAD二次开发(UG/Proe/其他) - 随笔分类 - 白途思 - 博客园
  6. java 坦克大战 素材_经典90坦克大战素材
  7. 不要放弃!“软考论文”一点也不难
  8. 傲腾™,企业应用加速利器!
  9. chrome插件Adblock Plus拓展程序
  10. linux java8 安装包(版本8u131-b11)