itext 5.3.0 pdfファイルに水印を追加することを実現します。
4181 ワード
itext , , , xx.TTF , BaseFont , 。 :
BaseFont font = BaseFont.createFont(path + "MSYH.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
jarバッグが必要ですウェブサイトのダウンロードのitext-5.3.0.zipの下のjar包み
itextpdf-5.30.jar
itext-xtra-5.30.jar
中国語でサポートされる拡張jarパケットは不要であり、上記のロードフォントファイルからBaseFontに実装される。
具体的なウォーターマークコードは以下の通りです。
package com.sslinm.tools;
import java.io.FileOutputStream;
/**
* 【 : PDF ,( )】
* 【 : 】
*
* @author 【lfssay】
* @see 【 / 】
* @version 【 , 2013-8-20 11:22:21】
* @since 【 / 】
*/
public class PdfAddWaterMark {
static Log log = LogFactory.getLog(PdfAddWaterMark.class);
public static void main(String[] args) throws DocumentException, IOException {
new PdfAddWaterMark().addWaterMark("E:/tt/1.pdf", "E:/tt/129.pdf", " ", "E:/tt/1.jpg", 400, 800, 200, 800);
}
/**
*
* 【 : 】 【 : 】
*
* @see 【 、 # 、 # 】
* @param srcFile
*
* @param destFile
*
* @param text
*
* @param imgFile
*
* @param textWidth
*
* @param textHeight
*
* @param imgWidth
*
* @param imgHeight
*
* @throws IOException
* @throws DocumentException
*/
public void addWaterMark(String srcFile, String destFile, String text, String imgFile, int textWidth,
int textHeight, int imgWidth, int imgHeight) throws IOException, DocumentException {
//
PdfReader reader = new PdfReader(srcFile);
//
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destFile));
int total = reader.getNumberOfPages() + 1;
PdfContentByte content;
String path = this.getClass().getResource("/").getPath();
//
// BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
// BaseFont.EMBEDDED);
//
BaseFont font = BaseFont.createFont(path + "MSYH.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
// BaseFont base2 = BaseFont.createFont(BaseFont.HELVETICA,
// BaseFont.WINANSI, BaseFont.EMBEDDED);
//
String waterText = text;
Image image = null;
if (!StringUtils.isBlank(imgFile)) {
image = Image.getInstance(imgFile);
image.setAbsolutePosition(imgWidth, imgHeight);
//
image.scaleToFit(100, 125);
}
int j = waterText.length(); //
char c = 0;
int high = 0;//
//
for (int i = 1; i < total; i++) {
//
high = 50;
//
content = stamper.getOverContent(i);
if (image != null) {
content.addImage(image);
}
if (!StringUtils.isBlank(text)) {
//
content.beginText();
//
content.setColorFill(BaseColor.BLUE);
// content.setColorFill(Color.GRAY);
//
content.setFontAndSize(font, 38);
//
// content.setTextMatrix(400, 880);
content.setTextMatrix(textWidth, textHeight);
//
content.showTextAligned(Element.ALIGN_LEFT, text, textWidth, textHeight, 45);
// for (int k = 0; k < j; k++) {
// content.setTextRise(14);
// c = waterText.charAt(k);
// // char
// content.showText(c + "");
// high -= 5;
// }
content.endText();
}
}
stamper.close();
log.info("===" + srcFile + "=== ==" + destFile + "== =====");
}
}