This commit is contained in:
2025-10-22 14:19:41 +08:00
commit e131e8b719
3326 changed files with 869357 additions and 0 deletions

View File

@@ -0,0 +1,671 @@
package com.point.strategy.common;
import com.itextpdf.text.*;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import org.springframework.util.ResourceUtils;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Date;
public class PdfFileHelper {
/*
水印间隔
* */
private static int interval = -100;
/**
* 归档章 单元格宽度
*/
public static int cell_width = 45;
/**
* 归档章 单元格高度
*/
public static int cell_height = 24;
/**
* 归档章 顶部距离(最小值38)
*/
public static int grid_top = 40;
/**
* 归档章 字体大小
*/
public static int font_size = 9;
/**
* 页号字体大小
*/
public static int pageno_font_size = 35;
/**
* PDF文件加盖归档章
*
* @param srcFile 源文件名
* @param tarFile 目标文件名称
* @param pageIndex 需要盖章的页序号 默认传1
* @param textContent 归档章内容
* @param direction 归档章位置1表示右边, 2表示中间 3表示左边
* @param scale 归档章放大系数,默认为1
*/
public static boolean Seal(String srcFile, String tarFile, int pageIndex, String[][] textContent,
String direction, double scale) {
//目标文件存在,则先删除
File _tarFile = new File(tarFile);
if (_tarFile.exists()) {
_tarFile.delete();
}
try {
PdfReader pdfReader = new PdfReader(srcFile);
PdfReader.unethicalreading = true;
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(tarFile));
int numberOfPages = pdfReader.getNumberOfPages();
if (numberOfPages < 1)
return false;
Rectangle rectangle = pdfReader.getPageSizeWithRotation(pageIndex);
PdfContentByte content = pdfStamper.getOverContent(pageIndex);
//表格默认宽度
int grid_col_width = (int) Math.ceil(cell_width * scale * 1.0);
//表格默认高度
int grid_col_height = (int) Math.ceil(cell_height * scale * 1.0);
//表格行合计
int grid_rows = 2;
//表格列合计
int grid_cols = 3;
//起点位置(居中)
float grid_left = (rectangle.getWidth() - grid_col_width * grid_cols) / 2;
float text_left = (rectangle.getWidth() - grid_col_width * grid_cols) / 2;
if ("1".equals(direction)) {
grid_left = rectangle.getWidth() - grid_col_width * grid_cols - 70;
text_left = rectangle.getWidth() - grid_col_width * grid_cols - 70;
} else if ("3".equals(direction)) {
grid_left = 10;
text_left = 10;
}
File ttfFile = ResourceUtils.getFile("classpath:SIMYOU.TTF");
BaseFont font = BaseFont.createFont(ttfFile.getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//BaseFont font = BaseFont.createFont("C:\\Users\\MI\\Desktop\\13\\SIMYOU.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
float width = rectangle.getWidth();
float height = rectangle.getHeight();
//全宗号,年度,件号
//机构或者问题,保管期限,总页数
PdfGState gs = new PdfGState();
gs.setFillOpacity(0.6f);
content.setGState(gs);
content.setGrayFill(0.3f);
//画网格
for (int r = 0; r < grid_rows; r++) {
for (int j = 0; j < grid_cols; j++) {
//画网格矩形
content.setColorStroke(BaseColor.RED);
float x = grid_left + grid_col_width * j;
float y = height - grid_top - grid_col_height * (r + 1);
content.rectangle(x, y, grid_col_width, grid_col_height);
content.setLineWidth(1f);
content.stroke();
//计算文本显示的矩形大小
float xxxx = font.getWidthPointKerned(textContent[r][j], (int) Math.ceil(font_size * scale * 1.0));
float yyyy = font.getAscentPoint(textContent[r][j], (int) Math.ceil(font_size * scale * 1.0));
int x1 = (int) ((grid_col_width - xxxx) / 2);
int y1 = (int) ((grid_col_height - yyyy) / 2);
//写入文本
content.beginText();
content.setColorFill(BaseColor.RED);
content.setFontAndSize(font, (int) Math.ceil(font_size * scale * 1.0));
content.setTextMatrix(0, 0);
//content.ShowTextAligned(Element.ALIGN_LEFT, textContent[r, j], text_left + grid_col_width*j +
// 2, height - grid_top - grid_col_height*r + 5, 0);
content.showTextAligned(Element.ALIGN_LEFT, textContent[r][j], x + x1, y + y1, 0);
content.endText();
}
}
pdfStamper.close();
pdfReader.close();
return true;
} catch (Exception ex) {
System.out.println(ex.getMessage());
return false;
}
}
/**
* 当前号码
*/
public static int CurrPageNo = 1;
/**
* 新绘制页码
*
* @param srcFile
* @param tarFile
* @return
*/
public static boolean pageNo(String srcFile, String tarFile) {
int currPageNo2 = 1;
//目标文件存在,则先删除
File _tarFile = new File(tarFile);
if (_tarFile.exists()) {
_tarFile.delete();
}
try {
PdfReader pdfReader = new PdfReader(srcFile);
PdfReader.unethicalreading = true;
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(tarFile));
int numberOfPages = pdfReader.getNumberOfPages();
File ttfFile = ResourceUtils.getFile("classpath:SIMYOU.TTF");
BaseFont font = BaseFont.createFont(ttfFile.getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// BaseFont font = BaseFont.createFont("C:\\Users\\MI\\Desktop\\13\\SIMYOU.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
PdfGState gs = new PdfGState();
gs.setFillOpacity(0.6f);
for (int i = 1; i <= numberOfPages; i++) {
Rectangle rectangle = pdfReader.getPageSizeWithRotation(i);
float pageWidth = rectangle.getWidth();
float pageHeight = rectangle.getHeight();
PdfContentByte content = pdfStamper.getOverContent(i);
content.setGState(gs);
content.setGrayFill(0.6f);
content.beginText();
content.setColorFill(BaseColor.BLACK);
content.setFontAndSize(font, pageno_font_size);
content.setTextMatrix(0, 0);
if (currPageNo2 % 2 == 1) {
content.showTextAligned(Element.ALIGN_LEFT, (currPageNo2++) + "", pageWidth - 40, pageHeight - 40,
0);
} else {
content.showTextAligned(Element.ALIGN_LEFT, (currPageNo2++) + "", 40, pageHeight - 40, 0);
}
content.endText();
}
pdfStamper.close();
pdfReader.close();
return true;
} catch (Exception ex) {
System.out.println(ex.getMessage());
return false;
}
}
/**
* 获取pdf文件总页数
* PdfReader
*
* @param f
* @return
*/
public static int getPdfPageCoun(String f) {
try {
PdfReader pdfReader = new PdfReader(f);
PdfReader.unethicalreading = true;
int numberOfPages = pdfReader.getNumberOfPages();
pdfReader.close();
return numberOfPages;
} catch (Exception ex) {
return 0;
}
}
/**
* Pdf文件加水印文字--居中
*
* @param srcFile
* @param markStr
* @return
*/
public static boolean setWaterMark(String srcFile,
String tarFile,
String markStr,
int fontSize,
String color,
int globalOblique) {
//目标文件存在,则先删除
File _tarFile = new File(tarFile);
if (_tarFile.exists()) {
_tarFile.delete();
}
try {
PdfReader pdfReader = new PdfReader(srcFile);
PdfReader.unethicalreading = true;
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(tarFile));
int numberOfPages = pdfReader.getNumberOfPages();
File ttfFile = ResourceUtils.getFile("classpath:SIMYOU.TTF");
BaseFont font = BaseFont.createFont(ttfFile.getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// BaseFont font = BaseFont.createFont("C:\\Users\\MI\\Desktop\\13\\SIMYOU.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
PdfGState gs = new PdfGState();
gs.setFillOpacity(0.6f);
for (int page = 1; page <= numberOfPages; page++) {
Rectangle rectangle = pdfReader.getPageSizeWithRotation(page);
float pageWidth = rectangle.getWidth();
float pageHeight = rectangle.getHeight();
PdfContentByte content = pdfStamper.getOverContent(page);
content.setGState(gs);
content.setGrayFill(0.6f);
//计算该文本某字体的矩形
float xxxx = font.getWidthPointKerned(markStr, fontSize);
float yyyy = font.getAscentPoint(markStr, fontSize);
content.beginText();
switch (color) {
case "WHITE":
content.setColorFill(BaseColor.WHITE);
break;
case "LIGHT_GRAY":
content.setColorFill(BaseColor.LIGHT_GRAY);
break;
case "GRAY":
content.setColorFill(BaseColor.GRAY);
break;
case "DARK_GRAY":
content.setColorFill(BaseColor.DARK_GRAY);
break;
case "BLACK":
content.setColorFill(BaseColor.BLACK);
break;
case "RED":
content.setColorFill(BaseColor.RED);
break;
case "PINK":
content.setColorFill(BaseColor.PINK);
break;
case "ORANGE":
content.setColorFill(BaseColor.ORANGE);
break;
case "YELLOW":
content.setColorFill(BaseColor.YELLOW);
break;
case "GREEN":
content.setColorFill(BaseColor.GREEN);
break;
case "MAGENTA":
content.setColorFill(BaseColor.MAGENTA);
break;
case "CYAN":
content.setColorFill(BaseColor.CYAN);
break;
case "BLUE":
content.setColorFill(BaseColor.BLUE);
break;
default:
content.setColorFill(BaseColor.GREEN);
}
content.setFontAndSize(font, fontSize);
content.setTextMatrix(0, 0);
//角度
content.showTextAligned(Element.ALIGN_LEFT, markStr, (pageWidth - xxxx) / 2, (pageHeight - yyyy) / 2,
globalOblique);
content.endText();
}
pdfStamper.close();
pdfReader.close();
return true;
} catch (Exception ex) {
System.out.println("水印添加失败:" + ex.getMessage());
return false;
}
}
/**
* 合并Pdf
*
* @param fileArray pdf图片数组[]{"d:/a/1.pdf","d:/a/2.pdf"}
* @param tarFile 生成的目标pdf
* @return
*/
public static boolean mergePdf(String[] fileArray, String tarFile) {
//目标文件存在,则先删除
File _tarFile = new File(tarFile);
if (_tarFile.exists()) {
_tarFile.delete();
}
Arrays.sort(fileArray);
try {
Document doc = new Document();
PdfCopy pdf = new PdfCopy(doc, new FileOutputStream(tarFile));
doc.open();
for (int i = 0; i < fileArray.length; i++) {
if (fileArray[i] != null) {
PdfReader pdfReader = new PdfReader(fileArray[i]);
PdfReader.unethicalreading = true;
int numberOfPages = pdfReader.getNumberOfPages();
for (int page = 0; page < numberOfPages; page++) {
PdfImportedPage newPage = pdf.getImportedPage(pdfReader, page + 1);
pdf.addPage(newPage);
}
pdf.freeReader(pdfReader);
pdfReader.close();
}
}
doc.close();
return true;
} catch (Exception ex) {
System.out.println("合并Pdf失败" + ex.getMessage());
return false;
}
}
/*
* @Description 图片转pdf
* @Date 13:33 2019/6/10
* @Param []
* @return boolean
**/
public static boolean image2Pdf(String source, String target) {
try {
BufferedImage img = ImageIO.read(new File(source));
PdfReader.unethicalreading = true;
Image png1 = Image.getInstance(source); //通过文件路径获取image
// float heigth = png1.getHeight();
// float width = png1.getWidth();
//new一个pdf文档
Document doc = new Document(null, 0, 0, 0, 0);
if (img == null) {
doc.setPageSize(new Rectangle(png1.getWidth(), png1.getHeight()));
} else {
doc.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
}
PdfWriter.getInstance(doc, new FileOutputStream(target)); //pdf写入
doc.open();//打开文档
// doc.newPage(); //在pdf创建一页
// int percent = getPercent2(heigth, width);
// png1.setAlignment(Image.MIDDLE);
// png1.scalePercent(percent+3);// 表示是原来图像的比例;
doc.add(png1);
doc.close();
File mOutputPdfFile = new File(target); //输出流
if (!mOutputPdfFile.exists()) {
mOutputPdfFile.deleteOnExit();
}
mOutputPdfFile.createNewFile();
return true;
} catch (Exception ex) {
System.out.println("图片转pdf失败" + ex.getMessage());
return false;
}
}
/****
* 给PDF文件某些页增加马赛克
* @param srcFile 源文件
* @param tarFile 目标文件
* @param tarPages 需要增加马赛克的页号数组
* @return
*/
public static boolean PdfBlock(String srcFile, String tarFile, int[] tarPages) {
//目标文件存在,则先删除
File _tarFile = new File(tarFile);
if (_tarFile.exists()) {
_tarFile.delete();
}
try {
PdfReader pdfReader = new PdfReader(srcFile);
PdfReader.unethicalreading = true;
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(tarFile));
//获取文件总页数
int numberOfPages = pdfReader.getNumberOfPages();
for (int page : tarPages) {
if (page > numberOfPages) {
break;
}
Rectangle rectangle = pdfReader.getPageSizeWithRotation(page);
float pageWidth = rectangle.getWidth();
float pageHeight = rectangle.getHeight();
PdfContentByte content = pdfStamper.getOverContent(page);
//保存状态
content.saveState();
content.setColorFill(BaseColor.BLACK);
content.rectangle(0, 0, pageWidth, pageHeight);
content.fill();
//还原状态
content.restoreState();
}
pdfStamper.close();
pdfReader.close();
return true;
} catch (Exception ex) {
System.out.println(ex.getMessage());
return false;
}
}
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;
}
/*
pdf加水印平铺
* */
public static void waterMark(String inputFile,
String outputFile, String waterMarkName) {
try {
PdfReader reader = new PdfReader(inputFile);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(
outputFile));
File ttfFile = ResourceUtils.getFile("classpath:SIMYOU.TTF");
BaseFont base = BaseFont.createFont(ttfFile.getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
Rectangle pageRect = null;
PdfGState gs = new PdfGState();
gs.setFillOpacity(0.2f);
gs.setStrokeOpacity(0.2f);
int total = reader.getNumberOfPages() + 1;
JLabel label = new JLabel();
FontMetrics metrics;
int textH = 0;
int textW = 0;
label.setText(waterMarkName);
metrics = label.getFontMetrics(label.getFont());
textH = metrics.getHeight();
textW = metrics.stringWidth(label.getText());
PdfContentByte under;
for (int i = 1; i < total; i++) {
pageRect = reader.getPageSizeWithRotation(i);
under = stamper.getOverContent(i);
under.saveState();
under.setGState(gs);
under.beginText();
under.setFontAndSize(base, 30);
// 水印文字成30度角倾斜
//你可以随心所欲的改你自己想要的角度
for (int height = interval + textH; height < pageRect.getHeight();
height = height + textH*3) {
for (int width = interval + textW; width < pageRect.getWidth() + textW;
width = width + textW*2) {
under.showTextAligned(Element.ALIGN_LEFT
, waterMarkName, width - textW,
height - textH, 30);
}
}
// 添加水印文字
under.endText();
}
//说三遍
//一定不要忘记关闭流
//一定不要忘记关闭流
//一定不要忘记关闭流
stamper.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
pdf加水印平铺
*/
public static ByteArrayOutputStream waterMark(InputStream inputStream, String waterMarkName) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
PdfReader reader = new PdfReader(inputStream);
PdfStamper stamper = new PdfStamper(reader, outputStream);
File ttfFile = ResourceUtils.getFile("classpath:SIMYOU.TTF");
BaseFont base = BaseFont.createFont(ttfFile.getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
Rectangle pageRect = null;
PdfGState gs = new PdfGState();
gs.setFillOpacity(0.2f);
gs.setStrokeOpacity(0.2f);
int total = reader.getNumberOfPages() + 1;
JLabel label = new JLabel();
FontMetrics metrics;
int textH = 0;
int textW = 0;
label.setText(waterMarkName);
metrics = label.getFontMetrics(label.getFont());
textH = metrics.getHeight();
textW = metrics.stringWidth(label.getText());
PdfContentByte under;
for (int i = 1; i < total; i++) {
pageRect = reader.getPageSizeWithRotation(i);
under = stamper.getOverContent(i);
under.saveState();
under.setGState(gs);
under.beginText();
under.setFontAndSize(base, 30);
// 水印文字成30度角倾斜
//你可以随心所欲的改你自己想要的角度
for (int height = interval + textH; height < pageRect.getHeight();
height = height + textH*10) {
for (int width = interval + textW; width < pageRect.getWidth() + textW;
width = width + textW*9) {
under.showTextAligned(Element.ALIGN_LEFT
, waterMarkName, width - textW,
height - textH, 30);
}
}
// 添加水印文字
under.endText();
}
stamper.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return outputStream;
}
public static void main1(String[] args) {
String source = "C:\\Users\\MI\\Desktop\\13\\pdf\\b.pdf";
String target = "C:\\Users\\MI\\Desktop\\13\\pdf\\b-" + DateUtil.date2String(new Date(), 3) + ".pdf";
// String source = "D:\\test\\222.pdf";
// String target = "D:\\test\\111.pdf";
String[][] aaa = {{"11", "12", "13"}, {"21", "22", "23"}};
Seal(source, target, 1, aaa, "2", 2);
// test(source, target);
// source = "d:/2.pdf";
// target = "d:/3.pdf";
// int[] pages = {1, 3};
//
// boolean r = PdfBlock(source, target, pages);
System.out.print("1");
}
public static void main2(String[] args) {
String source = "C:\\Users\\MI\\Desktop\\13\\img\\2.jpg";
String target = "C:\\Users\\MI\\Desktop\\13\\img\\\\2-110.pdf";
image2Pdf(source, target);
}
public static void main3(String[] args) {
String source = "C:\\Users\\MI\\Desktop\\13\\img\\1.jpg";
String target = "C:\\Users\\MI\\Desktop\\13\\img\\1-" + DateUtil.date2String(new Date(), 3) + ".pdf";
image2Pdf(source, target);
}
public static void main4(String[] args) {
String srcFile = "C:\\Users\\MI\\Desktop\\13\\pdf\\b.pdf";
String tarFile = "C:\\Users\\MI\\Desktop\\13\\pdf\\setWaterMark-" + DateUtil.date2String(new Date(), 3) + ".pdf";
String markStr = "管理员";
int fontSize = 50;
String color = "GREEN";
int globalOblique = 0;
setWaterMark(srcFile, tarFile, markStr, fontSize, color, globalOblique);
}
public static void main5(String[] args) {
String tarFile = "C:\\Users\\MI\\Desktop\\13\\pdf\\mergePdf-" + DateUtil.date2String(new Date(), 3) + ".pdf";
String[] fileArray = {"C:\\Users\\MI\\Desktop\\13\\pdf\\k1.pdf", "C:\\Users\\MI\\Desktop\\13\\pdf\\k2.pdf"};
mergePdf(fileArray, tarFile);
}
public static void main(String[] args) {
pageNo("C:\\Users\\MI\\Desktop\\13\\pdf\\caiwenhong.pdf","C:\\Users\\MI\\Desktop\\13\\pdf\\caiwenhong-pageNo.pdf");
}
}