可以去官网下载pdfbox-x.x.x-src.zip 看看案例
1.引入依赖
org.apache.pdfbox pdfbox 2.0.19 org.bouncycastle bcmail-jdk15on 1.64
package com.jfcimb.utils;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationRubberStamp;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceDictionary;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceStream;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.util.Matrix;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.NumberFormat;
import java.util.List;
import java.util.Locale;
/**
* Title:PdfBoxUtil
*
* @author xuxiaoji
**/
public class PdfUtils {
private static final String PDF_SRC="C:\\Users\\xuxiaoji\\Desktop\\图片\\FDP\\sign_me.pdf";
private static final String SAVE_GRAPHICS_STATE = "q\n";
private static final String RESTORE_GRAPHICS_STATE = "Q\n";
private static final String CONCATENATE_MATRIX = "cm\n";
private static final String XOBJECT_DO = "Do\n";
private static final String SPACE = " ";
private static final NumberFormat FORMATDECIMAL = NumberFormat.getNumberInstance(Locale.US);
//pdf转成image
public static void toImage() {
File file = new File(PDF_SRC);
try {
PDDocument doc = PDDocument.load(file);
PDFRenderer renderer = new PDFRenderer(doc);
int pageCount = doc.getNumberOfPages();
for (int i = 0; i < pageCount; i++) {
// 方式1,第二个参数是设置缩放比(即像素)
//BufferedImage image = renderer.renderImageWithDPI(i, 296);
// 方式2,第二个参数是设置缩放比(即像素)
BufferedImage image = renderer.renderImage(i, 2.5f);
ImageIO.write(image, "PNG", new File("d:\\1.png"));
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void waterMarkImageByIcon() {
String icon = "C:\\Users\\xuxiaoji\\Desktop\\图片\\3.jpg";
String src = "C:\\Users\\xuxiaoji\\Desktop\\图片\\2.jpeg";
String targer = "C:\\Users\\xuxiaoji\\Desktop\\图片\\2end.jpeg";
waterMarkImageByIcon(icon, src, targer, 0, 10, 10, 1f);
}
/**
* 给图片添加水印、可设置水印图片旋转角度
*
* @param iconPath 水印图片路径
* @param srcImgPath 源图片路径
* @param targerPath 目标图片路径
* @param degree 水印图片旋转角度
* @param width 宽度(与左相比)
* @param height 高度(与顶相比)
* @param clarity 透明度(小于1的数)越接近0越透明
*/
public static void waterMarkImageByIcon(String iconPath, String srcImgPath,
String targerPath, Integer degree, Integer width, Integer height,
float clarity) {
OutputStream os = null;
try {
Image srcImg = ImageIO.read(new File(srcImgPath));
System.out.println("width:" + srcImg.getWidth(null));
System.out.println("height:" + srcImg.getHeight(null));
BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),
srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
// 得到画笔对象
// Graphics g= buffImg.getGraphics();
Graphics2D g = buffImg.createGraphics();
// 设置对线段的锯齿状边缘处理
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(
srcImg.getScaledInstance(srcImg.getWidth(null),
srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0,
null);
if (null != degree) {
// 设置水印旋转
g.rotate(Math.toRadians(degree),
(double) buffImg.getWidth() / 2,
(double) buffImg.getHeight() / 2);
}
// 水印图象的路径 水印一般为gif或者png的,这样可设置透明度
ImageIcon imgIcon = new ImageIcon(iconPath);
// 得到Image对象。
Image img = imgIcon.getImage();
float alpha = clarity; // 透明度
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
alpha));
// 表示水印图片的位置
g.drawImage(img, width, height, null);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
g.dispose();
os = new FileOutputStream(targerPath);
// 生成图片
ImageIO.write(buffImg, "JPG", os);
System.out.println("添加水印图片完成!");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != os) {
os.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void readString(String[] args) throws Exception {
readString(PDF_SRC);
}
/**
* 读取文本
*/
public static void readString(String source) throws IOException {
PDDocument doc = PDDocument.load(new File(source));
PDFTextStripper stripper = new PDFTextStripper();
// 设置按顺序输出
stripper.setSortByPosition(true);
stripper.setStartPage(1);
stripper.setEndPage(doc.getNumberOfPages());
String text = stripper.getText(doc);
System.out.println(text);
}
/**
* 水印
*/
public static void markTxt(String source, String target) throws InvalidPasswordException, IOException {
File tmpPDF = new File(target);
PDDocument doc = PDDocument.load(new File(source));
doc.setAllSecurityToBeRemoved(true);
for (PDPage page : doc.getPages()) {
PDPageContentStream cs = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true,
true);
String ts = "Some sample text";
PDFont font = PDType1Font.HELVETICA_OBLIQUE;
// PDResources resources = page.getResources();
PDExtendedGraphicsState r0 = new PDExtendedGraphicsState();
// 透明度
r0.setNonStrokingAlphaConstant(0.2f);
r0.setAlphaSourceFlag(true);
cs.setGraphicsStateParameters(r0);
cs.setNonStrokingColor(200, 0, 0);// Red
cs.beginText();
float fontSize = 50.0f;
cs.setFont(font, fontSize);
// 获取旋转实例
cs.setTextMatrix(Matrix.getRotateInstance(20, 350f, 490f));
cs.showText(ts);
cs.endText();
cs.close();
}
doc.save(tmpPDF);
}
public static void main(String[] args) throws Exception {
new PdfUtils().pdfAddImageUtil();
}
public void pdfAddImageUtil() throws IOException {
String name = "_" + System.currentTimeMillis();
String documentFile = "C:\\Users\\xuxiaoji\\Desktop\\图片\\FDP\\sign_me_3.pdf";
String stampFile = "C:\\Users\\xuxiaoji\\Desktop\\图片\\FDP\\stamp.jpg";
String outFile = "C:\\Users\\xuxiaoji\\Desktop\\图片\\FDP\\test-output\\TestRubberStampWithImage" + name + ".pdf";
new File("target/test-output").mkdirs();
String[] args = new String[]{documentFile, outFile, stampFile};
//rubberStamp.doIt(args);
this.doItByEndPage(args);
}
//最后一页加图片
public void doItByEndPage(String[] args) throws IOException {
if (args.length != 3) {
} else {
PDDocument document = null;
try {
document = PDDocument.load(new File(args[0]));
if (document.isEncrypted()) {
throw new IOException("Encrypted documents are not supported for this example");
}
int i = document.getNumberOfPages() - 1;
PDPage page = document.getPage(i);
List annotations = page.getAnnotations();
PDAnnotationRubberStamp rubberStamp = new PDAnnotationRubberStamp();
rubberStamp.setName(PDAnnotationRubberStamp.NAME_TOP_SECRET);
rubberStamp.setRectangle(new PDRectangle(200, 100));
rubberStamp.setContents("A top secret note");
// create a PDXObjectImage with the given image file
// if you already have the image in a BufferedImage,
// call LosslessFactory.createFromImage() instead
PDImageXObject ximage = PDImageXObject.createFromFile(args[2], document);
// define and set the target rectangle
float lowerLeftX = 750;
float lowerLeftY = 50;
float formWidth = 150;
float formHeight = 25;
float imgWidth = 50;
float imgHeight = 25;
PDRectangle rect = new PDRectangle();
rect.setLowerLeftX(lowerLeftX);
rect.setLowerLeftY(lowerLeftY);
rect.setUpperRightX(lowerLeftX + formWidth);
rect.setUpperRightY(lowerLeftY + formHeight);
// Create a PDFormXObject
PDFormXObject form = new PDFormXObject(document);
form.setResources(new PDResources());
form.setBBox(rect);
form.setFormType(1);
// adjust the image to the target rectangle and add it to the stream
OutputStream os = form.getStream().createOutputStream();
drawXObject(ximage, form.getResources(), os, lowerLeftX, lowerLeftY, imgWidth, imgHeight);
os.close();
PDAppearanceStream myDic = new PDAppearanceStream(form.getCOSObject());
PDAppearanceDictionary appearance = new PDAppearanceDictionary(new COSDictionary());
appearance.setNormalAppearance(myDic);
rubberStamp.setAppearance(appearance);
rubberStamp.setRectangle(rect);
// add the new RubberStamp to the document
annotations.add(rubberStamp);
document.save(args[1]);
} finally {
if (document != null) {
document.close();
}
}
}
}
//每页加图片
public void doIt(String[] args) throws IOException {
if (args.length != 3) {
} else {
PDDocument document = null;
try {
document = PDDocument.load(new File(args[0]));
if (document.isEncrypted()) {
throw new IOException("Encrypted documents are not supported for this example");
}
for (int i = 0; i < document.getNumberOfPages(); i++) {
PDPage page = document.getPage(i);
List annotations = page.getAnnotations();
PDAnnotationRubberStamp rubberStamp = new PDAnnotationRubberStamp();
rubberStamp.setName(PDAnnotationRubberStamp.NAME_TOP_SECRET);
rubberStamp.setRectangle(new PDRectangle(200, 100));
rubberStamp.setContents("A top secret note");
// create a PDXObjectImage with the given image file
// if you already have the image in a BufferedImage,
// call LosslessFactory.createFromImage() instead
PDImageXObject ximage = PDImageXObject.createFromFile(args[2], document);
// define and set the target rectangle
float lowerLeftX = 750;
float lowerLeftY = 50;
float formWidth = 150;
float formHeight = 25;
float imgWidth = 50;
float imgHeight = 25;
PDRectangle rect = new PDRectangle();
rect.setLowerLeftX(lowerLeftX);
rect.setLowerLeftY(lowerLeftY);
rect.setUpperRightX(lowerLeftX + formWidth);
rect.setUpperRightY(lowerLeftY + formHeight);
// Create a PDFormXObject
PDFormXObject form = new PDFormXObject(document);
form.setResources(new PDResources());
form.setBBox(rect);
form.setFormType(1);
// adjust the image to the target rectangle and add it to the stream
OutputStream os = form.getStream().createOutputStream();
drawXObject(ximage, form.getResources(), os, lowerLeftX, lowerLeftY, imgWidth, imgHeight);
os.close();
PDAppearanceStream myDic = new PDAppearanceStream(form.getCOSObject());
PDAppearanceDictionary appearance = new PDAppearanceDictionary(new COSDictionary());
appearance.setNormalAppearance(myDic);
rubberStamp.setAppearance(appearance);
rubberStamp.setRectangle(rect);
// add the new RubberStamp to the document
annotations.add(rubberStamp);
}
document.save(args[1]);
} finally {
if (document != null) {
document.close();
}
}
}
}
private void drawXObject(PDImageXObject xobject, PDResources resources, OutputStream os,
float x, float y, float width, float height) throws IOException {
// This is similar to PDPageContentStream.drawXObject()
COSName xObjectId = resources.add(xobject);
appendRawCommands(os, SAVE_GRAPHICS_STATE);
appendRawCommands(os, FORMATDECIMAL.format(width));
appendRawCommands(os, SPACE);
appendRawCommands(os, FORMATDECIMAL.format(0));
appendRawCommands(os, SPACE);
appendRawCommands(os, FORMATDECIMAL.format(0));
appendRawCommands(os, SPACE);
appendRawCommands(os, FORMATDECIMAL.format(height));
appendRawCommands(os, SPACE);
appendRawCommands(os, FORMATDECIMAL.format(x));
appendRawCommands(os, SPACE);
appendRawCommands(os, FORMATDECIMAL.format(y));
appendRawCommands(os, SPACE);
appendRawCommands(os, CONCATENATE_MATRIX);
appendRawCommands(os, SPACE);
appendRawCommands(os, "/");
appendRawCommands(os, xObjectId.getName());
appendRawCommands(os, SPACE);
appendRawCommands(os, XOBJECT_DO);
appendRawCommands(os, SPACE);
appendRawCommands(os, RESTORE_GRAPHICS_STATE);
}
private void appendRawCommands(OutputStream os, String commands) throws IOException {
os.write(commands.getBytes("ISO-8859-1"));
}
}