PDF操作

package com.pdf.util;

import com.itextpdf.io.source.ByteArrayOutputStream;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.HorizontalAlignment;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.UnitValue;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import com.pdf.entity.pdf;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PdfUtils {
public static final String DEST2 = "E:\test4.pdf";//输出文件路径
public static void OutPutTableFile(String dest) throws Exception{
PdfDocument pdfDoc = new PdfDocument(new com.itextpdf.kernel.pdf.PdfWriter(dest));
com.itextpdf.layout.Document doc = new com.itextpdf.layout.Document(pdfDoc);

PdfFont sysFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
Table table = new Table(new float[]{1,1,1,7}).setWidth(UnitValue.createPercentValue(100));
// Cell cell1=new Cell().add(new Paragraph("考生序号")).setFont(sysFont).setBackgroundColor(new DeviceRgb(221,234,238));
Cell cell1=new Cell().add(new Paragraph("考生序号")).setFont(sysFont).setFontSize(10).setTextAlignment(TextAlignment.CENTER);
cell1.setWidth(Float.parseFloat("50"));
Cell cell2=new Cell().add(new Paragraph("姓名")).setFont(sysFont).setFontSize(10).setTextAlignment(TextAlignment.CENTER);
// Cell cell3=new Cell().add(new Paragraph("座位号")).setFont(sysFont).setBorder(new SolidBorder(new DeviceRgb(221,234,238), 1));
cell2.setWidth(Float.parseFloat("50"));
Cell cell3=new Cell().add(new Paragraph("座位号")).setFont(sysFont).setFontSize(10).setTextAlignment(TextAlignment.CENTER);
// Cell cell4=new Cell().add(new Paragraph("更正栏")).setFont(sysFont).setBorder(Border.NO_BORDER);
cell3.setWidth(Float.parseFloat("50"));
Cell cell4=new Cell().add(new Paragraph("更正栏")).setFont(sysFont).setFontSize(10).setTextAlignment(TextAlignment.CENTER);
cell4.setWidth(Float.parseFloat("100"));
table.addCell(cell1);
table.addCell(cell2);
table.addCell(cell3);
table.addCell(cell4);
//从数据库里面查询出数据
String str = "mybatis-config.xml";
InputStream in = Resources.getResourceAsStream(str);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
SqlSession session = sqlSessionFactory.openSession();
List<pdf> pdfList = session.selectList("SelectPdf");
for (pdf p :
pdfList) {
for (int i=0;i<1;i++){
Cell cell5=new Cell().add(new Paragraph(String.valueOf(p.getExamNo()))).setFont(sysFont).setFontSize(10).setTextAlignment(TextAlignment.CENTER);
table.addCell(cell5);
Cell cell6=new Cell().add(new Paragraph(p.getUsername())).setFont(sysFont).setFontSize(10).setTextAlignment(TextAlignment.CENTER);
table.addCell(cell6);
Cell cell7=new Cell().add(new Paragraph(String.valueOf(p.getSitRoom()))).setFont(sysFont).setFontSize(10).setTextAlignment(TextAlignment.CENTER);
table.addCell(cell7);
Cell cell8=new Cell().add(new Paragraph(p.getChangTiele())).setFont(sysFont).setFontSize(10).setTextAlignment(TextAlignment.CENTER);
table.addCell(cell8);
}
}
doc.add(table.setHorizontalAlignment(HorizontalAlignment.CENTER));
doc.close();
}
//填充表单字段
// public static final String DEST2 = "E:\test4.pdf";//文件路径
public static void OutPutForm(String fileName,String finalPath) throws IOException, DocumentException {
PdfReader reader = new PdfReader(fileName);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
/* 将要生成的目标PDF文件名称 */
PdfStamper ps = new PdfStamper(reader, bos);
PdfContentByte under = ps.getUnderContent(1);
/* 使用中文字体 */
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
fontList.add(bf);
/* 取出报表模板中的所有字段 */
AcroFields fields = ps.getAcroFields();
fields.setSubstitutionFonts(fontList);
fillData(fields, data());
/* 必须要调用这个,否则文档不会生成的 */
ps.setFormFlattening(true);
ps.close();
OutputStream fos = new FileOutputStream(finalPath);
fos.write(bos.toByteArray());
fos.flush();
fos.close();
bos.close();
}

public static void fillData(AcroFields fields, Map<String, String> data)
throws IOException, DocumentException {
for (String key : data.keySet()) {
String value = data.get(key);
fields.setField(key, value); // 为字段赋值,注意字段名称是区分大小写的
}
}

public static Map<String, String> data() {
Map<String, String> data = new HashMap<String, String>();
data.put("examTime", "2019年05月29日");
data.put("examName", "国家通用语言文字综合能力测试(GYC)");
data.put("examLvl", "四级");
data.put("positionName","北京大学");
data.put("roomNo","301");
return data;
}

public static void addTail(String TempPdf,String TempPdf2,String finalPath) throws IOException, DocumentException {
FileOutputStream outputStream = new FileOutputStream(finalPath,true);
PdfReader reader = new PdfReader(TempPdf); //读取pdf模板
PdfReader reader1 = new PdfReader(TempPdf2); //读取pdf2模板
Rectangle pagesize = reader.getPageSize(1);
com.itextpdf.text.Document document = new com.itextpdf.text.Document(pagesize);
PdfWriter writer = PdfWriter.getInstance(document,outputStream);
document.open();
PdfContentByte pdfContentByte = writer.getDirectContentUnder();
PdfImportedPage pageTemplate = writer.getImportedPage(reader, 1);
PdfImportedPage pageTemplate1 = writer.getImportedPage(reader1, 1);
pdfContentByte.addTemplate(pageTemplate,0,-50);
pdfContentByte.addTemplate(pageTemplate1,0,0);
// document.add(new Paragraph("Hello World"));
document.close();
reader.close();
File file1 = new File(TempPdf2);
if (file1.exists()){
file1.delete();
}

File file = new File(TempPdf);
if (file.exists()){
file.delete();
}
System.out.println("执行完成");
}



public static void main(String[] args) throws Exception {

String fileNames = "C://Users//Administrator//Desktop//座位一览表.pdf"; // pdf模板
String finalPath = "E://test005.pdf";

String TempPdf = "E://test4.pdf";
String TempPdf2 = "E://test005.pdf";
String finaPath = "E://chenligeng.pdf";

OutPutTableFile(TempPdf);
OutPutForm(fileNames,finalPath);
addTail(TempPdf,TempPdf2,finaPath);
}
}
原文地址:https://www.cnblogs.com/chenligeng/p/11127248.html