资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

pdf加水印java代码 java给pdf加水印

java如何实现在web工程中用OpenOffice生成带有图片水印的pdf

需要itext2.1.5,

创新互联公司是一家专注于成都做网站、网站制作、成都外贸网站建设与策划设计,岳普湖网站建设哪家好?创新互联公司做网站,专注于网站建设10多年,网设计领域的专业建站公司;建站业务涵盖:岳普湖等地区。岳普湖做网站价格咨询:028-86922220

以下是对pdf加水印的代码,包括文字水印和图片水印

public int fileCopy(String srcPath, String destPath) {

FileOutputStream fos = null;

FileInputStream fis = null;

try {

fos = new FileOutputStream(destPath);

fis = new FileInputStream(srcPath);

byte[] buffer = new byte[1024];

int len = 0;

while ((len = fis.read(buffer)) 0) {

fos.write(buffer, 0, len);

}

return 1;

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

fis.close();

fos.flush();

fos.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

return 0;

}

/**

* 为pdf文件加文字水印

*

* @param srcPath

*            源文件路径

* @param destPath

*            目标文件路径

* @param waterText

*            水印文字

* @throws DocumentException

* @throws IOException

*/

public void wordWaterMark(String srcPath, String destPath, String waterText) throws DocumentException, IOException {

int result = fileCopy(srcPath, destPath);

if (result == 1) {

// 待加水印的文件

PdfReader reader = new PdfReader(destPath);

// 加完水印的文件

PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(srcPath));

int total = reader.getNumberOfPages() + 1;

PdfContentByte content;

// 设置字体

BaseFont base = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

// 水印文字

int j = waterText.length(); // 文字长度

char c = 0;

int high = 0;// 高度

// 循环对每页插入水印

for (int i = 1; i total; i++) {

// 水印的起始

high = 60;

content = stamper.getUnderContent(i);

PdfGState gs = new PdfGState();

gs.setFillOpacity(0.1f);// 设置透明度为0.2

content.setGState(gs);

// 开始

content.beginText();

// 设置颜色

// content.setColorFill(new Color());

// 设置字体及字号

content.setFontAndSize(base, 88);

// 设置起始位置

content.setTextMatrix(120, 333);

// 开始写入水印

for (int k = 0; k j; k++) {

content.setTextRise(high);

c = waterText.charAt(k);

content.showText(c + "");

high += 20;

}

content.endText();

}

stamper.close();

System.out.println("添加成功++++++++++++++++++++++++++++++++++++++++++");

} else {

System.out.println("复制pdf失败====================");

}

}

public void picWaterMark(String srcPath, String destPath, String imageFilePath)

throws DocumentException, IOException {

int result = fileCopy(srcPath, destPath);

if (result == 1) {

// 待加水印的文件

PdfReader reader = new PdfReader(destPath);

// 加完水印的文件

PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(srcPath));

Image img = Image.getInstance(imageFilePath);

img.setAbsolutePosition(50, 400);// 坐标

img.setRotation(20);// 旋转 弧度

img.setRotationDegrees(45);// 旋转 角度

// image.scaleAbsolute(200,100);//自定义大小

img.scalePercent(50);// 依照比例缩放

int pageSize = reader.getNumberOfPages();

for (int i = 1; i = pageSize; i++) {

PdfContentByte under = stamper.getUnderContent(i);

under.addImage(img);

PdfGState gs = new PdfGState();

gs.setFillOpacity(0.2f);// 设置透明度为0.2

under.setGState(gs);

}

stamper.close();// 关闭

System.out.println("添加成功++++++++++++++++++++++++++++++++++++++++++");

} else {

System.out.println("复制pdf失败====================");

}

}

linux下转pdf可以用libreoffice,需要安装,这个是免费的,具体代码如下:

String command = "libreoffice5.0 --invisible --convert-to pdf:writer_pdf_Export --outdir " + destFilepath

+ " " + source;

try {

p = Runtime.getRuntime().exec(command);

p.waitFor();

} catch (InterruptedException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

java中打印的pdf怎么添加图片水印

添加水印可以参考使用控件来添加的方法,如下:

1. 添加单个图片水印效果:

import com.spire.pdf.*;

import java.awt.geom.Rectangle2D;

public class watermark {

public static void main(String[] args) {

//加载PDF文档

PdfDocument doc = new PdfDocument();

doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.pdf");

//获取第一页

PdfPageBase page = doc.getPages().get(0);

//设置背景图片

page.setBackgroundImage("C:\\Users\\Administrator\\Desktop\\logo.png");

//设置背景区域

Rectangle2D.Float rect = new Rectangle2D.Float();

rect.setRect(280, 300, 150, 150);

page.setBackgroundRegion(rect);

//保存文档

doc.saveToFile("output/imageWaterMark.pdf");

doc.close();

}

}

2. 添加平铺图片水印效果

import com.spire.pdf.*;

import com.spire.pdf.graphics.PdfImage;

import com.spire.pdf.graphics.PdfTilingBrush;

import java.awt.*;

import java.awt.geom.Dimension2D;

import java.awt.geom.Rectangle2D;

public class AddBackground {

public static void main(String[] args) {

//创建PdfDocument对象,并加载PDF测试文档

PdfDocument pdf = new PdfDocument();

pdf.loadFromFile("test.pdf");

//遍历文档每一页,加载图片,并设置成平铺背景(水印)

for (int i = 0; i pdf.getPages().getCount();i++)

{

PdfPageBase page = pdf.getPages().get(i);

Dimension2D dimension2D = new Dimension();

dimension2D.setSize(page.getCanvas().getSize().getWidth()/4, page.getCanvas().getSize().getHeight()/3);

PdfTilingBrush brush = new PdfTilingBrush(dimension2D);

brush.getGraphics().setTransparency(0.2f);

 brush.getGraphics().translateTransform(brush.getSize().getWidth()/10,brush.getSize().getHeight()/10);

brush.getGraphics().rotateTransform(30);

PdfImage image = PdfImage.fromImage("logo.png");

brush.getGraphics().drawImage(image,brush.getSize().getWidth()-image.getWidth()/2,(brush.getSize().getHeight())/2);

Rectangle2D rectangle2D = new Rectangle2D.Float();

rectangle2D.setFrame(new Point(0,0),page.getCanvas().getClientSize());

page.getCanvas().drawRectangle(brush,rectangle2D);

}

//保存文档

pdf.saveToFile("SetTiledBackground.pdf");

pdf.dispose();

}

}

注:这里使用的是free Spire.Pdf.jar(以上代码参考自文章1、文章2)

java 如何给pdf文件加水印

Java生成PDF 加密 水印

1、iText简介

iText是一个开放源码的Java类库,可以用来方便地生成PDF文件。大家通过访问;release_id=167948

下载最新版本的类库,下载完成之后会得到一个.jar包,把这个包加入JDK的classpath即可使用。

如果生成的PDF文件中需要出现中文、日文、韩文字符,则还需要通过访问

下载iTextAsian.jar包。

关于iText类库的使用,

有比较详细的教程。该教程从入门开始,比较系统地介绍了在PDF文件中放入文字、图片、表格等的方法和技巧。

读完这片教程,大致就可以做一些从简单到复杂的PDF文件了。不过,试图通过教程解决在生成PDF文件过程中遇到的所有困难无疑是一种奢望。所以,阅读iText的api文档显得非常重要。读者在下载类库的同时,也可以下载类库的文档。

注:如果以上两个下载链接无法下载而且通过网络也找不到这个jar包的同志可以留下邮箱地址,我会在两个工作日之内发邮件过去。

以下部分我是我调试通过的源代码,提供大家参考:

import java.awt.*;

import java.io.*;

import com.lowagie.text.*;

import com.lowagie.text.Font;

import

com.lowagie.text.Rectangle;

import com.lowagie.text.pdf.*;

/**

* 最近的项目中使用Itext将txt文件转换为PDF文件, 并且实现对文件的一些权限控制。

现实对pdf文件加

*密,添加水印等。

*/

public class PDFConvertBL

{

//

txt原始文件的路径

private static final String txtFilePath = "d:/11.txt";

// 生成的pdf文件路径

private static final String pdfFilePath =

"d:/22.pdf";

// 添加水印图片路径

// private static final String

imageFilePath = "D:/33.jpg";

// 生成临时文件前缀

private static final

String prefix = "tempFile";

// 所有者密码

private static final String

OWNERPASSWORD = "12345678";

/**

* txt文件转换为pdf文件

*

* @param txtFile

txt文件路径

* @param pdfFile pdf文件路径

* @param userPassWord

用户密码

* @param waterMarkName 水印内容

* @param permission

操作权限

*/

public static void generatePDFWithTxt(String txtFile,

String pdfFile, String userPassWord, String

waterMarkName,

int permission)

{

try

{

// 生成临时文件

File file =

File.createTempFile(prefix, ".pdf");

//

创建pdf文件到临时文件

if (createPDFFile(txtFile, file))

{

// 增加水印和加密

waterMark(file.getPath(),

pdfFile, userPassWord, OWNERPASSWORD, waterMarkName, permission);

}

}

catch (Exception e)

{

e.printStackTrace();

}

}

/**

* 创建PDF文档

*

* @param txtFilePath

txt文件路径(源文件)

* @param pdfFilePath pdf文件路径(新文件)

*/

private

static boolean createPDFFile(String txtFilePath, File file)

{

// 设置纸张

Rectangle rect = new Rectangle(PageSize.A4);

//

设置页码

HeaderFooter footer = new HeaderFooter(new Phrase("页码:",

setChineseFont()), true);

footer.setBorder(Rectangle.NO_BORDER);

// step1

Document

doc = new Document(rect, 50, 50, 50, 50);

doc.setFooter(footer);

try

{

FileReader

fileRead = new FileReader(txtFilePath);

BufferedReader read = new

BufferedReader(fileRead);

// 设置pdf文件生成路径 step2

PdfWriter.getInstance(doc, new FileOutputStream(file));

//

打开pdf文件 step3

doc.open();

// 实例化Paragraph

获取写入pdf文件的内容,调用支持中文的方法. step4

while (read.ready())

{

// 添加内容到pdf(这里将会按照txt文件的原始样式输出)

doc.add(new Paragraph(read.readLine(), setChineseFont()));

}

// 关闭pdf文件 step5

doc.close();

return true;

}

catch (Exception e)

{

e.printStackTrace();

return false;

}

}

/**

* 在pdf文件中添加水印

*

* @param inputFile

原始文件

* @param outputFile 水印输出文件

* @param waterMarkName

水印名字

*/

private static void waterMark(String inputFile, String

outputFile, String userPassWord, String ownerPassWord,

String waterMarkName, int permission)

{

try

{

PdfReader reader = new PdfReader(inputFile);

PdfStamper stamper = new PdfStamper(reader, new

FileOutputStream(outputFile));

// 设置密码

stamper.setEncryption(userPassWord.getBytes(), ownerPassWord.getBytes(),

permission, false);

BaseFont base =

BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",

BaseFont.NOT_EMBEDDED);

int total = reader.getNumberOfPages() +

1;

// Image image =

Image.getInstance(imageFilePath);

//

image.setAbsolutePosition(200, 400);

PdfContentByte

under;

int j = waterMarkName.length();

char c =

0;

int rise = 0;

for (int i = 1; i total;

i++)

{

rise = 500;

under =

stamper.getUnderContent(i);

// 添加图片

//

under.addImage(image);

under.beginText();

under.setColorFill(Color.CYAN);

under.setFontAndSize(base,

30);

// 设置水印文字字体倾斜 开始

if (j =

15)

{

under.setTextMatrix(200,

120);

for (int k = 0; k j;

k++)

{

under.setTextRise(rise);

c =

waterMarkName.charAt(k);

under.showText(c +

"");

rise -= 20;

}

}

else

{

under.setTextMatrix(180, 100);

for (int k = 0; k j; k++)

{

under.setTextRise(rise);

c = waterMarkName.charAt(k);

under.showText(c +

"");

rise -= 18;

}

}

// 字体设置结束

under.endText();

// 画一个圆

//

under.ellipse(250, 450, 350, 550);

//

under.setLineWidth(1f);

// under.stroke();

}

stamper.close();

}

catch (Exception

e)

{

e.printStackTrace();

}

}

/**

* 设置中文

*

* @return Font

*/

private static Font setChineseFont()

{

BaseFont base =

null;

Font fontChinese = null;

try

{

base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",

BaseFont.EMBEDDED);

fontChinese = new Font(base, 12,

Font.NORMAL);

}

catch (DocumentException e)

{

e.printStackTrace();

}

catch (IOException

e)

{

e.printStackTrace();

}

return fontChinese;

}

public static void main(String[] args)

{

generatePDFWithTxt(txtFilePath, pdfFilePath, "123", "水印文字", 16);

}

}

文章参考一些网络博客稍加修改调试,特此申明


网页名称:pdf加水印java代码 java给pdf加水印
文章链接:http://cdkjz.cn/article/dddegog.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220