preface
Someone came up to you and said, all of this is for me to output as a report, PDF format, so there is the following, take notes, later useful directly come to get. I looked on the Internet and found that everyone was using IText. IText, a well-known open project, is a Java class library for generating PDF documents. IText can not only generate PDF or RTF documents, but also convert XML and Html files to PDF files.
itextpdf.com/
Maven rely on
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>Copy the code
Basic operation
Itext has a lot of functionality, but I’ll start with the basic operations. For more advanced operations, see below. The basic processing steps are as follows:
//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 ();Copy the code
1. Output data directly to PDF files
A special note here is that Chinese must specify the font, namely BaseFont
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); // use Font 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("Flight Report of Changzhou Wujin Area 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("Task No. : 20190701 Start Date: 20190701", font));
document.add(new Paragraph("Task Name: Changzhou Wujin Zone 1 End Date: 20190701", font));
document.add(new Paragraph("Average altitude: 100m Average speed: 100km/h", font));
document.add(new Paragraph("Task Area: 1000㎡ End Date: 20190701", font));
document.add(new Paragraph("Total flying time: 1000㎡", font));
document.addCreationDate();
document.close();
} catch (Exception e) {
System.out.println("file create exception"); }} /** * Generate PDF file ** @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); // use Font 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() + "Flight report", 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();
floatdocumentHeight = documentWidth / 580 * 320; // Reset 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("Task No. :" + missionReport.getMissionCode() + ", start date:" + finalReport.getStartTime(), font));
document.add(new Paragraph("Task Name:" + missionReport.getMissionName() + , end date:" + finalReport.getEndTime(), font));
document.add(new Paragraph("Average flying altitude:" + finalReport.getAvgFlightHeight() + "m" + ", average flight speed:" + finalReport.getAvgFlightSpeed() + "km/h", font));
document.add(new Paragraph("Mission area:" + finalReport.getMissionArea() + "㎡" + ", total flight duration:" + 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(Failed to generate PDF: + e.getMessage());
}
return pdfPath;
}
public static void main(String[] args) throws AirNaviException {
String report = "{\" detailMissionReport \ ": [{\" avgFlightHeight \ ": 119.7, \" avgFlightSpeed \ ": 71.1, \" the endPoint \ ": \" 113.27484, 22.86843 \ ", \ "endT ime\":\"2019-09-17 FlightDuration 17:47:07 \ ", \ "\" : 9, \ "reportID \" : 1, \ "the startPoint \", \ "113.31429, 22.78240 \" and \ "startTime \" : \ "in the 2019-09-17 s StatisticsTimes 17:38:03 \ ", \ "\" : 505}], \ "missionReport \" : {\ "avgFlightHeight \" : 119.7, \ "avgFlightSpeed \" : 71.1, \ "the endPoint \" : \ "113.31429, 22.78240 \" and \ "endTime \" : \ "in the 2019-09-17 s FlightDuration 17:47:07 \ ", \ "\" : 9, \ "reportID \" : 1, \ "the startPoint \", \ "113.31429, 22.78240 \" and \ "startTime \" : \ "in the 2019-09-17 s StatisticsTimes 17:38:03 \ ", \ "\" : 0}, \ "missionArea \ missionCode" : 0.0, \ '\ ", \ "M001 \" and \ "888813 ddef6646cd9bfaba5ab missionID \", \" MissionName b748a43 \ ", \ "\", \ "DE sheng waypoint M008 \" and \ "missionStatus \ missionType" : 1, \ "\" : 0, \ "plannedFlightTime \" : \ "20190909 \"}";
MissionReportTb missionReportTb = JSONObject.parseObject(report, MissionReportTb.class);
exportReport(missionReportTb); }}Copy the code
2. Generate a PDF file based on the template and export it
First you need to create a PDF template:
1. Make the template interface in Word first
2. Save the file as a PDF file
3. Use Adobe Acrobat Pro software to open the PDF file you just converted into Word (note: if you don’t have this software, you can download it through my Baidu cloud, link: pan.baidu.com/s/1pL2klzt)…
4. Click the “Prepare form” button on the right and select “test.pdf” to start
Enter the edit page, it will automatically detect and name the form field, right click the form field, click properties, the text field properties dialog box (in fact, there is no operation, generally do not need to modify anything, at least I did not modify oh. If you want to change fill1 and so on, you can do that.)
5. After you’ve done the above, just “save as” and save the PDF
The above part is to make a PDF template operation, after the above completion, start to generate PDF files according to the PDF template through the program, Java program:
public class Snippet {
// Use the template to generate PDF
public static void fillTemplate(a) {
// Template path
String templatePath = "PDF" E: / test 3.;
// The path to the generated new file
String newPDFPath = "E:/ceshi.pdf";
PdfReader reader;
FileOutputStream out;
ByteArrayOutputStream bos;
PdfStamper stamper;
try {
out = new FileOutputStream(newPDFPath);/ / the output stream
reader = new PdfReader(templatePath);// Read the PDF template
bos = new ByteArrayOutputStream();
stamper = new PdfStamper(reader, bos);
AcroFields form = stamper.getAcroFields();
String[] str = {"123456789"."TOP__ONE"."Male"."1991-01-01"."130222111133338888"."Baoding, Hebei Province"};
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);// If false, the generated PDF file can be edited
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(); }}Copy the code
The result is as follows
More operations
1, page size, page background color, margin, the Title, Author, Subject, and Keywords
Core code:
// Page size
Rectangle rect = new Rectangle(PageSize.B5.rotate());
// Page background color
rect.setBackgroundColor(BaseColor.ORANGE);
Document doc = new Document(rect);
PdfWriter writer = PdfWriter.getInstance(doc, out);
//PDF version (default 1.4)
writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2);
// Document attributes
doc.addTitle("Title@sample");
doc.addAuthor("Author@rensanning");
doc.addSubject("Subject@iText sample");
doc.addKeywords("Keywords@iText");
doc.addCreator("Creator@iText");
// The margins are blank
doc.setMargins(10.20.30.40);
doc.open();
doc.add(new Paragraph("Hello World"));
Copy the code
Output result:
2. Set a password
Core code:
PdfWriter writer = PdfWriter.getInstance(doc, out);
// Set the password to "World".
writer.setEncryption("Hello".getBytes(), "World".getBytes(),
PdfWriter.ALLOW_SCREENREADERS,
PdfWriter.STANDARD_ENCRYPTION_128);
doc.open();
doc.add(new Paragraph("Hello World"));
Copy the code
Output result:
3, add Page core code:
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"));
Copy the code
4. Add watermark (background image)
// Image watermark
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);
// Text watermark
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();
/ / background
Image img2 = Image.getInstance("resource/test.jpg");
img2.setAbsolutePosition(0.0);
PdfContentByte under2 = stamp.getUnderContent(3);
under2.addImage(img2);
stamp.close();
reader.close();
Copy the code
5. Insert Chunk, Phrase, Paragraph, List core codes
//Chunk object: 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.5 f.1f.1.5 f);
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.5 f.1f.1.5 f);
id2.setTextRise(6);
id2.setUnderline(0.2 f, -2f);
document.add(id2);
document.add(Chunk.NEWLINE);
//Phrase Object: 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.2 f, -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.2 f, -2f);
director2.add(name2);
director2.add(new Chunk(","));
director2.add(new Chunk(""));
director2.add(new Chunk("japanese"));
director2.setLeading(24);
document.add(director2);
//Paragraph object: 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);
// a List 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);
Copy the code
Insert table
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);
Copy the code
7. Table nesting
PdfPTable table = new PdfPTable(4); PdfPTable nested1 = new PdfPTable(2); nested1.addCell("1.1");
nested1.addCell("1.2"); PdfPTable nested2 = new PdfPTable(1); nested2.addCell("2.1");
nested2.addCell("2.2"); // Insert the table into the specified positionfor (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);
Copy the code
8. Set the table header
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); / / border datatable. GetDefaultCell (.) setBorderWidth (1); / / the background colorfor (int i = 1; i < 1000; i++) {
for (int x = 0; x < NumColumns; x++) {
datatable.addCell(bogusData[x]);
}
}
document.add(datatable);
Copy the code
Space is limited, if you need more action, can refer to the article: www.cnblogs.com/liaojie970/…
The last
If you are interested in Java and big data, please long press the QR code to follow the wave, I will try to bring you value. If you feel that you have a little help, please help to like or forward oh. Pay attention to the public number ** [love code], reply 2019** has relevant information oh.