有我的(死需求)跑過來跟你說,這些都給我輸出成報告,pdf格式的,因此就有了下面這個,作一下筆記,之後有用直接過來拿。在網上找了一下,發現你們都是在用itext。 iText是著名的開放項目,是用於生成PDF文檔的一個java類庫。經過iText不只能夠生成PDF或rtf的文檔,並且能夠將XML、Html文件轉化爲PDF文件。html
itextpdf.com/java
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
複製代碼
itext有不少功能,這裏先說基本的操做。其餘更多高級的操做,能夠繼續看下面的。 基本處理步驟以下僞代碼:bash
//Step 1—Create a Document.
Document document = new Document();
//Step 2—Get a PdfWriter instance.
PdfWriter.getInstance(document, new FileOutputStream(FILE_DIR + "createSamplePDF.pdf"));
//Step 3—Open the Document.
document.open();
//Step 4—Add content.
document.add(new Paragraph("Hello World"));
//Step 5—Close the Document.
document.close();
複製代碼
這裏有個特別注意的是,中文必需要指定字體,便是BaseFontmaven
public class PDFReport {
private final static String REPORT_PATH = "C:/air-navi-monitor/report";
private static void exportReport() {
BaseFont bf;
Font font = null;
Font font2 = null;
try {
bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
BaseFont.NOT_EMBEDDED);//建立字體
font = new Font(bf, 12);//使用字體
font2 = new Font(bf, 12, Font.BOLD);//使用字體
} catch (Exception e) {
e.printStackTrace();
}
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream("E:/2.pdf"));
document.open();
Paragraph elements = new Paragraph("常州武進1區飛行報告", font2);
elements.setAlignment(Paragraph.ALIGN_CENTER);
document.add(elements);
Image png = Image.getInstance("E:\\test.png");
png.setAlignment(Image.ALIGN_CENTER);
document.add(png);
document.add(new Paragraph("任務編號:20190701 開始日期:20190701", font));
document.add(new Paragraph("任務名稱:常州武進1區 結束日期:20190701", font));
document.add(new Paragraph("平均飛行高度:100m 平均飛行速度:100km/h", font));
document.add(new Paragraph("任務面積:1000㎡ 結束日期:20190701", font));
document.add(new Paragraph("飛行總時長:1000㎡", font));
document.addCreationDate();
document.close();
} catch (Exception e) {
System.out.println("file create exception");
}
}
/**
* 生成pdf文件
*
* @param missionReport
* @return
*/
public static String exportReport(MissionReportTb missionReport) throws AirNaviException {
String pdfPath = null;
String imgPath = Shape2Image.getImgPath(missionReport.getMissionID());
// String imgPath = "E:\\test.png";
String finalReportStr = missionReport.getMissionReport();
MissionReport finalReport = JSONObject.parseObject(finalReportStr, MissionReport.class);
BaseFont bf;
Font font = null;
Font font2 = null;
try {
bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
BaseFont.NOT_EMBEDDED);//建立字體
font = new Font(bf, 12);//使用字體
font2 = new Font(bf, 12, Font.BOLD);//使用字體
} catch (Exception e) {
e.printStackTrace();
}
Document document = new Document();
try {
File dir = new File(REPORT_PATH);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(REPORT_PATH + File.separator + missionReport.getMissionID() + ".pdf");
if (!file.exists()) {
file.createNewFile();
}
PdfWriter.getInstance(document, new FileOutputStream(REPORT_PATH + File.separator + missionReport.getMissionID() + ".pdf"));
document.open();
Paragraph elements = new Paragraph(missionReport.getMissionName() + "飛行報告", font2);
elements.setAlignment(Paragraph.ALIGN_CENTER);
document.add(elements);
Image png = Image.getInstance(imgPath);
// https://blog.csdn.net/lingbo89/article/details/76177825
float documentWidth = document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin();
float documentHeight = documentWidth / 580 * 320;//從新設置寬高
png.scaleAbsolute(documentWidth, documentHeight);//從新設置寬高
png.scalePercent(50);
// 根據域的大小縮放圖片
// image.scaleToFit(signRect.getWidth(), signRect.getHeight());
png.setAlignment(Image.ALIGN_CENTER);
document.add(png);
document.add(new Paragraph("任務編號:" + missionReport.getMissionCode() + ",開始日期:" + finalReport.getStartTime(), font));
document.add(new Paragraph("任務名稱:" + missionReport.getMissionName() + ",結束日期:" + finalReport.getEndTime(), font));
document.add(new Paragraph("平均飛行高度:" + finalReport.getAvgFlightHeight() + "m" + ",平均飛行速度:" + finalReport.getAvgFlightSpeed() + "km/h", font));
document.add(new Paragraph("任務面積:" + finalReport.getMissionArea() + "㎡" + ",飛行總時長:" + finalReport.getFlightDuration() + "min", font));
document.addCreationDate();
document.close();
pdfPath = file.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
System.out.println("file create exception");
throw new AirNaviException("生成PDF失敗:" + e.getMessage());
}
return pdfPath;
}
public static void main(String[] args) throws AirNaviException {
String report = "{\"detailMissionReport\":[{\"avgFlightHeight\":119.7,\"avgFlightSpeed\":71.1,\"endPoint\":\"113.27484,22.86843\",\"endTime\":\"2019-09-17 17:47:07\",\"flightDuration\":9,\"reportID\":1,\"startPoint\":\"113.31429,22.78240\",\"startTime\":\"2019-09-17 17:38:03\",\"statisticsTimes\":505}],\"missionReport\":{\"avgFlightHeight\":119.7,\"avgFlightSpeed\":71.1,\"endPoint\":\"113.31429,22.78240\",\"endTime\":\"2019-09-17 17:47:07\",\"flightDuration\":9,\"reportID\":1,\"startPoint\":\"113.31429,22.78240\",\"startTime\":\"2019-09-17 17:38:03\",\"statisticsTimes\":0},\"missionArea\":0.0,\"missionCode\":\"M001\",\"missionID\":\"888813ddef6646cd9bfaba5abb748a43\",\"missionName\":\"德勝航點M008\",\"missionStatus\":1,\"missionType\":0,\"plannedFlightTime\":\"20190909\"}";
MissionReportTb missionReportTb = JSONObject.parseObject(report, MissionReportTb.class);
exportReport(missionReportTb);
}
}
複製代碼
首先你的製做一個pdf模板:測試
1.先用word作出模板界面字體
2.文件另存爲pdf格式文件大數據
3.經過Adobe Acrobat pro軟件打開剛剛用word轉換成的pdf文件(注:若是沒有這個軟件能夠經過個人百度雲下載,連接:pan.baidu.com/s/1pL2klzt)…ui
4.點擊右邊的"準備表單"按鈕,選擇"測試.pdf"選擇開始編碼
進去到編輯頁面,打開後它會自動偵測並命名錶單域,右鍵表單域,點擊屬性,出現文本域屬性對話框(其實無需任何操做,通常狀況下不須要修改什麼東西,至少我沒有修改哦。若是你想修改fill1等信息,能夠進行修改)spa
5.作完上面的工做後,直接"另存爲"將pdf存儲就能夠
以上部分是製做pdf模板操做,上述完成後,就開始經過程序來根據pdf模板生成pdf文件了,上java程序:
public class Snippet {
// 利用模板生成pdf
public static void fillTemplate() {
// 模板路徑
String templatePath = "E:/測試3.pdf";
// 生成的新文件路徑
String newPDFPath = "E:/ceshi.pdf";
PdfReader reader;
FileOutputStream out;
ByteArrayOutputStream bos;
PdfStamper stamper;
try {
out = new FileOutputStream(newPDFPath);// 輸出流
reader = new PdfReader(templatePath);// 讀取pdf模板
bos = new ByteArrayOutputStream();
stamper = new PdfStamper(reader, bos);
AcroFields form = stamper.getAcroFields();
String[] str = {"123456789", "TOP__ONE", "男", "1991-01-01", "130222111133338888", "河北省保定市"};
int i = 0;
java.util.Iterator<String> it = form.getFields().keySet().iterator();
while (it.hasNext()) {
String name = it.next().toString();
System.out.println(name);
form.setField(name, str[i++]);
}
stamper.setFormFlattening(true);// 若是爲false那麼生成的PDF文件還能編輯,必定要設爲true
stamper.close();
Document doc = new Document();
PdfCopy copy = new PdfCopy(doc, out);
doc.open();
PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
copy.addPage(importPage);
doc.close();
} catch (IOException e) {
System.out.println(1);
} catch (DocumentException e) {
System.out.println(2);
}
}
public static void main(String[] args) {
fillTemplate();
}
}
複製代碼
運行結果以下
一、頁面大小,頁面背景色,頁邊空白,Title,Author,Subject,Keywords
核心代碼:
//頁面大小
Rectangle rect = new Rectangle(PageSize.B5.rotate());
//頁面背景色
rect.setBackgroundColor(BaseColor.ORANGE);
Document doc = new Document(rect);
PdfWriter writer = PdfWriter.getInstance(doc, out);
//PDF版本(默認1.4)
writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2);
//文檔屬性
doc.addTitle("Title@sample");
doc.addAuthor("Author@rensanning");
doc.addSubject("Subject@iText sample");
doc.addKeywords("Keywords@iText");
doc.addCreator("Creator@iText");
//頁邊空白
doc.setMargins(10, 20, 30, 40);
doc.open();
doc.add(new Paragraph("Hello World"));
複製代碼
輸出結果:
二、設置密碼
核心代碼:
PdfWriter writer = PdfWriter.getInstance(doc, out);
// 設置密碼爲:"World"
writer.setEncryption("Hello".getBytes(), "World".getBytes(),
PdfWriter.ALLOW_SCREENREADERS,
PdfWriter.STANDARD_ENCRYPTION_128);
doc.open();
doc.add(new Paragraph("Hello World"));
複製代碼
輸出結果:
三、添加Page 核心代碼:
document.open();
document.add(new Paragraph("First page"));
document.add(new Paragraph(Document.getVersion()));
document.newPage();
writer.setPageEmpty(false);
document.newPage();
document.add(new Paragraph("New page"));
複製代碼
四、添加水印(背景圖)
//圖片水印
PdfReader reader = new PdfReader(FILE_DIR + "setWatermark.pdf");
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR
+ "setWatermark2.pdf"));
Image img = Image.getInstance("resource/watermark.jpg");
img.setAbsolutePosition(200, 400);
PdfContentByte under = stamp.getUnderContent(1);
under.addImage(img);
//文字水印
PdfContentByte over = stamp.getOverContent(2);
over.beginText();
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI,
BaseFont.EMBEDDED);
over.setFontAndSize(bf, 18);
over.setTextMatrix(30, 30);
over.showTextAligned(Element.ALIGN_LEFT, "DUPLICATE", 230, 430, 45);
over.endText();
//背景圖
Image img2 = Image.getInstance("resource/test.jpg");
img2.setAbsolutePosition(0, 0);
PdfContentByte under2 = stamp.getUnderContent(3);
under2.addImage(img2);
stamp.close();
reader.close();
複製代碼
五、插入Chunk, Phrase, Paragraph, List 核心代碼
//Chunk對象: a String, a Font, and some attributes
document.add(new Chunk("China"));
document.add(new Chunk(" "));
Font font = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);
Chunk id = new Chunk("chinese", font);
id.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
id.setTextRise(6);
document.add(id);
document.add(Chunk.NEWLINE);
document.add(new Chunk("Japan"));
document.add(new Chunk(" "));
Font font2 = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);
Chunk id2 = new Chunk("japanese", font2);
id2.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
id2.setTextRise(6);
id2.setUnderline(0.2f, -2f);
document.add(id2);
document.add(Chunk.NEWLINE);
//Phrase對象: a List of Chunks with leading
document.newPage();
document.add(new Phrase("Phrase page"));
Phrase director = new Phrase();
Chunk name = new Chunk("China");
name.setUnderline(0.2f, -2f);
director.add(name);
director.add(new Chunk(","));
director.add(new Chunk(" "));
director.add(new Chunk("chinese"));
director.setLeading(24);
document.add(director);
Phrase director2 = new Phrase();
Chunk name2 = new Chunk("Japan");
name2.setUnderline(0.2f, -2f);
director2.add(name2);
director2.add(new Chunk(","));
director2.add(new Chunk(" "));
director2.add(new Chunk("japanese"));
director2.setLeading(24);
document.add(director2);
//Paragraph對象: a Phrase with extra properties and a newline
document.newPage();
document.add(new Paragraph("Paragraph page"));
Paragraph info = new Paragraph();
info.add(new Chunk("China "));
info.add(new Chunk("chinese"));
info.add(Chunk.NEWLINE);
info.add(new Phrase("Japan "));
info.add(new Phrase("japanese"));
document.add(info);
//List對象: a sequence of Paragraphs called ListItem
document.newPage();
List list = new List(List.ORDERED);
for (int i = 0; i < 10; i++) {
ListItem item = new ListItem(String.format("%s: %d movies",
"country" + (i + 1), (i + 1) * 100), new Font(
Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE));
List movielist = new List(List.ORDERED, List.ALPHABETICAL);
movielist.setLowercase(List.LOWERCASE);
for (int j = 0; j < 5; j++) {
ListItem movieitem = new ListItem("Title" + (j + 1));
List directorlist = new List(List.UNORDERED);
for (int k = 0; k < 3; k++) {
directorlist.add(String.format("%s, %s", "Name1" + (k + 1),
"Name2" + (k + 1)));
}
movieitem.add(directorlist);
movielist.add(movieitem);
}
item.add(movielist);
list.add(item);
}
document.add(list);
複製代碼
六、插入表格
PdfPTable table = new PdfPTable(3);
PdfPCell cell;
cell = new PdfPCell(new Phrase("Cell with colspan 3"));
cell.setColspan(3);
table.addCell(cell);
cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
cell.setRowspan(2);
table.addCell(cell);
table.addCell("row 1; cell 1");
table.addCell("row 1; cell 2");
table.addCell("row 2; cell 1");
table.addCell("row 2; cell 2");
document.add(table);
複製代碼
七、表格嵌套
PdfPTable table = new PdfPTable(4);
//1行2列
PdfPTable nested1 = new PdfPTable(2);
nested1.addCell("1.1");
nested1.addCell("1.2");
//2行1列
PdfPTable nested2 = new PdfPTable(1);
nested2.addCell("2.1");
nested2.addCell("2.2");
//將表格插入到指定位置
for (int k = 0; k < 24; ++k) {
if (k == 1) {
table.addCell(nested1);
} else if (k == 20) {
table.addCell(nested2);
} else {
table.addCell("cell " + k);
}
}
document.add(table);
複製代碼
八、設置表頭
String[] bogusData = { "M0065920", "SL", "FR86000P", "PCGOLD",
"119000", "96 06", "2001-08-13", "4350", "6011648299",
"FLFLMTGP", "153", "119000.00" };
int NumColumns = 12;
// 12
PdfPTable datatable = new PdfPTable(NumColumns);
int headerwidths[] = { 9, 4, 8, 10, 8, 11, 9, 7, 9, 10, 4, 10 }; // percentage
datatable.setWidths(headerwidths);
datatable.setWidthPercentage(100);
datatable.getDefaultCell().setPadding(3);
datatable.getDefaultCell().setBorderWidth(2);
datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
datatable.addCell("Clock #");
datatable.addCell("Trans Type");
datatable.addCell("Cusip");
datatable.addCell("Long Name");
datatable.addCell("Quantity");
datatable.addCell("Fraction Price");
datatable.addCell("Settle Date");
datatable.addCell("Portfolio");
datatable.addCell("ADP Number");
datatable.addCell("Account ID");
datatable.addCell("Reg Rep ID");
datatable.addCell("Amt To Go ");
datatable.setHeaderRows(1);
//邊框
datatable.getDefaultCell().setBorderWidth(1);
//背景色
for (int i = 1; i < 1000; i++) {
for (int x = 0; x < NumColumns; x++) {
datatable.addCell(bogusData[x]);
}
}
document.add(datatable);
複製代碼
篇幅有限,若是你須要更多操做,能夠參考文章: www.cnblogs.com/liaojie970/…
若是對 Java、大數據感興趣請長按二維碼關注一波,我會努力帶給大家價值。以爲對你哪怕有一丁點幫助的請幫忙點個贊或者轉發哦。 關注公衆號**【愛編碼】,回覆2019**有相關資料哦。