Java使用itextpdf生成PDF文件并添加斜面水印并完成下载(图片导出pdf)

提供自己的一些工具类
生成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);//默认大小
        }
        //注: 字体必须和 文字一起new
        Paragraph 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)); //通过文件路径获取image
                float 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);//生成pdf
            file.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);

PdfPCell详解

cell.setFixedHeight(40f);	//设置单元格高度
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //设置单元格文字垂直居中
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //设置单元格文字水平居中
cell.disableBorderSide(1);  //隐藏单元格上边框
cell.disableBorderSide(2);  //隐藏单元格下边框
cell.disableBorderSide(3);  //隐藏单元格上、下边框
cell.disableBorderSide(4);  //隐藏单元格左边框
cell.disableBorderSide(5);  //隐藏单元格左、上边框
cell.disableBorderSide(6);  //隐藏单元格左、下边框
cell.disableBorderSide(7);  //隐藏单元格左、上、下边框
cell.disableBorderSide(8);  //隐藏单元格右边框
cell.disableBorderSide(9);  //隐藏单元格右、上边框
cell.disableBorderSide(10); //隐藏单元格右、下边框
cell.disableBorderSide(11); //隐藏单元格右、上、下边框
cell.disableBorderSide(12); //隐藏单元格左、右边框
cell.disableBorderSide(13); //隐藏单元格上、左、右边框
cell.disableBorderSide(14); //隐藏单元格下、左、右边框
cell.disableBorderSide(15); //隐藏单元格全部
cell.setRowspan(1); //跨1行 可以与Colspan一起使用,合并第几行的第几列
cell.setColspan(2); //跨2列 可以与Rowspan一起使用,合并第几行的第几列
cell.setBackgroundColor(BaseColor.CYAN); //设置背景色
cell.setMinimumHeight(30f); //设置最小高度
cell.setBorder(Rectangle.NO_BORDER); //设置无边框

猜你喜欢

转载自blog.csdn.net/whatevery/article/details/121271736