網上百度到的基本都是生成pdf的時候,添加頁眉頁腳,但是假如對已有的pdf添加頁眉頁腳就比較麻煩,突然想到了可以曲線救國,用itext進行復制pdf的時候,在添加頁眉頁腳,最后可以成功的。
生成pdf的代碼忘記參考誰的了。。。。
生成Pdf的代碼如下:
/**
* @author WGR
* @create 2020/8/18 -- 15:57
*/
public class PdfReport {
// main測試
public static void main(String[] args) throws Exception {
try {
// 1.新建document對象
Document document = new Document(PageSize.A4);// 建立一個Document對象
// 2.建立一個書寫器(Writer)與document對象關聯
File file = new File("D:\\PDFDemo.pdf");
// file.createNewFile();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
// writer.setPageEvent(new Watermark("HELLO ITEXTPDF"));// 水印
// writer.setPageEvent(new MyHeaderFooter());// 頁眉/頁腳
// // 3.打開文檔
document.open();
document.addTitle("Title@PDF-Java");// 標題
document.addAuthor("Author@umiz");// 作者
document.addSubject("Subject@iText pdf sample");// 主題
document.addKeywords("Keywords@iTextpdf");// 關鍵字
document.addCreator("Creator@umiz`s");// 創建者
// 4.向文檔中添加內容
new PdfReport().generatePDF(document);
// 5.關閉文檔
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 定義全局的字體靜態變量
private static Font titlefont;
private static Font headfont;
private static Font keyfont;
private static Font textfont;
// 最大寬度
private static int maxWidth = 520;
// 靜態代碼塊
static {
try {
// 不同字體(這里定義為同一種字體:包含不同字號、不同style)
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
titlefont = new Font(bfChinese, 16, Font.BOLD);
headfont = new Font(bfChinese, 14, Font.BOLD);
keyfont = new Font(bfChinese, 10, Font.BOLD);
textfont = new Font(bfChinese, 10, Font.NORMAL);
} catch (Exception e) {
e.printStackTrace();
}
}
// 生成PDF文件
public void generatePDF(Document document) throws Exception {
// 段落
Paragraph paragraph = new Paragraph("美好的一天從早起開始!", titlefont);
paragraph.setAlignment(1); //設置文字居中 0靠左 1,居中 2,靠右
paragraph.setIndentationLeft(12); //設置左縮進
paragraph.setIndentationRight(12); //設置右縮進
paragraph.setFirstLineIndent(24); //設置首行縮進
paragraph.setLeading(20f); //行間距
paragraph.setSpacingBefore(5f); //設置段落上空白
paragraph.setSpacingAfter(10f); //設置段落下空白
// 直線
Paragraph p1 = new Paragraph();
p1.add(new Chunk(new LineSeparator()));
// 點線
Paragraph p2 = new Paragraph();
p2.add(new Chunk(new DottedLineSeparator()));
// 超鏈接
Anchor anchor = new Anchor("baidu");
anchor.setReference("www.baidu.com");
// 定位
Anchor gotoP = new Anchor("goto");
gotoP.setReference("#top");
// 添加圖片
Image image = Image.getInstance("C:\\Users\\asus\\Desktop\\123.jpg");
image.setAlignment(Image.ALIGN_CENTER);
image.scalePercent(40); //依照比例縮放
// 表格
PdfPTable table = createTable(new float[] { 40, 120, 120, 120, 80, 80 });
table.addCell(createCell("美好的一天", headfont, Element.ALIGN_LEFT, 6, false));
table.addCell(createCell("早上9:00", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell("中午11:00", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell("中午13:00", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell("下午15:00", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell("下午17:00", keyfont, Element.ALIGN_CENTER));
table.addCell(createCell("晚上19:00", keyfont, Element.ALIGN_CENTER));
Integer totalQuantity = 0;
for (int i = 0; i < 5; i++) {
table.addCell(createCell("起床1", textfont));
table.addCell(createCell("吃午飯1", textfont));
table.addCell(createCell("午休1", textfont));
table.addCell(createCell("下午茶", textfont));
table.addCell(createCell("回家", textfont));
table.addCell(createCell("吃晚飯", textfont));
totalQuantity ++;
}
table.addCell(createCell("總計", keyfont));
table.addCell(createCell("", textfont));
table.addCell(createCell("", textfont));
table.addCell(createCell("", textfont));
table.addCell(createCell(String.valueOf(totalQuantity) + "件事", textfont));
table.addCell(createCell("", textfont));
document.add(paragraph);
document.add(anchor);
document.add(p2);
document.add(gotoP);
document.add(p1);
document.add(table);
document.add(image);
}
/**------------------------創建表格單元格的方法start----------------------------*/
/**
* 創建單元格(指定字體)
* @param value
* @param font
* @return
*/
public PdfPCell createCell(String value, Font font) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setPhrase(new Phrase(value, font));
return cell;
}
/**
* 創建單元格(指定字體、水平..)
* @param value
* @param font
* @param align
* @return
*/
public PdfPCell createCell(String value, Font font, int align) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setPhrase(new Phrase(value, font));
return cell;
}
/**
* 創建單元格(指定字體、水平居..、單元格跨x列合並)
* @param value
* @param font
* @param align
* @param colspan
* @return
*/
public PdfPCell createCell(String value, Font font, int align, int colspan) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setColspan(colspan);
cell.setPhrase(new Phrase(value, font));
return cell;
}
/**
* 創建單元格(指定字體、水平居..、單元格跨x列合並、設置單元格內邊距)
* @param value
* @param font
* @param align
* @param colspan
* @param boderFlag
* @return
*/
public PdfPCell createCell(String value, Font font, int align, int colspan, boolean boderFlag) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setColspan(colspan);
cell.setPhrase(new Phrase(value, font));
cell.setPadding(3.0f);
if (!boderFlag) {
cell.setBorder(0);
cell.setPaddingTop(15.0f);
cell.setPaddingBottom(8.0f);
} else if (boderFlag) {
cell.setBorder(0);
cell.setPaddingTop(0.0f);
cell.setPaddingBottom(15.0f);
}
return cell;
}
/**
* 創建單元格(指定字體、水平..、邊框寬度:0表示無邊框、內邊距)
* @param value
* @param font
* @param align
* @param borderWidth
* @param paddingSize
* @param flag
* @return
*/
public PdfPCell createCell(String value, Font font, int align, float[] borderWidth, float[] paddingSize, boolean flag) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setPhrase(new Phrase(value, font));
cell.setBorderWidthLeft(borderWidth[0]);
cell.setBorderWidthRight(borderWidth[1]);
cell.setBorderWidthTop(borderWidth[2]);
cell.setBorderWidthBottom(borderWidth[3]);
cell.setPaddingTop(paddingSize[0]);
cell.setPaddingBottom(paddingSize[1]);
if (flag) {
cell.setColspan(2);
}
return cell;
}
/**------------------------創建表格單元格的方法end----------------------------*/
/**--------------------------創建表格的方法start------------------- ---------*/
/**
* 創建默認列寬,指定列數、水平(居中、右、左)的表格
* @param colNumber
* @param align
* @return
*/
public PdfPTable createTable(int colNumber, int align) {
PdfPTable table = new PdfPTable(colNumber);
try {
table.setTotalWidth(maxWidth);
table.setLockedWidth(true);
table.setHorizontalAlignment(align);
table.getDefaultCell().setBorder(1);
} catch (Exception e) {
e.printStackTrace();
}
return table;
}
/**
* 創建指定列寬、列數的表格
* @param widths
* @return
*/
public PdfPTable createTable(float[] widths) {
PdfPTable table = new PdfPTable(widths);
try {
table.setTotalWidth(maxWidth);
table.setLockedWidth(true);
table.setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setBorder(1);
} catch (Exception e) {
e.printStackTrace();
}
return table;
}
/**
* 創建空白的表格
* @return
*/
public PdfPTable createBlankTable() {
PdfPTable table = new PdfPTable(1);
table.getDefaultCell().setBorder(0);
table.addCell(createCell("", keyfont));
table.setSpacingAfter(20.0f);
table.setSpacingBefore(20.0f);
return table;
}
/**--------------------------創建表格的方法end------------------- ---------*/
}
添加頁眉頁腳的類
/**
* @author WGR
* @create 2020/8/18 -- 15:59
*/
public class MyHeaderFooter extends PdfPageEventHelper {
// 總頁數
PdfTemplate totalPage;
Font hfFont;
{
try {
hfFont = new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 8, Font.NORMAL);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 打開文檔時,創建一個總頁數的模版
@Override
public void onOpenDocument(PdfWriter writer, Document document) {
PdfContentByte cb =writer.getDirectContent();
totalPage = cb.createTemplate(30, 16);
}
// 一頁加載完成觸發,寫入頁眉和頁腳
@Override
public void onEndPage(PdfWriter writer, Document document) {
PdfContentByte cb =writer.getDirectContent();
totalPage = cb.createTemplate(30, 16);
PdfPTable table = new PdfPTable(3);
try {
table.setTotalWidth(PageSize.A4.getWidth() - 100);
table.setWidths(new int[] { 24, 24, 3});
table.setLockedWidth(true);
table.getDefaultCell().setFixedHeight(-10);
table.getDefaultCell().setBorder(Rectangle.BOTTOM);
table.addCell(new Paragraph("我是頁眉/頁腳", hfFont));// 可以直接使用addCell(str),不過不能指定字體,中文無法顯示
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell(new Paragraph("第" + writer.getPageNumber() + "頁/", hfFont));
// 總頁數
PdfPCell cell = new PdfPCell(Image.getInstance(totalPage));
cell.setBorder(Rectangle.BOTTOM);
table.addCell(cell);
// 將頁眉寫到document中,位置可以指定,指定到下面就是頁腳
table.writeSelectedRows(0, -1, 50, PageSize.A4.getHeight() - 20, writer.getDirectContent());
} catch (Exception de) {
throw new ExceptionConverter(de);
}
}
// 全部完成后,將總頁數的pdf模版寫到指定位置
@Override
public void onCloseDocument(PdfWriter writer, Document document) {
String text = "總" + (writer.getPageNumber()) + "頁";
ColumnText.showTextAligned(totalPage, Element.ALIGN_LEFT, new Paragraph(text,hfFont), 2, 2, 0);
}
}
如果想指定頁眉為圖片的可以用:
class PdfHeaderFooter extends PdfPageEventHelper {
Font bfChinese;
int fontSize = 10;
Image image;
@Override
public void onOpenDocument(PdfWriter writer, Document document) {
try {
bfChinese = new Font(BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), fontSize, Font.NORMAL, BaseColor.GRAY);
image = Image.getInstance(PDFUtil.class.getResource("/template/small.png"));
image.scalePercent(50);
image.setAbsolutePosition(8, document.top());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void onEndPage(PdfWriter writer, Document document) {
try {
Rectangle rect = new Rectangle(0, 38, 50, 50);
String line1 = String.format("- %d -", writer.getPageNumber());
ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER,
new Phrase(line1, bfChinese),
(document.rightMargin() + document.right() + document.leftMargin() - document.left() - bfChinese.getBaseFont().getWidthPoint(line1, fontSize) / 2) / 2.0F,
document.bottom() - 22,
0);
String line2 = "本文件保密,未經允許,不得向任何第三方提供。";
ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER,
new Phrase(line2, bfChinese),
(document.rightMargin() + document.right() + document.leftMargin() - document.left()) / 2.0F,
document.bottom() - 32,
0);
writer.getDirectContent().addImage(image);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
最終要的就是下面的方法:
public static void main(String[] args) throws DocumentException, IOException {
// Create output PDF
Document document = new Document(PageSize.A4);
File file = new File("D:\\PDFDemo1.pdf");
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
document.open();
PdfContentByte cb = writer.getDirectContent();
writer.setPageEvent(new MyHeaderFooter());// 頁眉/頁腳
// Load existing PDF
File file2 = new File("D:\\PDFDemo.pdf");
PdfReader reader = new PdfReader(new FileInputStream(file2));
PdfImportedPage page = writer.getImportedPage(reader, 1);
// Copy first page of existing PDF into output PDF
document.newPage();
cb.addTemplate(page, 0, 0);
// Add your new data / text here
// for example...
// document.addKeywords("Keywords@iTextpdf");// 關鍵字
// document.addCreator("Creator@umiz`s");// 創建者
// document.add(new Paragraph("my timestamp"));
document.close();
}
這個只是一頁的,假如多頁,可以獲取源pdf的頁面進行for循環就可以了。