1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > java给多个不同文档(doc docx jpg png tif)合并成一个pdf文档 并添加设置页面权限 和水印

java给多个不同文档(doc docx jpg png tif)合并成一个pdf文档 并添加设置页面权限 和水印

时间:2023-09-22 08:50:37

相关推荐

java给多个不同文档(doc docx jpg png tif)合并成一个pdf文档 并添加设置页面权限 和水印

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

前言

对pdf文档的合并转换 加水印等 多个文件转pdf 还有改变图片的尺寸大小

依赖包可以自己去找下

代码

package com.yilu.archives.doc.utils;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;

import com.documents4j.api.DocumentType;

import com.documents4j.api.IConverter;

import com.documents4j.job.LocalConverter;

import com.itextpdf.text.Font;

import com.itextpdf.text.Image;

import com.itextpdf.text.Rectangle;

import com.itextpdf.text.*;

import com.itextpdf.text.pdf.*;

import com.spire.pdf.PdfDocument;

import com.spire.pdf.PdfPageBase;

import com.spire.pdf.PdfPageSize;

import com.spire.pdf.graphics.PdfMargins;

import com.yilu.archives.doc.dao.entity.TArchivesFileTransition;

import com.yilu.archives.doc.dao.mapper.TArchivesFileTransitionMapper;

import org.apache.pdfbox.multipdf.PDFMergerUtility;

import org.springframework.beans.factory.annotation.Autowired;

import javax.imageio.ImageIO;

import java.awt.*;

import java.awt.geom.Dimension2D;

import java.awt.geom.Point2D;

import java.awt.image.BufferedImage;

import java.io.*;

import java.security.MessageDigest;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.List;

import java.util.Random;

public class PdfFileUtils {

@Autowired

TArchivesFileTransitionMapper archivesFileTransitionMapper;

/**

*

* @param files 要合并的文件路径

* @param mergePath 存放路径的文件夹

* @throws FileNotFoundException

*/

public static String MergePdf(List<String> files,String mergePath) throws FileNotFoundException {

//pdf合并工具类

PDFMergerUtility mergePdf = new PDFMergerUtility();

//合并pdf生成的文件名

String destinationFileName =new Date().getTime()+".pdf";

//这是需要合并的PDF文件

// String filePath = targetPath;

// 合并后pdf存放路径

String bothPath = mergePath;

File file3 = new File(bothPath);

try{

if(!file3.exists()){

file3.mkdirs();

}

}catch(Exception e1){

e1.printStackTrace();

}

//循环拿到要合成的路径

for (String file : files){

mergePdf.addSource(file);

}

//设置合并生成pdf文件名称

mergePdf.setDestinationFileName(bothPath + File.separator + destinationFileName);

//合并pdf

try {

mergePdf.mergeDocuments();

//合并pdf文件后 进行页面大小设置

//mergePdf.getDestinationFileName() 当前合并pdf文件的名称

//inpath 目前测试的路径 后期要修改 是绝对路径

Random r = new Random();

int anInt = r.nextInt(5);

String path=mergePath+"/"+anInt+".pdf";

//修改图片的样式

//String amendpage = amendpage(mergePdf.getDestinationFileName(), destinationFileName);

//创建PdfDocument对象

PdfDocument originalDoc = new PdfDocument();

//加载PDF文件

originalDoc.loadFromFile(mergePdf.getDestinationFileName());

//创建一个新的PdfDocument实例

PdfDocument newDoc = new PdfDocument();

//遍历所有PDF 页面

Dimension2D dimension2D = new Dimension();

for (int i = 0; i < originalDoc.getPages().getCount(); i++) {

PdfPageBase page = originalDoc.getPages().get(i);

PdfMargins margins = new PdfMargins(0,0,0,0);

//设置新文档的页面大小为A4

PdfPageBase newPage = newDoc.getPages().add(PdfPageSize.Arch_A, margins);

//调整画布,设置内容也根据页面的大小进行缩放

double wScale = (PdfPageSize.Arch_A.getWidth()) / PdfPageSize.Arch_A.getWidth();

double hScale = (PdfPageSize.Arch_A.getHeight()) / PdfPageSize.Arch_A.getHeight();

newPage.getCanvas().translateTransform(wScale, hScale);

//复制原文档的内容到新文档

newPage.getCanvas().drawTemplate(page.createTemplate(), new Point2D.Float());

//保存PDF

newDoc.saveToFile(path);

}

newDoc.close();

return path;

}catch (IOException e) {

e.printStackTrace();

return null;//返回空 给controller判断

}finally {

if(files!=null){

PdfFileUtils.delFiles(files);

}

if(mergePdf.getDestinationFileName()!=null){

PdfFileUtils.delFile(mergePdf.getDestinationFileName());

}

}

}

//传入参数,并进行文档格式转换 outpath:绝对路径

public static String eqfile(String outpath) {

String file = isImageFile(outpath);

return file;

}

/**

*

* @param outpath 要被转换的路径

* @fileNumber 档号 到时候要传入

* @return

*/

public static String isImageFile(String outpath) { //判断格式是否正确

//截取文档的后缀

String ext = outpath.substring(outpath.lastIndexOf(".") + 1); //截取点后面的字符串 lastIndexOf返回最后一次出现的位置

String s="";

// String pdfPath="";

if ("JPG".equalsIgnoreCase(ext)) {

//修改图片宽高

try {

changeSize(650,860,outpath);

} catch (Exception e) {

e.printStackTrace();

}

//转换pdf文档

s = transitionJpg(outpath, null);

}

if ("PDF".equalsIgnoreCase(ext)) {

s=outpath;

}

if ("DOC".equalsIgnoreCase(ext)) {

s = transitionDoc(outpath, null);

}

if ("DOCX".equalsIgnoreCase(ext)) {

s = transitionDocx(outpath, null);

}

if ("TIF".equalsIgnoreCase(ext)) {

try {

changeSize(650,860,outpath);

} catch (Exception e) {

e.printStackTrace();

}

s = transitionJpg(outpath, null);

}

if ("PNG".equalsIgnoreCase(ext)) {

try {

changeSize(650,860,outpath);

} catch (Exception e) {

e.printStackTrace();

}

s=transitionJpg(outpath, null);

}

return s;

}

/**

* doc转换成pdf 并保存,然后在删除原先的doc文件

* @param inputPath 后台找到存储的文件 传过来转换

* @param fileNumber 根据这个档号生成文件夹

* @return

*/

public static String transitionDoc(String inputPath, String fileNumber) {

//转义\\ 分割格式

String[] str = inputPath.split("\\.");

//拼接新的路径

String outputFile=str[0].toString()+".pdf";

try {

//合成

InputStream docxInputStream = new FileInputStream(inputPath);

OutputStream outputStream = new FileOutputStream(outputFile);

IConverter converter = LocalConverter.builder().build();

converter.convert(docxInputStream).as(DocumentType.DOC).to(outputStream).as(DocumentType.PDF).execute();

outputStream.close();

} catch (Exception e) {

e.printStackTrace();

}

//返回新的路径去保存

return outputFile;

}

/**

* docx转换成pdf

* @param inputpath 后台传过来的文档存放路径 去转换

* @param fileNumber

* @return

*/

public static String transitionDocx(String inputpath,String fileNumber) {

//转义\\ 分割格式

String[] str = inputpath.split("\\.");

//拼接新的路径

String outputFile=str[0].toString()+".pdf";

try {

InputStream docxInputStream = new FileInputStream(inputpath);

OutputStream outputStream = new FileOutputStream(outputFile);

IConverter converter = LocalConverter.builder().build();

converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();

outputStream.close();

} catch (Exception e) {

e.printStackTrace();

}

return outputFile;

}

/**

* jpg转换成pdf,和tif转换成pdf 同用一个

* @param imagePath 后台传输过来的jpg路径

* @return

*/

public static String transitionJpg(String imagePath,String fileNumber) {

//转义\\ 分割格式

String[] str = imagePath.split("\\.");

//拼接新的路径

String outputFile=str[0].toString()+".pdf";

try {

BufferedImage img = ImageIO.read(new File(imagePath));

FileOutputStream fos = new FileOutputStream(outputFile);

Document doc = new Document(null, 0, 0, 0, 0);

doc.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));

Image image = Image.getInstance(imagePath);

//设置图片的缩放

//image.scalePercent(100);

PdfWriter.getInstance(doc, fos);

doc.open();

doc.add(image);

doc.close();

} catch (IOException e) {

e.printStackTrace();

} catch (BadElementException e) {

e.printStackTrace();

} catch (DocumentException e) {

e.printStackTrace();

}

return outputFile;

}

/**

* java修改pdf文档页面的宽高

* 参数 inPath 修改后的新的绝对路径

* 参数 outPath pdf的路径

* */

public static String amendpage(String outPath,String inPath){

//创建PdfDocument对象

PdfDocument originalDoc = new PdfDocument();

//加载PDF文件

originalDoc.loadFromFile(outPath);

//创建一个新的PdfDocument实例

PdfDocument newDoc = new PdfDocument();

//遍历所有PDF 页面

Dimension2D dimension2D = new Dimension();

for (int i = 0; i < originalDoc.getPages().getCount(); i++) {

PdfPageBase page = originalDoc.getPages().get(i);

PdfMargins margins = new PdfMargins(0,0,0,0);

//设置新文档的页面大小为A4

PdfPageBase newPage = newDoc.getPages().add(PdfPageSize.Arch_A, margins);

//调整画布,设置内容也根据页面的大小进行缩放

double wScale = (PdfPageSize.Arch_A.getWidth()) / PdfPageSize.Arch_A.getWidth();

double hScale = (PdfPageSize.Arch_A.getHeight()) / PdfPageSize.Arch_A.getHeight();

newPage.getCanvas().translateTransform(wScale, hScale);

//复制原文档的内容到新文档

newPage.getCanvas().drawTemplate(page.createTemplate(), new Point2D.Float());

//保存PDF

newDoc.saveToFile(outPath);

}

newDoc.close();

return outPath;

}

/**

*

* @param count 默认从1开始 在添加权限页面时设置

* @param srcFilePath 要加水印的pdf文档

* @param descFilePath 然后生成一个新的pdf文档

* @param textWatermark 加水印的档案馆信息

* @param textWaterpath 用户的信息 和修改的时间

* @return

* @throws IOException

* @throws DocumentException

*/

public static boolean pdfInsertWatermark(Integer count,String srcFilePath,String descFilePath,

String textWatermark,String textWaterpath,

Integer state)throws Exception {

PdfReader reader = new PdfReader(srcFilePath);

PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(descFilePath));

PdfGState gs = new PdfGState();

//统一的系统文字格式

BaseFont font = BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

gs.setFillOpacity(0.2f);// 设置透明度

// 设置覆盖全页的文字格式

Font f=new Font(font,10);

Phrase p = new Phrase(textWaterpath,f);

int total = reader.getNumberOfPages() + 1;

PdfContentByte content;

//为每一页加上档案馆的水印

for (int i = count; i < total; i++) {

content = stamper.getOverContent(i);

content.beginText();

content.setGState(gs);

if(state==0){

content.setColorFill(BaseColor.RED); //水印颜色

}

if(state==1){

content.setColorFill(BaseColor.GRAY);

}

content.setFontAndSize(font, 40); //水印字体样式和大小

content.showTextAligned(Element.ALIGN_CENTER,textWatermark, 300, 300, 45); //水印内容和水印位置

//为每一页加上用户资料和修改的时间 以防档案泄露

for (int y = 0; y < 10; y++) {

for (int x = 0; x < 8; x++) {

// 水印文字成0度角倾斜

ColumnText.showTextAligned(content, Element.ALIGN_CENTER, p, 158 * y,80 + 140 * x , 45);

}

}

content.endText();

}

stamper.close();//关闭流 防止删除删除不了

reader.close();

reader=null;

return true;

}

/**

* 改变图片的尺寸

*

* @param newWidth, newHeight, path

* @return boolean

*/

public static void changeSize(int newWidth, int newHeight, String path) {

BufferedInputStream in = null;

try {

in = new BufferedInputStream(new FileInputStream(path));

//字节流转图片对象

BufferedImage bi = ImageIO.read(in);

//构建图片流

BufferedImage tag = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);

//绘制改变尺寸后的图

tag.getGraphics().drawImage(bi, 0, 0, newWidth, newHeight, null);

//输出流

BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(path));

//JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

//encoder.encode(tag);

ImageIO.write(tag, "JPG", out);

in.close();

out.close();

} catch (IOException e) {

e.printStackTrace();

}

}

//删除多个文件文件

public static void delFiles(List<String> paths){

for (int i=0;i<paths.size();i++){

File file=new File(paths.get(i));

if (file.exists()) {

file.delete();

}

}

}

public static void delFile(String paths){

File file=new File(paths);

if (file.exists()&&file.isFile()){

file.delete();

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。