最近项目中有一些对PDF操作的需求,包括:
PDF转变为图片;
把图片进行切割;
把图片转变回PDF;
为PDF加水印文字;
为PDF加水印图片。
这里记录一下这些方法,方便日后用到时可查,也希望可以帮助有这方面需求的小伙伴。
以下方法均为可直接运行的测试方法,复制导包就可以运行,这里测试都可以跑通。
1,PDF转变为图片
/**
* @author dalin
*将PDF格式的文件转换成png文件
*/
public class PdfToPNG {
public static void main(String[] args) {
String filePath = "D:\\pdf\\2.pdf";
Document document = new Document();
document.setFile(filePath);
float scale = 2.5f;//缩放比例
float rotation = 0f;//旋转角度
for (int i = 0; i < document.getNumberOfPages(); i++) {
BufferedImage image = (BufferedImage)
document.getPageImage(i, GraphicsRenderingHints.SCREEN, org.icepdf.core.pobjects.Page.BOUNDARY_CROPBOX, rotation, scale);
RenderedImage rendImage = image;
try {
File file = new File("D:\\img\\" + i + ".png");
ImageIO.write(rendImage, "png", file);
} catch (IOException e) {
e.printStackTrace();
}
image.flush();
}
document.dispose();
}
}
2,图片切割
/**
* @author dalin
*分割png文件,这里做截取png文件部分
*/
public class FenGePNG {
private static void splitImage() throws IOException {
String originalImg = "D:\\img\\0.png";
// 读入大图
File file = new File(originalImg);
FileInputStream fis = new FileInputStream(file);
BufferedImage image = ImageIO.read(fis);
// 分割成4*4(16)个小图
int rows = 2;
int cols = 1;
int chunks = rows * cols;
// 计算每个小图的宽度和高度
int chunkWidth = image.getWidth() / cols;
int chunkHeight = image.getHeight() / rows;
int count = 0;
BufferedImage imgs[] = new BufferedImage[chunks];
for (int x = 0; x < rows; x++) {
for (int y = 0; y < cols; y++) {
//设置小图的大小和类型
imgs[count] = new BufferedImage(chunkWidth, chunkHeight, image.getType());
//写入图像内容
Graphics2D gr = imgs[count++].createGraphics();
gr.drawImage(image, 0, 0,
chunkWidth, chunkHeight,
chunkWidth* y, chunkHeight * x,
chunkWidth * y + chunkWidth,
chunkHeight * x + chunkHeight, null);
gr.dispose();
}
}
// 输出小图
for (int i = 0; i < imgs.length; i++) {
ImageIO.write(imgs[i], "jpg", new File("D:\\img\\" + "img"+i + ".jpg"));
}
System.out.println("完成分割!");
}
public static void main(String[] args) {
try {
splitImage();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3,图片转变为PDF
/**
* @author dalin
* png文件类型转为PDF类型
*/
public class PNGToPdf {
private static void jpgToPdf(File pdfFile,File imgFile) throws Exception {
//文件转img
InputStream is = new FileInputStream(pdfFile);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for(int i;(i=is.read())!=-1;)
{
baos.write(i);
}
baos.flush();
//取得图像的宽和高。
Image img = Image.getInstance(baos.toByteArray());
float width = img.width();
float height = img.height();
img.setAbsolutePosition(0.0F, 0.0F);//取消偏移
System.out.println("width = "+width+"\theight"+height);
//img转pdf
Document doc = new Document(new Rectangle(width,height));
PdfWriter pw = PdfWriter.getInstance(doc,new FileOutputStream(imgFile));
doc.open();
doc.add(img);
//释放资源
System.out.println(doc.newPage());
pw.flush();
baos.close();
doc.close();
pw.close();
}
public static void main(String[] args) {
try {
jpgToPdf(new File("D:\\img\\0.png"),new File("D:\\pdf\\2new.pdf"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
4,为PDF加文字水印和图片水印
public class Test {
public static void main(String[] args) throws DocumentException, IOException {
// 要输出的pdf文件
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("D:\\pdf\\water6.pdf")));
setWatermark(bos, "D:\\pdf\\2.pdf", 16);
}
public static void setWatermark(BufferedOutputStream bos, String input, int permission)
throws DocumentException, IOException {
Rectangle pageRect = null;
PdfReader reader = new PdfReader(input);
PdfStamper stamper = new PdfStamper(reader, bos);
int total = reader.getNumberOfPages() + 1;
PdfContentByte content;
Image image = Image.getInstance("D:/pdf/1.jpg");
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
PdfGState gs = new PdfGState();
for (int i = 1; i < total; i++) {
pageRect = stamper.getReader().getPageSizeWithRotation(i);
// 计算水印X,Y坐标
// float x = pageRect.getWidth() / 1;
float y = pageRect.getHeight() / 1;
System.out.println("这张PDF长是:" + y);
// content = stamper.getOverContent(i);// 在内容上方加水印
content = stamper.getUnderContent(i);// 在内容下方加水印
gs.setFillOpacity(0.2f);
// content.setGState(gs);
content.beginText();
content.setColorFill(Color.LIGHT_GRAY);
content.setFontAndSize(base, 25);
// content.setTextMatrix(500,500);
image.setAbsolutePosition(100, 200);
image.setRotationDegrees(30);
content.showTextAligned(Element.ALIGN_LEFT, "XXXX防伪标志", 250, 200, 55);
image.scaleToFit(200, 200);
content.addImage(image);
content.setColorFill(Color.BLACK);
content.setFontAndSize(base, 8);
content.endText();
}
stamper.close();
}
}
好了,就这些了。包基本就是iText那些