代码示例:
import com.itextpdf.text.*;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.List;
import com.itextpdf.text.pdf.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
/**
* Created by roztop1 on 2017/3/31.
*/
public class TestPDF {
private static final String FILE_PATH = "D:/test.pdf";
// 1.新建document对象
private Document document = null;
private File file = null;
@Before
public void init() throws IOException {
document = new Document();
file = getFile(FILE_PATH);
}
@After
public void open() throws IOException {
openFile(file);
}
/**
* 打开本地文件
*
* @param file
* @throws IOException
*/
public static void openFile(File file) throws IOException {
Desktop.getDesktop().open(file);
}
public static void openFile(String file_path) throws IOException {
Desktop.getDesktop().open(getFile(file_path));
}
/**
* 获取文件
*
* @param filePath
* @return
*/
public static File getFile(String filePath) {
File file = new File(filePath);
return file;
}
/**
* 初体验
*
* @throws DocumentException
* @throws FileNotFoundException
*/
@Test
public void testStart() throws DocumentException, IOException {
// 2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
// 创建 PdfWriter 对象 第一个参数是对文档对象的引用,第二个参数是文件的实际名称,在该名称中还会给出其输出路径。
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
// 3.打开文档
document.open();
// 4.添加一个内容段落
document.add(new Paragraph("Hello World!PDF"));
// 5.关闭文档
document.close();
writer.close();
}
/**
* PDF设置属性
*
* @throws IOException
* @throws DocumentException
*/
@Test
public void setPDFFiled() throws IOException, DocumentException {
//建立一个书写器
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
//打开文件
document.open();
//添加内容
document.add(new Paragraph("can't chines to PDF"));
//设置属性
//标题
document.addTitle("this is title");
//作者
document.addAuthor("NOW");
//主题
document.addSubject("this is subject");
//关键字
document.addKeywords("PDF");
//创建时间
document.addCreationDate();
//应用程序
document.addCreator("pdf");
//关闭文档
document.close();
//关闭书写器
writer.close();
}
/**
* PDF写入img
*
* @throws IOException
* @throws DocumentException
*/
@Test
public void setPDFImg() throws IOException, DocumentException {
//建立一个书写器
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
//打开文件
document.open();
//添加内容
document.add(new Paragraph("HD content here"));
//图片1
Image image1 = Image.getInstance(new URL("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1490939858438&di=2843ce3aa39a7d6c261b87ab58b13d93&imgtype=0&src=http%3A%2F%2Fv1.qzone.cc%2Fpic%2F201701%2F22%2F16%2F54%2F5884732f13e05732.jpg%2521600x600.jpg"));
//设置图片位置的x轴和y周
image1.setAbsolutePosition(100f, 550f);
//设置图片的宽度和高度
image1.scaleAbsolute(200, 200);
//将图片1添加到pdf文件中
document.add(image1);
//图片2
Image image2 = Image.getInstance(new URL("https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1490929743&di=b1c8504e10d04ca6736c9134d1c57fee&src=http://v1.qzone.cc/pic/201701/22/16/53/5884732676930797.jpg!600x600.jpg"));
//将图片2添加到pdf文件中
document.add(image2);
//关闭文档
document.close();
//关闭书写器
writer.close();
}
/**
* PDF中创建表格
*/
@Test
public void setTable() throws FileNotFoundException, DocumentException {
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
//打开文件
document.open();
//添加内容
document.add(new Paragraph("HD content here"));
// 3列的表.
PdfPTable table = new PdfPTable(3);
table.setWidthPercentage(100); // 宽度100%填充
table.setSpacingBefore(10f); // 前间距
table.setSpacingAfter(10f); // 后间距
ArrayList<PdfPRow> listRow = table.getRows();
//设置列宽
float[] columnWidths = {1f, 2f, 3f};
table.setWidths(columnWidths);
//行1
PdfPCell cells1[] = new PdfPCell[3];
PdfPRow row1 = new PdfPRow(cells1);
//单元格
cells1[0] = new PdfPCell(new Paragraph("111"));//单元格内容
cells1[0].setBorderColor(BaseColor.BLUE);//边框验证
cells1[0].setPaddingLeft(20);//左填充20
cells1[0].setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
cells1[0].setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
cells1[1] = new PdfPCell(new Paragraph("222"));
cells1[2] = new PdfPCell(new Paragraph("333"));
//行2
PdfPCell cells2[] = new PdfPCell[3];
PdfPRow row2 = new PdfPRow(cells2);
cells2[0] = new PdfPCell(new Paragraph("444"));
//把第一行添加到集合
listRow.add(row1);
listRow.add(row2);
//把表格添加到文件中
document.add(table);
//关闭文档
document.close();
//关闭书写器
writer.close();
}
/**
* PDF中创建列表
*/
@Test
public void setList() throws FileNotFoundException, DocumentException {
//建立一个书写器
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
//打开文件
document.open();
//添加内容
document.add(new Paragraph("HD content here"));
//添加有序列表
List orderedList = new List(List.ORDERED);
orderedList.add(new ListItem("Item one"));
orderedList.add(new ListItem("Item two"));
orderedList.add(new ListItem("Item three"));
document.add(orderedList);
//关闭文档
document.close();
//关闭书写器
writer.close();
}
/**
* PDF中设置样式/格式化输出,输出中文内容,必须引入itext-asian.jar
*/
@Test
public void setStyle() throws IOException, DocumentException {
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
//打开文件
document.open();
//中文字体,解决中文不能显示问题
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
//蓝色字体
Font blueFont = new Font(bfChinese);
blueFont.setColor(BaseColor.BLUE);
//段落文本
Paragraph paragraphBlue = new Paragraph("paragraphOne blue front", blueFont);
document.add(paragraphBlue);
//绿色字体
Font greenFont = new Font(bfChinese);
greenFont.setColor(BaseColor.GREEN);
//创建章节
Paragraph chapterTitle = new Paragraph("段落标题xxxx", greenFont);
Chapter chapter1 = new Chapter(chapterTitle, 1);
chapter1.setNumberDepth(0);
Paragraph sectionTitle = new Paragraph("部分标题", greenFont);
Section section1 = chapter1.addSection(sectionTitle);
Paragraph sectionContent = new Paragraph("部分内容", blueFont);
section1.add(sectionContent);
//将章节添加到文章中
document.add(chapter1);
//关闭文档
document.close();
//关闭书写器
writer.close();
}
/**
* PDF设置密码
*
* @throws FileNotFoundException
* @throws DocumentException
*/
@Test
public void setPWD() throws FileNotFoundException, DocumentException {
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
//用户密码
String userPassword = "123456";
//拥有者密码
String ownerPassword = "hd";
writer.setEncryption(userPassword.getBytes(), ownerPassword.getBytes(), PdfWriter.ALLOW_PRINTING,
PdfWriter.ENCRYPTION_AES_128);
// 打开文件
document.open();
//添加内容
document.add(new Paragraph("password !!!!"));
// 关闭文档
document.close();
// 关闭书写器
writer.close();
}
/**
* 设置权限
*/
@Test
public void setPermission() throws Exception {
// 建立一个书写器
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
// 只读权限
writer.setEncryption("".getBytes(), "".getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
// 打开文件
document.open();
// 添加内容
document.add(new Paragraph("password !!!!"));
// 关闭文档
document.close();
// 关闭书写器
writer.close();
}
/**
* 读取/修改已有的PDF文件
*/
@Test
public void readOrUpdatePDF() throws Exception {
//读取pdf文件
PdfReader pdfReader = new PdfReader(FILE_PATH);
//修改器
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream("D:/test2.pdf"));
Image image = Image.getInstance(new URL("https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1490929743&di=b1c8504e10d04ca6736c9134d1c57fee&src=http://v1.qzone.cc/pic/201701/22/16/53/5884732676930797.jpg!600x600.jpg"));
image.scaleAbsolute(50, 50);
image.setAbsolutePosition(0, 700);
for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
PdfContentByte content = pdfStamper.getUnderContent(i);
content.addImage(image);
}
pdfStamper.close();
openFile("D:/test2.pdf");
}
}