PDF部分常用操作
1:多个pdf合并成一个pdf文件
2:多张图片合并成一个pdf文件;
3:pdf设置页眉页脚;
pdf页眉页脚构造类
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import java.io.IOException;
/**
* @Program wison-new-oa
* @ClassName MyHeaderFooter
* @Description MyHeaderFooter
* @Author liguoming
* @Date 2023-03-13 10:20
* @Version 1.0
**/
public class MyHeaderFooter extends PdfPageEventHelper {
public String oaCode;//支付申请表单编码
// 总页数
PdfTemplate totalPage;
BaseFont hfFont;
//无参构造方法
public MyHeaderFooter() {
super();
}
//有参构造方法
public MyHeaderFooter(String oaCode) {
super();
this.oaCode=oaCode;
try {
hfFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
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 {
PdfContentByte headAndFootPdfContent = writer.getDirectContent();
totalPage = headAndFootPdfContent.createTemplate(30, 16);
headAndFootPdfContent.saveState();
headAndFootPdfContent.beginText();
//设置中文
headAndFootPdfContent.setFontAndSize(hfFont, 8);
// //文档页头信息设置
// float x = document.top(-20);
// float x1 = document.top(-5);
// //页头信息中间
// headAndFootPdfContent.showTextAligned(PdfContentByte.ALIGN_CENTER, oaCode, (document.right() + document.left()) / 2, x, 0);
// //页头信息左面
// headAndFootPdfContent.showTextAligned(PdfContentByte.ALIGN_LEFT, oaCode,
// document.left() + 100, x1, 0);
// //页头信息中间
// headAndFootPdfContent.showTextAligned(PdfContentByte.ALIGN_CENTER, oaCode,
// (document.right() + document.left()) / 2, x1, 0);
// //页头信息右面
// headAndFootPdfContent.showTextAligned(PdfContentByte.ALIGN_RIGHT, " 单位:册", document.right() - 100, x1, 0);
//文档页脚信息设置
float y = document.bottom(-20);
float y1 = document.bottom(-35);
// //页脚信息左面
// headAndFootPdfContent.showTextAligned(PdfContentByte.ALIGN_LEFT, "储运部负责人:", document.left() + 100, y, 0);
// //页脚信息中间
// headAndFootPdfContent.showTextAligned(PdfContentByte.ALIGN_CENTER, " 库管员: ", (document.right() + document.left()) / 2, y, 0);
//页脚信息右面
headAndFootPdfContent.showTextAligned(PdfContentByte.ALIGN_RIGHT, " 单号:"+oaCode, document.right() - 100, y, 0);
//添加页码
//页脚信息中间
headAndFootPdfContent.showTextAligned(PdfContentByte.ALIGN_CENTER, "--第" + document.getPageNumber() + "页",
(document.right() + document.left()) / 2, y1, 0);
//在每页结束的时候把“第x页”信息写道模版指定位置
headAndFootPdfContent.addTemplate(totalPage, (document.right() + document.left()) / 2 + 15, y1);//定位“y页” 在具体的页面调试时候需要更改这xy的坐标
headAndFootPdfContent.endText();
headAndFootPdfContent.restoreState();
} catch (Exception de) {
throw new ExceptionConverter(de);
}
}
}
PDF工具类
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import java.io.*;
import java.util.List;
/**
* @Program wison-new-oa
* @ClassName PDFUtil
* @Description PDFUtil
* @Author liguoming
* @Date 2023-03-09 13:31
* @Version 1.0
**/
@Slf4j
public class PDFUtil {
/**
* 多个pdf合并一个pdf
* @param files
* @param targetPath
* @return
* @throws Exception
*/
public static File MulFileToOne(List<File> files, String targetPath) throws Exception {
PDFMergerUtility mergePdf = new PDFMergerUtility();
for (File f : files) {
if(f.exists() && f.isFile()){
// 循环添加要合并的pdf
mergePdf.addSource(f);
}
}
// 设置合并生成pdf文件名称
mergePdf.setDestinationFileName(targetPath);
// 合并pdf
mergePdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
for (File f : files) {
if(f.exists() && f.isFile()){
f.delete();
}
}
return new File(targetPath);
}
/**
*
* @param outPdfFilepath 生成pdf文件路径
* @param imageFiles 需要转换的图片File类Array,按array的顺序合成图片
*/
public static void imagesToPdf(String outPdfFilepath, List<File> imageFiles) throws Exception {
log.info("进入图片合成PDF工具方法");
File file = new File(outPdfFilepath);
// 第一步:创建一个document对象。
Document document = new Document();
document.setMargins(0, 0, 0, 0);
// 第二步:
// 创建一个PdfWriter实例,
PdfWriter.getInstance(document, new FileOutputStream(file));
// 第三步:打开文档。
document.open();
// 第四步:在文档中增加图片。
for(File tempFile : imageFiles) {
if (tempFile.getName().toLowerCase().endsWith(".bmp")
|| tempFile.getName().toLowerCase().endsWith(".jpg")
|| tempFile.getName().toLowerCase().endsWith(".jpeg")
|| tempFile.getName().toLowerCase().endsWith(".gif")
|| tempFile.getName().toLowerCase().endsWith(".png")) {
String temp = tempFile.getAbsolutePath();
log.info("图片路径:"+temp);
Image img = Image.getInstance(temp);
img.setAlignment(Image.ALIGN_CENTER);
img.scaleAbsolute(PageSize.A4);// 直接设定显示尺寸
// 根据图片大小设置页面,一定要先设置页面,再newPage(),否则无效
//document.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
document.setPageSize(PageSize.A4);
document.newPage();
document.add(img);
//保存到pdf之后,删除附件
tempFile.delete();
}
}
// 第五步:关闭文档。
document.close();
log.info("图片合成PDF完成");
}
/**
* 给pdf设置页眉页脚
*/
public static void setPDFHeaderFooter(File fileTemp, String outFile, String oaCode) {
try {
// Create output PDF
Document document = new Document(PageSize.A4);
File file = new File(outFile);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
document.open();
PdfContentByte cb = writer.getDirectContent();
writer.setPageEvent(new MyHeaderFooter(oaCode));// 页眉/页脚
// Load existing PDF
PdfReader reader = new PdfReader(new FileInputStream(fileTemp));
for (int index = 1; index <= reader.getNumberOfPages(); index++) {
PdfImportedPage page = writer.getImportedPage(reader, index);
// 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();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}