Springboot outputs PDF files

Preface

There's a person (dead demand) running over to tell you, these are all output to me as a report, pdf format, so there's the following one, take notes, later useful directly come to get it. Looking online, we found that everyone is using itext.
IText is a well-known open project, a java class library for generating PDF documents. Through iText, not only PDF or rtf documents can be generated, but also XML and Html files can be transformed into PDF files.  

http://itextpdf.com/

maven dependence

        <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>

Basic operation

itext has many functions, so let's start with the basic operations. More advanced operations, you can continue to see the following.
The basic processing steps are pseudocode 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();  

1. Direct output data to pdf file

A special note here is that Chinese must specify a font, that is, 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);//Create font
            font = new Font(bf, 12);//Using fonts
            font2 = new Font(bf, 12, Font.BOLD);//Using fonts
        } 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 number: 20190701        Start date: 20190701", font));
            document.add(new Paragraph("Task Name: Wujin District 1, Changzhou     End date: 20190701", font));
            document.add(new Paragraph("Average flight altitude: 100 m        Average flight speed: 100 km/h", font));
            document.add(new Paragraph("Task area: 1000㎡      End date: 20190701", font));
            document.add(new Paragraph("Total length of flight: 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);//Create font
            font = new Font(bf, 12);//Using fonts
            font2 = new Font(bf, 12, Font.BOLD);//Using fonts
        } 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();
            float documentHeight = documentWidth / 580 * 320;//Reset width and height
            png.scaleAbsolute(documentWidth, documentHeight);//Reset width and height
            png.scalePercent(50);
            // Scale pictures by domain size
//            image.scaleToFit(signRect.getWidth(), signRect.getHeight());
            png.setAlignment(Image.ALIGN_CENTER);
            document.add(png);
            document.add(new Paragraph("Task number:" + missionReport.getMissionCode() + ",Start date:" + finalReport.getStartTime(), font));
            document.add(new Paragraph("Task name:" + missionReport.getMissionName() + ",Ending date:" + finalReport.getEndTime(), font));
            document.add(new Paragraph("Average flight altitude:" + finalReport.getAvgFlightHeight() + "m" + ",Average flight speed:" + finalReport.getAvgFlightSpeed() + "km/h", font));
            document.add(new Paragraph("Task area:" + finalReport.getMissionArea() + "㎡" + ",Total length of flight:" + 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("generate PDF Failure:" + 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\":\"Desheng navigation point M008\",\"missionStatus\":1,\"missionType\":0,\"plannedFlightTime\":\"20190909\"}";
        MissionReportTb missionReportTb = JSONObject.parseObject(report, MissionReportTb.class);
        exportReport(missionReportTb);
    }

}

2. Generate pdf files from templates and export them

First you make a pdf template:

1. Make template interface with word first

2. Files are saved in pdf format

3. Open the pdf file just converted into word by Adobe Acrobat pro software. (Note: If there is no software that can be downloaded through my Baidu cloud, link: http://pan.baidu.com/s/1pL2klzt ) If you can't download it, you can go to Google.

4. Click the "Prepare Form" button on the right and select "Test. pdf" to start.

Go into the edit page, open it, it will automatically detect and name the form field, right-click the form field, click on the properties, appear the text field properties dialog box (actually no operation, generally do not need to modify anything, at least I did not modify oh). If you want to modify fill1 and other information, you can modify it.

5. After completing the above work, you can store pdf directly by "save as"

The above part is the operation of making pdf template. After the above-mentioned completion, we begin to generate pdf files by program according to pdf template. Upon java program:

public class Snippet {
// Generating pdf by template
    public static void fillTemplate() {
// Template path
        String templatePath = "E:/Test 3.pdf";
// Generated new file path
        String newPDFPath = "E:/ceshi.pdf";
        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            out = new FileOutputStream(newPDFPath);// Output stream
            reader = new PdfReader(templatePath);// Read 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 City, 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 it's false, then the generated PDF file can be edited. Make sure it's 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();
    }
}

The results are as follows.

More operations

1. Page size, page background color, margin blank, Title,Author,Subject,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 property  
doc.addTitle("Title@sample");  
doc.addAuthor("Author@rensanning");  
doc.addSubject("Subject@iText sample");  
doc.addKeywords("Keywords@iText");  
doc.addCreator("Creator@iText");  
  
//Margins  
doc.setMargins(10, 20, 30, 40);  
  
doc.open();  
doc.add(new Paragraph("Hello World")); 

Output results:

2. Setting 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"));  

Output results:

3. Adding 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"));  

4. Watermarking (background image)

//Picture 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 watermarking  
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 map  
Image img2 = Image.getInstance("resource/test.jpg");  
img2.setAbsolutePosition(0, 0);  
PdfContentByte under2 = stamp.getUnderContent(3);  
under2.addImage(img2);  
  
stamp.close();  
reader.close();  

5. Insert Chunk, Phrase, Paragraph, List
Core code

//Chunk objects: 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 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.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 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);  
  
//List object: 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);  

6. Insert tables

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);  

7. Form nesting

PdfPTable table = new PdfPTable(4);  
  
//1 rows and 2 columns  
PdfPTable nested1 = new PdfPTable(2);  
nested1.addCell("1.1");  
nested1.addCell("1.2");  
  
//2 rows and 1 columns  
PdfPTable nested2 = new PdfPTable(1);  
nested2.addCell("2.1");  
nested2.addCell("2.2");  
  
//Insert the table into the specified location  
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);  

8. Setting 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);  
  
//Frame  
datatable.getDefaultCell().setBorderWidth(1);  
  
//Background color  
for (int i = 1; i < 1000; i++) {  
    for (int x = 0; x < NumColumns; x++) {  
        datatable.addCell(bogusData[x]);  
    }  
}  
  
document.add(datatable);

Limited space, if you need more operation, you can refer to the article:
https://www.cnblogs.com/liaojie970/p/7132475.html

Last

If you are interested in Java and big data, please follow the wave of two-dimensional code for a long time, and I will try to bring you value. If you feel that even a little help to you, please give me a compliment or forward it.
Pay attention to the public number "Love Code" and reply to the relevant information in 2019.

Keywords: Java xml Maven Google

Added by desmond_ckl on Wed, 25 Sep 2019 16:06:35 +0300