都是自己踩过的坑,主要是为了实现pdf加水印,并且别人不方便去除的需求。
1、给pdf加水印
public static boolean waterMark(byte[] fileBytes, String outputFile, HashMap waterMarkName) {
String orgName = null;//机构名称
String name = null;//姓名
String mobile = null;//手机号码
if(waterMarkName.containsKey("orgName") && waterMarkName.containsKey("name") && waterMarkName.containsKey("mobile")){
orgName = waterMarkName.get("orgName").toString();
name = waterMarkName.get("name").toString();
mobile = waterMarkName.get("mobile").toString();
}
try {
PdfReader reader = new PdfReader(fileBytes);
//PdfReader reader = new PdfReader(inputFile);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
// 这里的字体设置比较关键,这个设置是支持中文的写法
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 使用系统字体
int total = reader.getNumberOfPages() + 1;
PdfContentByte under;
Rectangle pageRect = null;
for (int i = 1; i < total; i++) {
pageRect = stamper.getReader().getPageSizeWithRotation(i);
//计算水印X,Y坐标
float x = pageRect.getWidth();
float y = pageRect.getHeight();
//获得PDF最顶层
//under = stamper.getUnderContent(i);
under = stamper.getOverContent(i);
under.saveState();
PdfGState gs = new PdfGState();
// 设置透明度为
gs.setFillOpacity(0.3f);
under.setGState(gs);
//中间位置
under.beginText();
//设置字体颜色
under.setColorFill(BaseColor.GRAY);
//设置字体大小
under.setFontAndSize(base, 40);
// 水印文字成45度角倾斜
//中间
under.showTextAligned(Element.ALIGN_LEFT, orgName, x/2, y/2, 45);
under.showTextAligned(Element.ALIGN_LEFT, name, x/2, y/2-60, 45);
under.showTextAligned(Element.ALIGN_LEFT, mobile, x/2, y/2-120, 45);
//左下角
under.showTextAligned(Element.ALIGN_LEFT, orgName, 0, 120, 45);
under.showTextAligned(Element.ALIGN_LEFT, name, 0, 60, 45);
under.showTextAligned(Element.ALIGN_LEFT, mobile, 0, 0, 45);
//左上角
under.showTextAligned(Element.ALIGN_LEFT, orgName, 0, y-60, 45);
under.showTextAligned(Element.ALIGN_LEFT, name, 0, y-120, 45);
under.showTextAligned(Element.ALIGN_LEFT, mobile, 0, y-180, 45);
//右下角
under.showTextAligned(Element.ALIGN_LEFT, orgName, x-120, 120, 45);
under.showTextAligned(Element.ALIGN_LEFT, name, x-120, 60, 45);
under.showTextAligned(Element.ALIGN_LEFT, mobile, x-120, 0, 45);
//右上角
under.showTextAligned(Element.ALIGN_LEFT, orgName, x-120, y-60, 45);
under.showTextAligned(Element.ALIGN_LEFT, name, x-120, y-120, 45);
under.showTextAligned(Element.ALIGN_LEFT, mobile, x-120, y-180, 45);
// 添加水印文字
under.endText();
under.restoreState();//注意这里必须调用一次restoreState 否则设置无效
}
stamper.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
2、pdf转图片
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Iterator;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;
public class Pdf2Pic {
public static final String FILETYPE_JPG = "png";
/**
*
* 将指定的pdf文件转换为指定路径的图片
*
* @param filepath 原文件路径,例如d:/test/test.pdf
*
* @param imagepath 图片生成路径,例如 d:/test/
*
* @param zoom 缩略图显示倍数,1表示不缩放,0.3则缩小到30%
*
*/
public static void tranfer(String filepath, String imagepath, float zoom) throws PDFException, PDFSecurityException, IOException {
Document document = null;
float rotation = 0f;
document = new Document();
document.setFile(filepath);
int maxPages = document.getPageTree().getNumberOfPages();
for (int i = 0; i < maxPages; i++) {
BufferedImage img = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, zoom);
Iterator iter = ImageIO.getImageWritersBySuffix(FILETYPE_JPG);
ImageWriter writer = (ImageWriter) iter.next();
File outFile = new File(imagepath + new File(filepath).getName() + "_" + new DecimalFormat("000").format(i) + "." + FILETYPE_JPG);
FileOutputStream out = new FileOutputStream(outFile);
ImageOutputStream outImage = ImageIO.createImageOutputStream(out);
writer.setOutput(outImage);
writer.write(new IIOImage(img, null, null));
}
System.out.println("转换完成");
}
public static void main(String[] args) throws PDFException, PDFSecurityException, IOException {
long startTime = System.currentTimeMillis();
tranfer("D:/itext.pdf", "d:", 1);
long endTime = System.currentTimeMillis();
System.out.println("程序运行时间:" + (endTime - startTime) + "ms"); //输出程序运行时间
}
}
3、图片转pdf
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileOutputStream;
public class PrintToPdfUtil {
private static String FILEPATH = "D:\\";
/**
*
* @param fileName
* 生成pdf文件
* @param imagesPath
* 需要转换的图片路径的数组
*/
public static void imagesToPdf(String fileName, String imagesPath) {
try {
fileName = FILEPATH+fileName+".pdf";
File file = new File(fileName);
// 第一步:创建一个document对象。
Document document = new Document();
document.setMargins(0, 0, 0, 0);
// 第二步:
// 创建一个PdfWriter实例,
PdfWriter.getInstance(document, new FileOutputStream(file));
// 第三步:打开文档。
document.open();
// 第四步:在文档中增加图片。
File files = new File(imagesPath);
String[] images = files.list();
int len = images.length;
for (int i = 0; i < len; i++){
if (images[i].toLowerCase().endsWith(".bmp")
|| images[i].toLowerCase().endsWith(".jpg")
|| images[i].toLowerCase().endsWith(".jpeg")
|| images[i].toLowerCase().endsWith(".gif")
|| images[i].toLowerCase().endsWith(".png")) {
String temp = imagesPath + "\\" + images[i];
Image img = Image.getInstance(temp);
img.setAlignment(Image.ALIGN_CENTER);
// 根据图片大小设置页面,一定要先设置页面,再newPage(),否则无效
document.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
document.newPage();
document.add(img);
}
}
// 第五步:关闭文档。
document.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args){
long startTime = System.currentTimeMillis();
String name = "img2pdf";
String imagesPath = "D:\\";
imagesToPdf(name, imagesPath);
long endTime = System.currentTimeMillis();
System.out.println("程序运行时间:" + (endTime - startTime) + "ms"); //输出程序运行时间
}
}
有关pdf的各种操作(打水印、pdf转图片、图片转pdf)所需jar包,包括icepdf-core.jar、icepdf-viewer.jar、itext-asian-5.2.0.jar、itextpdf-5.3.5.jar